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