libsidplayfp  1.4.2
stringutils.h
1 /*
2  * This file is part of libsidplayfp, a SID player engine.
3  *
4  * Copyright 2013 Leandro Nini
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #ifndef STRINGUTILS_H
22 #define STRINGUTILS_H
23 
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27 
28 #if defined(HAVE_STRCASECMP) || defined (HAVE_STRNCASECMP)
29 # include <strings.h>
30 #endif
31 
32 #if defined(HAVE_STRICMP) || defined (HAVE_STRNICMP)
33 # include <string.h>
34 #endif
35 
36 #include <cctype>
37 #include <algorithm>
38 #include <string>
39 
40 
42 {
43 private:
44  static bool casecompare(char c1, char c2) { return (tolower(c1)==tolower(c2)); }
45 
46 public:
47  static bool equal(const std::string& s1, const std::string& s2)
48  {
49  return s1.size() == s2.size()
50  && std::equal(s1.begin(), s1.end(), s2.begin(), casecompare);
51  }
52 
53  static bool equal(const char* s1, const char* s2)
54  {
55 
56 #if defined(HAVE_STRCASECMP)
57  return strcasecmp(s1, s2) == 0;
58 #elif defined(HAVE_STRICMP)
59  return stricmp(s1, s2) == 0;
60 #else
61  if (s1 == s2)
62  return true;
63 
64  if (s1 == 0 || s2 == 0)
65  return false;
66 
67  while ((*s1 != '\0') || (*s2 != '\0'))
68  {
69  if (!casecompare(*s1, *s2))
70  return false;
71  ++s1;
72  ++s2;
73  }
74 
75  return true;
76 #endif
77  }
78 
79  static bool equal(const char* s1, const char* s2, size_t n)
80  {
81 
82 #if defined(HAVE_STRNCASECMP)
83  return strncasecmp(s1, s2, n) == 0;
84 #elif defined(HAVE_STRNICMP)
85  return strnicmp(s1, s2, n) == 0;
86 #else
87  if (s1 == s2 || n == 0)
88  return true;
89 
90  if (s1 == 0 || s2 == 0)
91  return false;
92 
93  while (n-- && ((*s1 != '\0') || (*s2 != '\0')))
94  {
95  if (!casecompare(*s1, *s2))
96  return false;
97  ++s1;
98  ++s2;
99  }
100 
101  return true;
102 #endif
103  }
104 };
105 
106 #endif
Definition: stringutils.h:41