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