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