libsidplayfp 2.15.0
stringutils.h
1/*
2 * This file is part of libsidplayfp, a SID player engine.
3 *
4 * Copyright 2013-2023 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(_WIN32)
29# include <string.h>
30#elif defined(HAVE_STRCASECMP) || defined (HAVE_STRNCASECMP)
31# include <strings.h>
32#endif
33
34#include <cctype>
35#include <algorithm>
36#include <string>
37
38
39namespace stringutils
40{
44 inline bool casecompare(char c1, char c2) { return (tolower(c1) == tolower(c2)); }
45
51 inline bool equal(const std::string& s1, const std::string& s2)
52 {
53 return s1.size() == s2.size()
54 && std::equal(s1.begin(), s1.end(), s2.begin(), casecompare);
55 }
56
62 inline bool equal(const char* s1, const char* s2)
63 {
64#if defined(_WIN32)
65 return _stricmp(s1, s2) == 0;
66#elif defined(HAVE_STRCASECMP)
67 return strcasecmp(s1, s2) == 0;
68#else
69 if (s1 == s2)
70 return true;
71
72 if (s1 == 0 || s2 == 0)
73 return false;
74
75 while ((*s1 != '\0') || (*s2 != '\0'))
76 {
77 if (!casecompare(*s1, *s2))
78 return false;
79 ++s1;
80 ++s2;
81 }
82
83 return true;
84#endif
85 }
86
92 inline bool equal(const char* s1, const char* s2, size_t n)
93 {
94#if defined(_WIN32)
95 return _strnicmp(s1, s2, n) == 0;
96#elif defined(HAVE_STRNCASECMP)
97 return strncasecmp(s1, s2, n) == 0;
98#else
99 if (s1 == s2 || n == 0)
100 return true;
101
102 if (s1 == 0 || s2 == 0)
103 return false;
104
105 while (n-- && ((*s1 != '\0') || (*s2 != '\0')))
106 {
107 if (!casecompare(*s1, *s2))
108 return false;
109 ++s1;
110 ++s2;
111 }
112
113 return true;
114#endif
115 }
116}
117
118#endif