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