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