]> git.lizzy.rs Git - dragonfireclient.git/blob - src/util/string.h
dc520e3a8947c91e8183873b68fe1d0bb611ccd5
[dragonfireclient.git] / src / util / string.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifndef UTIL_STRING_HEADER
21 #define UTIL_STRING_HEADER
22
23 #include "irrlichttypes_bloated.h"
24 #include <stdlib.h>
25 #include <string>
26 #include <cstring>
27 #include <vector>
28 #include <sstream>
29 #include <cctype>
30
31 #define STRINGIFY(x) #x
32 #define TOSTRING(x) STRINGIFY(x)
33
34 struct FlagDesc {
35         const char *name;
36         u32 flag;
37 };
38
39
40 // You must free the returned string!
41 // The returned string is allocated using new
42 wchar_t *narrow_to_wide_c(const char *str);
43
44 std::wstring narrow_to_wide(const std::string &mbs);
45 std::string wide_to_narrow(const std::wstring &wcs);
46 std::string translatePassword(std::string playername, std::wstring password);
47 std::string urlencode(std::string str);
48 std::string urldecode(std::string str);
49 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask);
50 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask);
51 size_t mystrlcpy(char *dst, const char *src, size_t size);
52 char *mystrtok_r(char *s, const char *sep, char **lasts);
53 u64 read_seed(const char *str);
54 bool parseColorString(const std::string &value, video::SColor &color, bool quiet);
55
56
57 /**
58  * Returns a copy of \p str with spaces inserted at the right hand side to ensure
59  * that the string is \p len characters in length. If \p str is <= \p len then the
60  * returned string will be identical to str.
61  */
62 inline std::string padStringRight(std::string str, size_t len)
63 {
64         if (len > str.size())
65                 str.insert(str.end(), len - str.size(), ' ');
66
67         return str;
68 }
69
70 /**
71  * Returns a version of \p str with the first occurrence of a string
72  * contained within ends[] removed from the end of the string.
73  *
74  * @param str
75  * @param ends A NULL- or ""- terminated array of strings to remove from s in
76  *      the copy produced.  Note that once one of these strings is removed
77  *      that no further postfixes contained within this array are removed.
78  *
79  * @return If no end could be removed then "" is returned.
80  */
81 inline std::string removeStringEnd(const std::string &str,
82                 const char *ends[])
83 {
84         const char **p = ends;
85
86         for (; *p && (*p)[0] != '\0'; p++) {
87                 std::string end = *p;
88                 if (str.size() < end.size())
89                         continue;
90                 if (str.compare(str.size() - end.size(), end.size(), end) == 0)
91                         return str.substr(0, str.size() - end.size());
92         }
93
94         return "";
95 }
96
97
98 /**
99  * Check two strings for equivalence.  If \p case_insensitive is true
100  * then the case of the strings is ignored (default is false).
101  *
102  * @param s1
103  * @param s2
104  * @param case_insensitive
105  * @return true if the strings match
106  */
107 template <typename T>
108 inline bool str_equal(const std::basic_string<T> &s1,
109                 const std::basic_string<T> &s2,
110                 bool case_insensitive = false)
111 {
112         if (!case_insensitive)
113                 return s1 == s2;
114
115         if (s1.size() != s2.size())
116                 return false;
117
118         for (size_t i = 0; i < s1.size(); ++i)
119                 if(tolower(s1[i]) != tolower(s2[i]))
120                         return false;
121
122         return true;
123 }
124
125
126 /**
127  * Check whether \p str begins with the string prefix. If \p case_insensitive
128  * is true then the check is case insensitve (default is false; i.e. case is
129  * significant).
130  *
131  * @param str
132  * @param prefix
133  * @param case_insensitive
134  * @return true if the str begins with prefix
135  */
136 template <typename T>
137 inline bool str_starts_with(const std::basic_string<T> &str,
138                 const std::basic_string<T> &prefix,
139                 bool case_insensitive = false)
140 {
141         if (str.size() < prefix.size())
142                 return false;
143
144         if (!case_insensitive)
145                 return str.compare(0, prefix.size(), prefix) == 0;
146
147         for (size_t i = 0; i < prefix.size(); ++i)
148                 if (tolower(str[i]) != tolower(prefix[i]))
149                         return false;
150         return true;
151 }
152
153
154 /**
155  * Splits a string into its component parts separated by the character
156  * \p delimiter.
157  *
158  * @return An std::vector<std::basic_string<T> > of the component parts
159  */
160 template <typename T>
161 inline std::vector<std::basic_string<T> > str_split(
162                 const std::basic_string<T> &str,
163                 T delimiter)
164 {
165         std::vector<std::basic_string<T> > parts;
166         std::basic_stringstream<T> sstr(str);
167         std::basic_string<T> part;
168
169         while (std::getline(sstr, part, delimiter))
170                 parts.push_back(part);
171
172         return parts;
173 }
174
175
176 /**
177  * @param str
178  * @return A copy of \p str converted to all lowercase characters.
179  */
180 inline std::string lowercase(const std::string &str)
181 {
182         std::string s2;
183
184         s2.reserve(str.size());
185
186         for (size_t i = 0; i < str.size(); i++)
187                 s2 += tolower(str[i]);
188
189         return s2;
190 }
191
192
193 /**
194  * @param str
195  * @return A copy of \p str with leading and trailing whitespace removed.
196  */
197 inline std::string trim(const std::string &str)
198 {
199         size_t front = 0;
200
201         while (std::isspace(str[front]))
202                 ++front;
203
204         size_t back = str.size();
205         while (back > front && std::isspace(str[back - 1]))
206                 --back;
207
208         return str.substr(front, back - front);
209 }
210
211
212 /**
213  * Returns whether \p str should be regarded as (bool) true.  Case and leading
214  * and trailing whitespace are ignored.  Values that will return
215  * true are "y", "yes", "true" and any number that is not 0.
216  * @param str
217  */
218 inline bool is_yes(const std::string &str)
219 {
220         std::string s2 = lowercase(trim(str));
221
222         return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0;
223 }
224
225
226 /**
227  * Converts the string \p str to a signed 32-bit integer. The converted value
228  * is constrained so that min <= value <= max.
229  *
230  * @see atoi(3) for limitations
231  *
232  * @param str
233  * @param min Range minimum
234  * @param max Range maximum
235  * @return The value converted to a signed 32-bit integer and constrained
236  *      within the range defined by min and max (inclusive)
237  */
238 inline s32 mystoi(const std::string &str, s32 min, s32 max)
239 {
240         s32 i = atoi(str.c_str());
241
242         if (i < min)
243                 i = min;
244         if (i > max)
245                 i = max;
246
247         return i;
248 }
249
250
251 /// Returns a 64-bit value represented by the string \p str (decimal).
252 inline s64 stoi64(const std::string &str)
253 {
254         std::stringstream tmp(str);
255         s64 t;
256         tmp >> t;
257         return t;
258 }
259
260 // MSVC2010 includes it's own versions of these
261 //#if !defined(_MSC_VER) || _MSC_VER < 1600
262
263
264 /**
265  * Returns a 32-bit value reprensented by the string \p str (decimal).
266  * @see atoi(3) for further limitations
267  */
268 inline s32 mystoi(const std::string &str)
269 {
270         return atoi(str.c_str());
271 }
272
273
274 /**
275  * Returns s 32-bit value represented by the wide string \p str (decimal).
276  * @see atoi(3) for further limitations
277  */
278 inline s32 mystoi(const std::wstring &str)
279 {
280         return mystoi(wide_to_narrow(str));
281 }
282
283
284 /**
285  * Returns a float reprensented by the string \p str (decimal).
286  * @see atof(3)
287  */
288 inline float mystof(const std::string &str)
289 {
290         return atof(str.c_str());
291 }
292
293 //#endif
294
295 #define stoi mystoi
296 #define stof mystof
297
298 // TODO: Replace with C++11 std::to_string.
299
300 /// Returns A string representing the value \p val.
301 template <typename T>
302 inline std::string to_string(T val)
303 {
304         std::ostringstream oss;
305         oss << val;
306         return oss.str();
307 }
308
309 /// Returns a string representing the decimal value of the 32-bit value \p i.
310 inline std::string itos(s32 i) { return to_string(i); }
311 /// Returns a string representing the decimal value of the 64-bit value \p i.
312 inline std::string i64tos(s64 i) { return to_string(i); }
313 /// Returns a string representing the decimal value of the float value \p f.
314 inline std::string ftos(float f) { return to_string(f); }
315
316
317 /**
318  * Replace all occurrences of \p pattern in \p str with \p replacement.
319  *
320  * @param str String to replace pattern with replacement within.
321  * @param pattern The pattern to replace.
322  * @param replacement What to replace the pattern with.
323  */
324 inline void str_replace(std::string &str, const std::string &pattern,
325                 const std::string &replacement)
326 {
327         std::string::size_type start = str.find(pattern, 0);
328         while (start != str.npos) {
329                 str.replace(start, pattern.size(), replacement);
330                 start = str.find(pattern, start + replacement.size());
331         }
332 }
333
334
335 /**
336  * Replace all occurrences of the character \p from in \p str with \p to.
337  *
338  * @param str The string to (potentially) modify.
339  * @param from The character in str to replace.
340  * @param to The replacement character.
341  */
342 void str_replace(std::string &str, char from, char to);
343
344
345 /**
346  * Check that a string only contains whitelisted characters. This is the
347  * opposite of string_allowed_blacklist().
348  *
349  * @param str The string to be checked.
350  * @param allowed_chars A string containing permitted characters.
351  * @return true if the string is allowed, otherwise false.
352  *
353  * @see string_allowed_blacklist()
354  */
355 inline bool string_allowed(const std::string &str, const std::string &allowed_chars)
356 {
357         return str.find_first_not_of(allowed_chars) == str.npos;
358 }
359
360
361 /**
362  * Check that a string contains no blacklisted characters. This is the
363  * opposite of string_allowed().
364  *
365  * @param str The string to be checked.
366  * @param blacklisted_chars A string containing prohibited characters.
367  * @return true if the string is allowed, otherwise false.
368
369  * @see string_allowed()
370  */
371 inline bool string_allowed_blacklist(const std::string &str,
372                 const std::string &blacklisted_chars)
373 {
374         return str.find_first_of(blacklisted_chars) == str.npos;
375 }
376
377
378 /**
379  * Create a string based on \p from where a newline is forcefully inserted
380  * every \p row_len characters.
381  *
382  * @note This function does not honour word wraps and blindy inserts a newline
383  *      every \p row_len characters whether it breaks a word or not.  It is
384  *      intended to be used for, for example, showing paths in the GUI.
385  *
386  * @param from The string to be wrapped into rows.
387  * @param row_len The row length (in characters).
388  * @return A new string with the wrapping applied.
389  */
390 inline std::string wrap_rows(const std::string &from,
391                 unsigned row_len)
392 {
393         std::string to;
394
395         for (size_t i = 0; i < from.size(); i++) {
396                 if (i != 0 && i % row_len == 0)
397                         to += '\n';
398                 to += from[i];
399         }
400
401         return to;
402 }
403
404
405 /**
406  * Removes backslashes from an escaped string (FormSpec strings)
407  */
408 template <typename T>
409 inline std::basic_string<T> unescape_string(std::basic_string<T> &s)
410 {
411         std::basic_string<T> res;
412
413         for (size_t i = 0; i < s.length(); i++) {
414                 if (s[i] == '\\') {
415                         i++;
416                         if (i >= s.length())
417                                 break;
418                 }
419                 res += s[i];
420         }
421
422         return res;
423 }
424
425
426 /**
427  * Checks that all characters in \p to_check are a decimal digits.
428  *
429  * @param to_check
430  * @return true if to_check is not empty and all characters in to_check are
431  *      decimal digits, otherwise false
432  */
433 inline bool is_number(const std::string &to_check)
434 {
435         for (size_t i = 0; i < to_check.size(); i++)
436                 if (!std::isdigit(to_check[i]))
437                         return false;
438
439         return !to_check.empty();
440 }
441
442
443 /**
444  * Returns a C-string, either "true" or "false", corresponding to \p val.
445  *
446  * @return If \p val is true, then "true" is returned, otherwise "false".
447  */
448 inline const char *bool_to_cstr(bool val)
449 {
450         return val ? "true" : "false";
451 }
452
453 #endif