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