libsidplayfp  1.8.7
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 
67 #if defined(HAVE_STRCASECMP)
68  return strcasecmp(s1, s2) == 0;
69 #elif defined(HAVE_STRICMP)
70  return stricmp(s1, s2) == 0;
71 #else
72  if (s1 == s2)
73  return true;
74 
75  if (s1 == 0 || s2 == 0)
76  return false;
77 
78  while ((*s1 != '\0') || (*s2 != '\0'))
79  {
80  if (!casecompare(*s1, *s2))
81  return false;
82  ++s1;
83  ++s2;
84  }
85 
86  return true;
87 #endif
88  }
89 
95  inline bool equal(const char* s1, const char* s2, size_t n)
96  {
97 
98 #if defined(HAVE_STRNCASECMP)
99  return strncasecmp(s1, s2, n) == 0;
100 #elif defined(HAVE_STRNICMP)
101  return strnicmp(s1, s2, n) == 0;
102 #else
103  if (s1 == s2 || n == 0)
104  return true;
105 
106  if (s1 == 0 || s2 == 0)
107  return false;
108 
109  while (n-- && ((*s1 != '\0') || (*s2 != '\0')))
110  {
111  if (!casecompare(*s1, *s2))
112  return false;
113  ++s1;
114  ++s2;
115  }
116 
117  return true;
118 #endif
119  }
120 }
121 
122 #endif
Definition: stringutils.h:41