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