libsidplayfp  2.0.2
stringutils.h
1 /*
2  * This file is part of libsidplayfp, a SID player engine.
3  *
4  * Copyright 2013-2014 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 
41 namespace stringutils
42 {
46  inline bool casecompare(char c1, char c2) { return (tolower(c1) == tolower(c2)); }
47 
53  inline bool equal(const std::string& s1, const std::string& s2)
54  {
55  return s1.size() == s2.size()
56  && std::equal(s1.begin(), s1.end(), s2.begin(), casecompare);
57  }
58 
64  inline bool equal(const char* s1, const char* s2)
65  {
66 #if defined(HAVE_STRCASECMP)
67  return strcasecmp(s1, s2) == 0;
68 #elif defined(HAVE_STRICMP)
69  return stricmp(s1, s2) == 0;
70 #else
71  if (s1 == s2)
72  return true;
73 
74  if (s1 == 0 || s2 == 0)
75  return false;
76 
77  while ((*s1 != '\0') || (*s2 != '\0'))
78  {
79  if (!casecompare(*s1, *s2))
80  return false;
81  ++s1;
82  ++s2;
83  }
84 
85  return true;
86 #endif
87  }
88 
94  inline bool equal(const char* s1, const char* s2, size_t n)
95  {
96 #if defined(HAVE_STRNCASECMP)
97  return strncasecmp(s1, s2, n) == 0;
98 #elif defined(HAVE_STRNICMP)
99  return strnicmp(s1, s2, n) == 0;
100 #else
101  if (s1 == s2 || n == 0)
102  return true;
103 
104  if (s1 == 0 || s2 == 0)
105  return false;
106 
107  while (n-- && ((*s1 != '\0') || (*s2 != '\0')))
108  {
109  if (!casecompare(*s1, *s2))
110  return false;
111  ++s1;
112  ++s2;
113  }
114 
115  return true;
116 #endif
117  }
118 }
119 
120 #endif