libsidplayfp  1.6.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 {
43  inline bool casecompare(char c1, char c2) { return (tolower(c1) == tolower(c2)); }
44 
48  inline bool equal(const std::string& s1, const std::string& s2)
49  {
50  return s1.size() == s2.size()
51  && std::equal(s1.begin(), s1.end(), s2.begin(), casecompare);
52  }
53 
57  inline bool equal(const char* s1, const char* s2)
58  {
59 
60 #if defined(HAVE_STRCASECMP)
61  return strcasecmp(s1, s2) == 0;
62 #elif defined(HAVE_STRICMP)
63  return stricmp(s1, s2) == 0;
64 #else
65  if (s1 == s2)
66  return true;
67 
68  if (s1 == 0 || s2 == 0)
69  return false;
70 
71  while ((*s1 != '\0') || (*s2 != '\0'))
72  {
73  if (!casecompare(*s1, *s2))
74  return false;
75  ++s1;
76  ++s2;
77  }
78 
79  return true;
80 #endif
81  }
82 
86  inline bool equal(const char* s1, const char* s2, size_t n)
87  {
88 
89 #if defined(HAVE_STRNCASECMP)
90  return strncasecmp(s1, s2, n) == 0;
91 #elif defined(HAVE_STRNICMP)
92  return strnicmp(s1, s2, n) == 0;
93 #else
94  if (s1 == s2 || n == 0)
95  return true;
96 
97  if (s1 == 0 || s2 == 0)
98  return false;
99 
100  while (n-- && ((*s1 != '\0') || (*s2 != '\0')))
101  {
102  if (!casecompare(*s1, *s2))
103  return false;
104  ++s1;
105  ++s2;
106  }
107 
108  return true;
109 #endif
110  }
111 }
112 
113 #endif
Definition: stringutils.h:41