3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #include "irrlichttypes_bloated.h"
23 #include "irrString.h"
32 #include <unordered_map>
36 #define STRINGIFY(x) #x
37 #define TOSTRING(x) STRINGIFY(x)
39 // Checks whether a value is an ASCII printable character
40 #define IS_ASCII_PRINTABLE_CHAR(x) \
41 (((unsigned int)(x) >= 0x20) && \
42 ( (unsigned int)(x) <= 0x7e))
44 // Checks whether a byte is an inner byte for an utf-8 multibyte sequence
45 #define IS_UTF8_MULTB_INNER(x) \
46 (((unsigned char)(x) >= 0x80) && \
47 ( (unsigned char)(x) <= 0xbf))
49 // Checks whether a byte is a start byte for an utf-8 multibyte sequence
50 #define IS_UTF8_MULTB_START(x) \
51 (((unsigned char)(x) >= 0xc2) && \
52 ( (unsigned char)(x) <= 0xf4))
54 // Given a start byte x for an utf-8 multibyte sequence
55 // it gives the length of the whole sequence in bytes.
56 #define UTF8_MULTB_START_LEN(x) \
57 (((unsigned char)(x) < 0xe0) ? 2 : \
58 (((unsigned char)(x) < 0xf0) ? 3 : 4))
60 typedef std::unordered_map<std::string, std::string> StringMap;
67 // Try to avoid converting between wide and UTF-8 unless you need to
68 // input/output stuff via Irrlicht
69 std::wstring utf8_to_wide(const std::string &input);
70 std::string wide_to_utf8(const std::wstring &input);
72 // You must free the returned string!
73 // The returned string is allocated using new[]
74 wchar_t *utf8_to_wide_c(const char *str);
76 std::string urlencode(const std::string &str);
77 std::string urldecode(const std::string &str);
78 u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask);
79 std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask);
80 size_t mystrlcpy(char *dst, const char *src, size_t size);
81 char *mystrtok_r(char *s, const char *sep, char **lasts);
82 u64 read_seed(const char *str);
83 bool parseColorString(const std::string &value, video::SColor &color, bool quiet,
84 unsigned char default_alpha = 0xff);
88 * Returns a copy of \p str with spaces inserted at the right hand side to ensure
89 * that the string is \p len characters in length. If \p str is <= \p len then the
90 * returned string will be identical to str.
92 inline std::string padStringRight(std::string str, size_t len)
95 str.insert(str.end(), len - str.size(), ' ');
101 * Returns a version of \p str with the first occurrence of a string
102 * contained within ends[] removed from the end of the string.
105 * @param ends A NULL- or ""- terminated array of strings to remove from s in
106 * the copy produced. Note that once one of these strings is removed
107 * that no further postfixes contained within this array are removed.
109 * @return If no end could be removed then "" is returned.
111 inline std::string removeStringEnd(const std::string &str,
114 const char **p = ends;
116 for (; *p && (*p)[0] != '\0'; p++) {
117 std::string end = *p;
118 if (str.size() < end.size())
120 if (str.compare(str.size() - end.size(), end.size(), end) == 0)
121 return str.substr(0, str.size() - end.size());
129 * Check two strings for equivalence. If \p case_insensitive is true
130 * then the case of the strings is ignored (default is false).
134 * @param case_insensitive
135 * @return true if the strings match
137 template <typename T>
138 inline bool str_equal(const std::basic_string<T> &s1,
139 const std::basic_string<T> &s2,
140 bool case_insensitive = false)
142 if (!case_insensitive)
145 if (s1.size() != s2.size())
148 for (size_t i = 0; i < s1.size(); ++i)
149 if(tolower(s1[i]) != tolower(s2[i]))
157 * Check whether \p str begins with the string prefix. If \p case_insensitive
158 * is true then the check is case insensitve (default is false; i.e. case is
163 * @param case_insensitive
164 * @return true if the str begins with prefix
166 template <typename T>
167 inline bool str_starts_with(const std::basic_string<T> &str,
168 const std::basic_string<T> &prefix,
169 bool case_insensitive = false)
171 if (str.size() < prefix.size())
174 if (!case_insensitive)
175 return str.compare(0, prefix.size(), prefix) == 0;
177 for (size_t i = 0; i < prefix.size(); ++i)
178 if (tolower(str[i]) != tolower(prefix[i]))
184 * Check whether \p str begins with the string prefix. If \p case_insensitive
185 * is true then the check is case insensitve (default is false; i.e. case is
190 * @param case_insensitive
191 * @return true if the str begins with prefix
193 template <typename T>
194 inline bool str_starts_with(const std::basic_string<T> &str,
196 bool case_insensitive = false)
198 return str_starts_with(str, std::basic_string<T>(prefix),
204 * Check whether \p str ends with the string suffix. If \p case_insensitive
205 * is true then the check is case insensitve (default is false; i.e. case is
210 * @param case_insensitive
211 * @return true if the str begins with suffix
213 template <typename T>
214 inline bool str_ends_with(const std::basic_string<T> &str,
215 const std::basic_string<T> &suffix,
216 bool case_insensitive = false)
218 if (str.size() < suffix.size())
221 size_t start = str.size() - suffix.size();
222 if (!case_insensitive)
223 return str.compare(start, suffix.size(), suffix) == 0;
225 for (size_t i = 0; i < suffix.size(); ++i)
226 if (tolower(str[start + i]) != tolower(suffix[i]))
233 * Check whether \p str ends with the string suffix. If \p case_insensitive
234 * is true then the check is case insensitve (default is false; i.e. case is
239 * @param case_insensitive
240 * @return true if the str begins with suffix
242 template <typename T>
243 inline bool str_ends_with(const std::basic_string<T> &str,
245 bool case_insensitive = false)
247 return str_ends_with(str, std::basic_string<T>(suffix),
253 * Splits a string into its component parts separated by the character
256 * @return An std::vector<std::basic_string<T> > of the component parts
258 template <typename T>
259 inline std::vector<std::basic_string<T> > str_split(
260 const std::basic_string<T> &str,
263 std::vector<std::basic_string<T> > parts;
264 std::basic_stringstream<T> sstr(str);
265 std::basic_string<T> part;
267 while (std::getline(sstr, part, delimiter))
268 parts.push_back(part);
276 * @return A copy of \p str converted to all lowercase characters.
278 inline std::string lowercase(const std::string &str)
282 s2.reserve(str.size());
293 * @return A copy of \p str with leading and trailing whitespace removed.
295 inline std::string trim(const std::string &str)
298 size_t back = str.size();
300 while (front < back && std::isspace(str[front]))
303 while (back > front && std::isspace(str[back - 1]))
306 return str.substr(front, back - front);
311 * Returns whether \p str should be regarded as (bool) true. Case and leading
312 * and trailing whitespace are ignored. Values that will return
313 * true are "y", "yes", "true" and any number that is not 0.
316 inline bool is_yes(const std::string &str)
318 std::string s2 = lowercase(trim(str));
320 return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0;
325 * Converts the string \p str to a signed 32-bit integer. The converted value
326 * is constrained so that min <= value <= max.
328 * @see atoi(3) for limitations
331 * @param min Range minimum
332 * @param max Range maximum
333 * @return The value converted to a signed 32-bit integer and constrained
334 * within the range defined by min and max (inclusive)
336 inline s32 mystoi(const std::string &str, s32 min, s32 max)
338 s32 i = atoi(str.c_str());
349 * Returns a 32-bit value reprensented by the string \p str (decimal).
350 * @see atoi(3) for further limitations
352 inline s32 mystoi(const std::string &str)
354 return atoi(str.c_str());
358 * Returns a float reprensented by the string \p str (decimal).
361 inline float mystof(const std::string &str)
363 return atof(str.c_str());
369 /// Returns a value represented by the string \p val.
370 template <typename T>
371 inline T from_string(const std::string &str)
373 std::stringstream tmp(str);
379 /// Returns a 64-bit signed value represented by the string \p str (decimal).
380 inline s64 stoi64(const std::string &str) { return from_string<s64>(str); }
382 #if __cplusplus < 201103L
385 /// Returns a string representing the value \p val.
386 template <typename T>
387 inline string to_string(T val)
393 #define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \
395 inline string to_string<T>(T val) \
399 << std::setprecision(6) \
403 DEFINE_STD_TOSTRING_FLOATINGPOINT(float)
404 DEFINE_STD_TOSTRING_FLOATINGPOINT(double)
405 DEFINE_STD_TOSTRING_FLOATINGPOINT(long double)
407 #undef DEFINE_STD_TOSTRING_FLOATINGPOINT
409 /// Returns a wide string representing the value \p val
410 template <typename T>
411 inline wstring to_wstring(T val)
413 return utf8_to_wide(to_string(val));
418 /// Returns a string representing the decimal value of the 32-bit value \p i.
419 inline std::string itos(s32 i) { return std::to_string(i); }
420 /// Returns a string representing the decimal value of the 64-bit value \p i.
421 inline std::string i64tos(s64 i) { return std::to_string(i); }
423 // std::to_string uses the '%.6f' conversion, which is inconsistent with
424 // std::ostream::operator<<() and impractical too. ftos() uses the
425 // more generic and std::ostream::operator<<()-compatible '%G' format.
426 /// Returns a string representing the decimal value of the float value \p f.
427 inline std::string ftos(float f)
429 std::ostringstream oss;
436 * Replace all occurrences of \p pattern in \p str with \p replacement.
438 * @param str String to replace pattern with replacement within.
439 * @param pattern The pattern to replace.
440 * @param replacement What to replace the pattern with.
442 inline void str_replace(std::string &str, const std::string &pattern,
443 const std::string &replacement)
445 std::string::size_type start = str.find(pattern, 0);
446 while (start != str.npos) {
447 str.replace(start, pattern.size(), replacement);
448 start = str.find(pattern, start + replacement.size());
453 * Escapes characters [ ] \ , ; that can not be used in formspecs
455 inline void str_formspec_escape(std::string &str)
457 str_replace(str, "\\", "\\\\");
458 str_replace(str, "]", "\\]");
459 str_replace(str, "[", "\\[");
460 str_replace(str, ";", "\\;");
461 str_replace(str, ",", "\\,");
465 * Replace all occurrences of the character \p from in \p str with \p to.
467 * @param str The string to (potentially) modify.
468 * @param from The character in str to replace.
469 * @param to The replacement character.
471 void str_replace(std::string &str, char from, char to);
475 * Check that a string only contains whitelisted characters. This is the
476 * opposite of string_allowed_blacklist().
478 * @param str The string to be checked.
479 * @param allowed_chars A string containing permitted characters.
480 * @return true if the string is allowed, otherwise false.
482 * @see string_allowed_blacklist()
484 inline bool string_allowed(const std::string &str, const std::string &allowed_chars)
486 return str.find_first_not_of(allowed_chars) == str.npos;
491 * Check that a string contains no blacklisted characters. This is the
492 * opposite of string_allowed().
494 * @param str The string to be checked.
495 * @param blacklisted_chars A string containing prohibited characters.
496 * @return true if the string is allowed, otherwise false.
498 * @see string_allowed()
500 inline bool string_allowed_blacklist(const std::string &str,
501 const std::string &blacklisted_chars)
503 return str.find_first_of(blacklisted_chars) == str.npos;
508 * Create a string based on \p from where a newline is forcefully inserted
509 * every \p row_len characters.
511 * @note This function does not honour word wraps and blindy inserts a newline
512 * every \p row_len characters whether it breaks a word or not. It is
513 * intended to be used for, for example, showing paths in the GUI.
515 * @note This function doesn't wrap inside utf-8 multibyte sequences and also
516 * counts multibyte sequences correcly as single characters.
518 * @param from The (utf-8) string to be wrapped into rows.
519 * @param row_len The row length (in characters).
520 * @return A new string with the wrapping applied.
522 inline std::string wrap_rows(const std::string &from,
527 size_t character_idx = 0;
528 for (size_t i = 0; i < from.size(); i++) {
529 if (!IS_UTF8_MULTB_INNER(from[i])) {
530 // Wrap string after last inner byte of char
531 if (character_idx > 0 && character_idx % row_len == 0)
543 * Removes backslashes from an escaped string (FormSpec strings)
545 template <typename T>
546 inline std::basic_string<T> unescape_string(const std::basic_string<T> &s)
548 std::basic_string<T> res;
550 for (size_t i = 0; i < s.length(); i++) {
563 * Remove all escape sequences in \p s.
565 * @param s The string in which to remove escape sequences.
566 * @return \p s, with escape sequences removed.
568 template <typename T>
569 std::basic_string<T> unescape_enriched(const std::basic_string<T> &s)
571 std::basic_string<T> output;
573 while (i < s.length()) {
574 if (s[i] == '\x1b') {
576 if (i == s.length()) continue;
579 while (i < s.length() && s[i] != ')') {
597 template <typename T>
598 std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
600 std::vector<std::basic_string<T> > tokens;
602 std::basic_string<T> current;
603 bool last_was_escape = false;
604 for (size_t i = 0; i < s.length(); i++) {
606 if (last_was_escape) {
609 last_was_escape = false;
612 tokens.push_back(current);
613 current = std::basic_string<T>();
614 last_was_escape = false;
615 } else if (si == '\\') {
616 last_was_escape = true;
619 last_was_escape = false;
624 tokens.push_back(current);
629 std::wstring translate_string(const std::wstring &s, Translations *translations);
631 std::wstring translate_string(const std::wstring &s);
633 inline std::wstring unescape_translate(const std::wstring &s) {
634 return unescape_enriched(translate_string(s));
638 * Checks that all characters in \p to_check are a decimal digits.
641 * @return true if to_check is not empty and all characters in to_check are
642 * decimal digits, otherwise false
644 inline bool is_number(const std::string &to_check)
646 for (char i : to_check)
647 if (!std::isdigit(i))
650 return !to_check.empty();
655 * Returns a C-string, either "true" or "false", corresponding to \p val.
657 * @return If \p val is true, then "true" is returned, otherwise "false".
659 inline const char *bool_to_cstr(bool val)
661 return val ? "true" : "false";
665 * Converts a duration in seconds to a pretty-printed duration in
666 * days, hours, minutes and seconds.
668 * @param sec duration in seconds
669 * @return pretty-printed duration
671 inline const std::string duration_to_string(int sec)
673 std::ostringstream ss;
674 const char *neg = "";
688 ss << neg << day << "d";
689 if (hour > 0 || min > 0 || sec > 0)
694 ss << neg << hour << "h";
695 if (min > 0 || sec > 0)
700 ss << neg << min << "min";
705 if (sec > 0 || total_sec == 0) {
706 ss << neg << sec << "s";
713 * Joins a vector of strings by the string \p delimiter.
715 * @return A std::string
717 inline std::string str_join(const std::vector<std::string> &list,
718 const std::string &delimiter)
720 std::ostringstream oss;
722 for (const auto &part : list) {
732 * Create a UTF8 std::string from a irr::core::stringw.
734 inline std::string stringw_to_utf8(const irr::core::stringw &input)
736 std::wstring str(input.c_str());
737 return wide_to_utf8(str);
741 * Create a irr::core:stringw from a UTF8 std::string.
743 inline irr::core::stringw utf8_to_stringw(const std::string &input)
745 std::wstring str = utf8_to_wide(input);
746 return irr::core::stringw(str.c_str());
750 * Sanitize the name of a new directory. This consists of two stages:
751 * 1. Check for 'reserved filenames' that can't be used on some filesystems
752 * and add a prefix to them
753 * 2. Remove 'unsafe' characters from the name by replacing them with '_'
755 std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix);
758 * Prints a sanitized version of a string without control characters.
759 * '\t' and '\n' are allowed, as are UTF-8 control characters (e.g. RTL).
760 * ASCII control characters are replaced with their hex encoding in angle
761 * brackets (e.g. "a\x1eb" -> "a<1e>b").
763 void safe_print_string(std::ostream &os, const std::string &str);