Fix MSVC build broken by 34d32ce
[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 "cpp11_container.h"
25 #include <stdlib.h>
26 #include <string>
27 #include <cstring>
28 #include <vector>
29 #include <map>
30 #include <sstream>
31 #include <iomanip>
32 #include <cctype>
33
34 #define STRINGIFY(x) #x
35 #define TOSTRING(x) STRINGIFY(x)
36
37 // Checks whether a value is an ASCII printable character
38 #define IS_ASCII_PRINTABLE_CHAR(x)   \
39         (((unsigned int)(x) >= 0x20) &&  \
40         ( (unsigned int)(x) <= 0x7e))
41
42 // Checks whether a byte is an inner byte for an utf-8 multibyte sequence
43 #define IS_UTF8_MULTB_INNER(x)       \
44         (((unsigned char)(x) >= 0x80) && \
45         ( (unsigned char)(x) <= 0xbf))
46
47 // Checks whether a byte is a start byte for an utf-8 multibyte sequence
48 #define IS_UTF8_MULTB_START(x)       \
49         (((unsigned char)(x) >= 0xc2) && \
50         ( (unsigned char)(x) <= 0xf4))
51
52 // Given a start byte x for an utf-8 multibyte sequence
53 // it gives the length of the whole sequence in bytes.
54 #define UTF8_MULTB_START_LEN(x)            \
55         (((unsigned char)(x) < 0xe0) ? 2 :     \
56         (((unsigned char)(x) < 0xf0) ? 3 : 4))
57
58 typedef UNORDERED_MAP<std::string, std::string> StringMap;
59
60 struct FlagDesc {
61         const char *name;
62         u32 flag;
63 };
64
65 // try not to convert between wide/utf8 encodings; this can result in data loss
66 // try to only convert between them when you need to input/output stuff via Irrlicht
67 std::wstring utf8_to_wide(const std::string &input);
68 std::string wide_to_utf8(const std::wstring &input);
69
70 wchar_t *utf8_to_wide_c(const char *str);
71
72 // NEVER use those two functions unless you have a VERY GOOD reason to
73 // they just convert between wide and multibyte encoding
74 // multibyte encoding depends on current locale, this is no good, especially on Windows
75
76 // You must free the returned string!
77 // The returned string is allocated using new
78 wchar_t *narrow_to_wide_c(const char *str);
79 std::wstring narrow_to_wide(const std::string &mbs);
80 std::string wide_to_narrow(const std::wstring &wcs);
81
82 std::string urlencode(const std::string &str);
83 std::string urldecode(const std::string &str);
84 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask);
85 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask);
86 size_t mystrlcpy(char *dst, const char *src, size_t size);
87 char *mystrtok_r(char *s, const char *sep, char **lasts);
88 u64 read_seed(const char *str);
89 bool parseColorString(const std::string &value, video::SColor &color, bool quiet);
90
91
92 /**
93  * Returns a copy of \p str with spaces inserted at the right hand side to ensure
94  * that the string is \p len characters in length. If \p str is <= \p len then the
95  * returned string will be identical to str.
96  */
97 inline std::string padStringRight(std::string str, size_t len)
98 {
99         if (len > str.size())
100                 str.insert(str.end(), len - str.size(), ' ');
101
102         return str;
103 }
104
105 /**
106  * Returns a version of \p str with the first occurrence of a string
107  * contained within ends[] removed from the end of the string.
108  *
109  * @param str
110  * @param ends A NULL- or ""- terminated array of strings to remove from s in
111  *      the copy produced.  Note that once one of these strings is removed
112  *      that no further postfixes contained within this array are removed.
113  *
114  * @return If no end could be removed then "" is returned.
115  */
116 inline std::string removeStringEnd(const std::string &str,
117                 const char *ends[])
118 {
119         const char **p = ends;
120
121         for (; *p && (*p)[0] != '\0'; p++) {
122                 std::string end = *p;
123                 if (str.size() < end.size())
124                         continue;
125                 if (str.compare(str.size() - end.size(), end.size(), end) == 0)
126                         return str.substr(0, str.size() - end.size());
127         }
128
129         return "";
130 }
131
132
133 /**
134  * Check two strings for equivalence.  If \p case_insensitive is true
135  * then the case of the strings is ignored (default is false).
136  *
137  * @param s1
138  * @param s2
139  * @param case_insensitive
140  * @return true if the strings match
141  */
142 template <typename T>
143 inline bool str_equal(const std::basic_string<T> &s1,
144                 const std::basic_string<T> &s2,
145                 bool case_insensitive = false)
146 {
147         if (!case_insensitive)
148                 return s1 == s2;
149
150         if (s1.size() != s2.size())
151                 return false;
152
153         for (size_t i = 0; i < s1.size(); ++i)
154                 if(tolower(s1[i]) != tolower(s2[i]))
155                         return false;
156
157         return true;
158 }
159
160
161 /**
162  * Check whether \p str begins with the string prefix. If \p case_insensitive
163  * is true then the check is case insensitve (default is false; i.e. case is
164  * significant).
165  *
166  * @param str
167  * @param prefix
168  * @param case_insensitive
169  * @return true if the str begins with prefix
170  */
171 template <typename T>
172 inline bool str_starts_with(const std::basic_string<T> &str,
173                 const std::basic_string<T> &prefix,
174                 bool case_insensitive = false)
175 {
176         if (str.size() < prefix.size())
177                 return false;
178
179         if (!case_insensitive)
180                 return str.compare(0, prefix.size(), prefix) == 0;
181
182         for (size_t i = 0; i < prefix.size(); ++i)
183                 if (tolower(str[i]) != tolower(prefix[i]))
184                         return false;
185         return true;
186 }
187
188 /**
189  * Check whether \p str begins with the string prefix. If \p case_insensitive
190  * is true then the check is case insensitve (default is false; i.e. case is
191  * significant).
192  *
193  * @param str
194  * @param prefix
195  * @param case_insensitive
196  * @return true if the str begins with prefix
197  */
198 template <typename T>
199 inline bool str_starts_with(const std::basic_string<T> &str,
200                 const T *prefix,
201                 bool case_insensitive = false)
202 {
203         return str_starts_with(str, std::basic_string<T>(prefix),
204                         case_insensitive);
205 }
206
207 /**
208  * Splits a string into its component parts separated by the character
209  * \p delimiter.
210  *
211  * @return An std::vector<std::basic_string<T> > of the component parts
212  */
213 template <typename T>
214 inline std::vector<std::basic_string<T> > str_split(
215                 const std::basic_string<T> &str,
216                 T delimiter)
217 {
218         std::vector<std::basic_string<T> > parts;
219         std::basic_stringstream<T> sstr(str);
220         std::basic_string<T> part;
221
222         while (std::getline(sstr, part, delimiter))
223                 parts.push_back(part);
224
225         return parts;
226 }
227
228
229 /**
230  * @param str
231  * @return A copy of \p str converted to all lowercase characters.
232  */
233 inline std::string lowercase(const std::string &str)
234 {
235         std::string s2;
236
237         s2.reserve(str.size());
238
239         for (size_t i = 0; i < str.size(); i++)
240                 s2 += tolower(str[i]);
241
242         return s2;
243 }
244
245
246 /**
247  * @param str
248  * @return A copy of \p str with leading and trailing whitespace removed.
249  */
250 inline std::string trim(const std::string &str)
251 {
252         size_t front = 0;
253
254         while (std::isspace(str[front]))
255                 ++front;
256
257         size_t back = str.size();
258         while (back > front && std::isspace(str[back - 1]))
259                 --back;
260
261         return str.substr(front, back - front);
262 }
263
264
265 /**
266  * Returns whether \p str should be regarded as (bool) true.  Case and leading
267  * and trailing whitespace are ignored.  Values that will return
268  * true are "y", "yes", "true" and any number that is not 0.
269  * @param str
270  */
271 inline bool is_yes(const std::string &str)
272 {
273         std::string s2 = lowercase(trim(str));
274
275         return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0;
276 }
277
278
279 /**
280  * Converts the string \p str to a signed 32-bit integer. The converted value
281  * is constrained so that min <= value <= max.
282  *
283  * @see atoi(3) for limitations
284  *
285  * @param str
286  * @param min Range minimum
287  * @param max Range maximum
288  * @return The value converted to a signed 32-bit integer and constrained
289  *      within the range defined by min and max (inclusive)
290  */
291 inline s32 mystoi(const std::string &str, s32 min, s32 max)
292 {
293         s32 i = atoi(str.c_str());
294
295         if (i < min)
296                 i = min;
297         if (i > max)
298                 i = max;
299
300         return i;
301 }
302
303
304 // MSVC2010 includes it's own versions of these
305 //#if !defined(_MSC_VER) || _MSC_VER < 1600
306
307
308 /**
309  * Returns a 32-bit value reprensented by the string \p str (decimal).
310  * @see atoi(3) for further limitations
311  */
312 inline s32 mystoi(const std::string &str)
313 {
314         return atoi(str.c_str());
315 }
316
317
318 /**
319  * Returns s 32-bit value represented by the wide string \p str (decimal).
320  * @see atoi(3) for further limitations
321  */
322 inline s32 mystoi(const std::wstring &str)
323 {
324         return mystoi(wide_to_narrow(str));
325 }
326
327
328 /**
329  * Returns a float reprensented by the string \p str (decimal).
330  * @see atof(3)
331  */
332 inline float mystof(const std::string &str)
333 {
334         return atof(str.c_str());
335 }
336
337 //#endif
338
339 #define stoi mystoi
340 #define stof mystof
341
342 /// Returns a value represented by the string \p val.
343 template <typename T>
344 inline T from_string(const std::string &str)
345 {
346         std::stringstream tmp(str);
347         T t;
348         tmp >> t;
349         return t;
350 }
351
352 /// Returns a 64-bit signed value represented by the string \p str (decimal).
353 inline s64 stoi64(const std::string &str) { return from_string<s64>(str); }
354
355 #if __cplusplus < 201103L
356 namespace std {
357
358 /// Returns a string representing the value \p val.
359 template <typename T>
360 inline string to_string(T val)
361 {
362         ostringstream oss;
363         oss << val;
364         return oss.str();
365 }
366 #define DEFINE_STD_TOSTRING_FLOATINGPOINT(T)            \
367         template <>                                     \
368         inline string to_string<T>(T val)               \
369         {                                               \
370                 ostringstream oss;                      \
371                 oss << std::fixed                       \
372                         << std::setprecision(6)         \
373                         << val;                         \
374                 return oss.str();                       \
375         }
376 DEFINE_STD_TOSTRING_FLOATINGPOINT(float)
377 DEFINE_STD_TOSTRING_FLOATINGPOINT(double)
378 DEFINE_STD_TOSTRING_FLOATINGPOINT(long double)
379
380 #undef DEFINE_STD_TOSTRING_FLOATINGPOINT
381
382 /// Returns a wide string representing the value \p val
383 template <typename T>
384 inline wstring to_wstring(T val)
385 {
386       return utf8_to_wide(to_string(val));
387 }
388 }
389 #endif
390
391 /// Returns a string representing the decimal value of the 32-bit value \p i.
392 inline std::string itos(s32 i) { return std::to_string(i); }
393 /// Returns a string representing the decimal value of the 64-bit value \p i.
394 inline std::string i64tos(s64 i) { return std::to_string(i); }
395
396 // std::to_string uses the '%.6f' conversion, which is inconsistent with
397 // std::ostream::operator<<() and impractical too.  ftos() uses the
398 // more generic and std::ostream::operator<<()-compatible '%G' format.
399 /// Returns a string representing the decimal value of the float value \p f.
400 inline std::string ftos(float f)
401 {
402         std::ostringstream oss;
403         oss << f;
404         return oss.str();
405 }
406
407
408 /**
409  * Replace all occurrences of \p pattern in \p str with \p replacement.
410  *
411  * @param str String to replace pattern with replacement within.
412  * @param pattern The pattern to replace.
413  * @param replacement What to replace the pattern with.
414  */
415 inline void str_replace(std::string &str, const std::string &pattern,
416                 const std::string &replacement)
417 {
418         std::string::size_type start = str.find(pattern, 0);
419         while (start != str.npos) {
420                 str.replace(start, pattern.size(), replacement);
421                 start = str.find(pattern, start + replacement.size());
422         }
423 }
424
425 /**
426  * Replace all occurrences of the character \p from in \p str with \p to.
427  *
428  * @param str The string to (potentially) modify.
429  * @param from The character in str to replace.
430  * @param to The replacement character.
431  */
432 void str_replace(std::string &str, char from, char to);
433
434
435 /**
436  * Check that a string only contains whitelisted characters. This is the
437  * opposite of string_allowed_blacklist().
438  *
439  * @param str The string to be checked.
440  * @param allowed_chars A string containing permitted characters.
441  * @return true if the string is allowed, otherwise false.
442  *
443  * @see string_allowed_blacklist()
444  */
445 inline bool string_allowed(const std::string &str, const std::string &allowed_chars)
446 {
447         return str.find_first_not_of(allowed_chars) == str.npos;
448 }
449
450
451 /**
452  * Check that a string contains no blacklisted characters. This is the
453  * opposite of string_allowed().
454  *
455  * @param str The string to be checked.
456  * @param blacklisted_chars A string containing prohibited characters.
457  * @return true if the string is allowed, otherwise false.
458
459  * @see string_allowed()
460  */
461 inline bool string_allowed_blacklist(const std::string &str,
462                 const std::string &blacklisted_chars)
463 {
464         return str.find_first_of(blacklisted_chars) == str.npos;
465 }
466
467
468 /**
469  * Create a string based on \p from where a newline is forcefully inserted
470  * every \p row_len characters.
471  *
472  * @note This function does not honour word wraps and blindy inserts a newline
473  *      every \p row_len characters whether it breaks a word or not.  It is
474  *      intended to be used for, for example, showing paths in the GUI.
475  *
476  * @note This function doesn't wrap inside utf-8 multibyte sequences and also
477  *      counts multibyte sequences correcly as single characters.
478  *
479  * @param from The (utf-8) string to be wrapped into rows.
480  * @param row_len The row length (in characters).
481  * @return A new string with the wrapping applied.
482  */
483 inline std::string wrap_rows(const std::string &from,
484                 unsigned row_len)
485 {
486         std::string to;
487
488         size_t character_idx = 0;
489         for (size_t i = 0; i < from.size(); i++) {
490                 if (!IS_UTF8_MULTB_INNER(from[i])) {
491                         // Wrap string after last inner byte of char
492                         if (character_idx > 0 && character_idx % row_len == 0)
493                                 to += '\n';
494                         character_idx++;
495                 }
496                 to += from[i];
497         }
498
499         return to;
500 }
501
502
503 /**
504  * Removes backslashes from an escaped string (FormSpec strings)
505  */
506 template <typename T>
507 inline std::basic_string<T> unescape_string(const std::basic_string<T> &s)
508 {
509         std::basic_string<T> res;
510
511         for (size_t i = 0; i < s.length(); i++) {
512                 if (s[i] == '\\') {
513                         i++;
514                         if (i >= s.length())
515                                 break;
516                 }
517                 res += s[i];
518         }
519
520         return res;
521 }
522
523 /**
524  * Remove all escape sequences in \p s.
525  *
526  * @param s The string in which to remove escape sequences.
527  * @return \p s, with escape sequences removed.
528  */
529 template <typename T>
530 std::basic_string<T> unescape_enriched(const std::basic_string<T> &s)
531 {
532         std::basic_string<T> output;
533         size_t i = 0;
534         while (i < s.length()) {
535                 if (s[i] == '\x1b') {
536                         ++i;
537                         if (i == s.length()) continue;
538                         if (s[i] == '(') {
539                                 ++i;
540                                 while (i < s.length() && s[i] != ')') {
541                                         if (s[i] == '\\') {
542                                                 ++i;
543                                         }
544                                         ++i;
545                                 }
546                                 ++i;
547                         } else {
548                                 ++i;
549                         }
550                         continue;
551                 }
552                 output += s[i];
553                 ++i;
554         }
555         return output;
556 }
557
558 template <typename T>
559 std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
560 {
561         std::vector<std::basic_string<T> > tokens;
562
563         std::basic_string<T> current;
564         bool last_was_escape = false;
565         for (size_t i = 0; i < s.length(); i++) {
566                 T si = s[i];
567                 if (last_was_escape) {
568                         current += '\\';
569                         current += si;
570                         last_was_escape = false;
571                 } else {
572                         if (si == delim) {
573                                 tokens.push_back(current);
574                                 current = std::basic_string<T>();
575                                 last_was_escape = false;
576                         } else if (si == '\\') {
577                                 last_was_escape = true;
578                         } else {
579                                 current += si;
580                                 last_was_escape = false;
581                         }
582                 }
583         }
584         //push last element
585         tokens.push_back(current);
586
587         return tokens;
588 }
589
590 /**
591  * Checks that all characters in \p to_check are a decimal digits.
592  *
593  * @param to_check
594  * @return true if to_check is not empty and all characters in to_check are
595  *      decimal digits, otherwise false
596  */
597 inline bool is_number(const std::string &to_check)
598 {
599         for (size_t i = 0; i < to_check.size(); i++)
600                 if (!std::isdigit(to_check[i]))
601                         return false;
602
603         return !to_check.empty();
604 }
605
606
607 /**
608  * Returns a C-string, either "true" or "false", corresponding to \p val.
609  *
610  * @return If \p val is true, then "true" is returned, otherwise "false".
611  */
612 inline const char *bool_to_cstr(bool val)
613 {
614         return val ? "true" : "false";
615 }
616
617 inline const std::string duration_to_string(int sec)
618 {
619         int min = sec / 60;
620         sec %= 60;
621         int hour = min / 60;
622         min %= 60;
623
624         std::stringstream ss;
625         if (hour > 0) {
626                 ss << hour << "h ";
627         }
628
629         if (min > 0) {
630                 ss << min << "m ";
631         }
632
633         if (sec > 0) {
634                 ss << sec << "s ";
635         }
636
637         return ss.str();
638 }
639
640
641 #endif