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