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