string.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include "irrlichttypes_bloated.h"
  18. #include <cstdlib>
  19. #include <string>
  20. #include <cstring>
  21. #include <vector>
  22. #include <map>
  23. #include <sstream>
  24. #include <iomanip>
  25. #include <cctype>
  26. #include <unordered_map>
  27. #define STRINGIFY(x) #x
  28. #define TOSTRING(x) STRINGIFY(x)
  29. // Checks whether a value is an ASCII printable character
  30. #define IS_ASCII_PRINTABLE_CHAR(x) \
  31. (((unsigned int)(x) >= 0x20) && \
  32. ( (unsigned int)(x) <= 0x7e))
  33. // Checks whether a byte is an inner byte for an utf-8 multibyte sequence
  34. #define IS_UTF8_MULTB_INNER(x) \
  35. (((unsigned char)(x) >= 0x80) && \
  36. ( (unsigned char)(x) <= 0xbf))
  37. // Checks whether a byte is a start byte for an utf-8 multibyte sequence
  38. #define IS_UTF8_MULTB_START(x) \
  39. (((unsigned char)(x) >= 0xc2) && \
  40. ( (unsigned char)(x) <= 0xf4))
  41. // Given a start byte x for an utf-8 multibyte sequence
  42. // it gives the length of the whole sequence in bytes.
  43. #define UTF8_MULTB_START_LEN(x) \
  44. (((unsigned char)(x) < 0xe0) ? 2 : \
  45. (((unsigned char)(x) < 0xf0) ? 3 : 4))
  46. typedef std::unordered_map<std::string, std::string> StringMap;
  47. struct FlagDesc {
  48. const char *name;
  49. u32 flag;
  50. };
  51. // try not to convert between wide/utf8 encodings; this can result in data loss
  52. // try to only convert between them when you need to input/output stuff via Irrlicht
  53. std::wstring utf8_to_wide(const std::string &input);
  54. std::string wide_to_utf8(const std::wstring &input);
  55. wchar_t *utf8_to_wide_c(const char *str);
  56. // NEVER use those two functions unless you have a VERY GOOD reason to
  57. // they just convert between wide and multibyte encoding
  58. // multibyte encoding depends on current locale, this is no good, especially on Windows
  59. // You must free the returned string!
  60. // The returned string is allocated using new
  61. wchar_t *narrow_to_wide_c(const char *str);
  62. std::wstring narrow_to_wide(const std::string &mbs);
  63. std::string wide_to_narrow(const std::wstring &wcs);
  64. std::string urlencode(const std::string &str);
  65. std::string urldecode(const std::string &str);
  66. u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask);
  67. std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask);
  68. size_t mystrlcpy(char *dst, const char *src, size_t size);
  69. char *mystrtok_r(char *s, const char *sep, char **lasts);
  70. u64 read_seed(const char *str);
  71. bool parseColorString(const std::string &value, video::SColor &color, bool quiet);
  72. /**
  73. * Returns a copy of \p str with spaces inserted at the right hand side to ensure
  74. * that the string is \p len characters in length. If \p str is <= \p len then the
  75. * returned string will be identical to str.
  76. */
  77. inline std::string padStringRight(std::string str, size_t len)
  78. {
  79. if (len > str.size())
  80. str.insert(str.end(), len - str.size(), ' ');
  81. return str;
  82. }
  83. /**
  84. * Returns a version of \p str with the first occurrence of a string
  85. * contained within ends[] removed from the end of the string.
  86. *
  87. * @param str
  88. * @param ends A NULL- or ""- terminated array of strings to remove from s in
  89. * the copy produced. Note that once one of these strings is removed
  90. * that no further postfixes contained within this array are removed.
  91. *
  92. * @return If no end could be removed then "" is returned.
  93. */
  94. inline std::string removeStringEnd(const std::string &str,
  95. const char *ends[])
  96. {
  97. const char **p = ends;
  98. for (; *p && (*p)[0] != '\0'; p++) {
  99. std::string end = *p;
  100. if (str.size() < end.size())
  101. continue;
  102. if (str.compare(str.size() - end.size(), end.size(), end) == 0)
  103. return str.substr(0, str.size() - end.size());
  104. }
  105. return "";
  106. }
  107. /**
  108. * Check two strings for equivalence. If \p case_insensitive is true
  109. * then the case of the strings is ignored (default is false).
  110. *
  111. * @param s1
  112. * @param s2
  113. * @param case_insensitive
  114. * @return true if the strings match
  115. */
  116. template <typename T>
  117. inline bool str_equal(const std::basic_string<T> &s1,
  118. const std::basic_string<T> &s2,
  119. bool case_insensitive = false)
  120. {
  121. if (!case_insensitive)
  122. return s1 == s2;
  123. if (s1.size() != s2.size())
  124. return false;
  125. for (size_t i = 0; i < s1.size(); ++i)
  126. if(tolower(s1[i]) != tolower(s2[i]))
  127. return false;
  128. return true;
  129. }
  130. /**
  131. * Check whether \p str begins with the string prefix. If \p case_insensitive
  132. * is true then the check is case insensitve (default is false; i.e. case is
  133. * significant).
  134. *
  135. * @param str
  136. * @param prefix
  137. * @param case_insensitive
  138. * @return true if the str begins with prefix
  139. */
  140. template <typename T>
  141. inline bool str_starts_with(const std::basic_string<T> &str,
  142. const std::basic_string<T> &prefix,
  143. bool case_insensitive = false)
  144. {
  145. if (str.size() < prefix.size())
  146. return false;
  147. if (!case_insensitive)
  148. return str.compare(0, prefix.size(), prefix) == 0;
  149. for (size_t i = 0; i < prefix.size(); ++i)
  150. if (tolower(str[i]) != tolower(prefix[i]))
  151. return false;
  152. return true;
  153. }
  154. /**
  155. * Check whether \p str begins with the string prefix. If \p case_insensitive
  156. * is true then the check is case insensitve (default is false; i.e. case is
  157. * significant).
  158. *
  159. * @param str
  160. * @param prefix
  161. * @param case_insensitive
  162. * @return true if the str begins with prefix
  163. */
  164. template <typename T>
  165. inline bool str_starts_with(const std::basic_string<T> &str,
  166. const T *prefix,
  167. bool case_insensitive = false)
  168. {
  169. return str_starts_with(str, std::basic_string<T>(prefix),
  170. case_insensitive);
  171. }
  172. /**
  173. * Check whether \p str ends with the string suffix. If \p case_insensitive
  174. * is true then the check is case insensitve (default is false; i.e. case is
  175. * significant).
  176. *
  177. * @param str
  178. * @param suffix
  179. * @param case_insensitive
  180. * @return true if the str begins with suffix
  181. */
  182. template <typename T>
  183. inline bool str_ends_with(const std::basic_string<T> &str,
  184. const std::basic_string<T> &suffix,
  185. bool case_insensitive = false)
  186. {
  187. if (str.size() < suffix.size())
  188. return false;
  189. size_t start = str.size() - suffix.size();
  190. if (!case_insensitive)
  191. return str.compare(start, suffix.size(), suffix) == 0;
  192. for (size_t i = 0; i < suffix.size(); ++i)
  193. if (tolower(str[start + i]) != tolower(suffix[i]))
  194. return false;
  195. return true;
  196. }
  197. /**
  198. * Check whether \p str ends with the string suffix. If \p case_insensitive
  199. * is true then the check is case insensitve (default is false; i.e. case is
  200. * significant).
  201. *
  202. * @param str
  203. * @param suffix
  204. * @param case_insensitive
  205. * @return true if the str begins with suffix
  206. */
  207. template <typename T>
  208. inline bool str_ends_with(const std::basic_string<T> &str,
  209. const T *suffix,
  210. bool case_insensitive = false)
  211. {
  212. return str_ends_with(str, std::basic_string<T>(suffix),
  213. case_insensitive);
  214. }
  215. /**
  216. * Splits a string into its component parts separated by the character
  217. * \p delimiter.
  218. *
  219. * @return An std::vector<std::basic_string<T> > of the component parts
  220. */
  221. template <typename T>
  222. inline std::vector<std::basic_string<T> > str_split(
  223. const std::basic_string<T> &str,
  224. T delimiter)
  225. {
  226. std::vector<std::basic_string<T> > parts;
  227. std::basic_stringstream<T> sstr(str);
  228. std::basic_string<T> part;
  229. while (std::getline(sstr, part, delimiter))
  230. parts.push_back(part);
  231. return parts;
  232. }
  233. /**
  234. * @param str
  235. * @return A copy of \p str converted to all lowercase characters.
  236. */
  237. inline std::string lowercase(const std::string &str)
  238. {
  239. std::string s2;
  240. s2.reserve(str.size());
  241. for (char i : str)
  242. s2 += tolower(i);
  243. return s2;
  244. }
  245. /**
  246. * @param str
  247. * @return A copy of \p str with leading and trailing whitespace removed.
  248. */
  249. inline std::string trim(const std::string &str)
  250. {
  251. size_t front = 0;
  252. while (std::isspace(str[front]))
  253. ++front;
  254. size_t back = str.size();
  255. while (back > front && std::isspace(str[back - 1]))
  256. --back;
  257. return str.substr(front, back - front);
  258. }
  259. /**
  260. * Returns whether \p str should be regarded as (bool) true. Case and leading
  261. * and trailing whitespace are ignored. Values that will return
  262. * true are "y", "yes", "true" and any number that is not 0.
  263. * @param str
  264. */
  265. inline bool is_yes(const std::string &str)
  266. {
  267. std::string s2 = lowercase(trim(str));
  268. return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0;
  269. }
  270. /**
  271. * Converts the string \p str to a signed 32-bit integer. The converted value
  272. * is constrained so that min <= value <= max.
  273. *
  274. * @see atoi(3) for limitations
  275. *
  276. * @param str
  277. * @param min Range minimum
  278. * @param max Range maximum
  279. * @return The value converted to a signed 32-bit integer and constrained
  280. * within the range defined by min and max (inclusive)
  281. */
  282. inline s32 mystoi(const std::string &str, s32 min, s32 max)
  283. {
  284. s32 i = atoi(str.c_str());
  285. if (i < min)
  286. i = min;
  287. if (i > max)
  288. i = max;
  289. return i;
  290. }
  291. // MSVC2010 includes it's own versions of these
  292. //#if !defined(_MSC_VER) || _MSC_VER < 1600
  293. /**
  294. * Returns a 32-bit value reprensented by the string \p str (decimal).
  295. * @see atoi(3) for further limitations
  296. */
  297. inline s32 mystoi(const std::string &str)
  298. {
  299. return atoi(str.c_str());
  300. }
  301. /**
  302. * Returns s 32-bit value represented by the wide string \p str (decimal).
  303. * @see atoi(3) for further limitations
  304. */
  305. inline s32 mystoi(const std::wstring &str)
  306. {
  307. return mystoi(wide_to_narrow(str));
  308. }
  309. /**
  310. * Returns a float reprensented by the string \p str (decimal).
  311. * @see atof(3)
  312. */
  313. inline float mystof(const std::string &str)
  314. {
  315. return atof(str.c_str());
  316. }
  317. //#endif
  318. #define stoi mystoi
  319. #define stof mystof
  320. /// Returns a value represented by the string \p val.
  321. template <typename T>
  322. inline T from_string(const std::string &str)
  323. {
  324. std::stringstream tmp(str);
  325. T t;
  326. tmp >> t;
  327. return t;
  328. }
  329. /// Returns a 64-bit signed value represented by the string \p str (decimal).
  330. inline s64 stoi64(const std::string &str) { return from_string<s64>(str); }
  331. #if __cplusplus < 201103L
  332. namespace std {
  333. /// Returns a string representing the value \p val.
  334. template <typename T>
  335. inline string to_string(T val)
  336. {
  337. ostringstream oss;
  338. oss << val;
  339. return oss.str();
  340. }
  341. #define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \
  342. template <> \
  343. inline string to_string<T>(T val) \
  344. { \
  345. ostringstream oss; \
  346. oss << std::fixed \
  347. << std::setprecision(6) \
  348. << val; \
  349. return oss.str(); \
  350. }
  351. DEFINE_STD_TOSTRING_FLOATINGPOINT(float)
  352. DEFINE_STD_TOSTRING_FLOATINGPOINT(double)
  353. DEFINE_STD_TOSTRING_FLOATINGPOINT(long double)
  354. #undef DEFINE_STD_TOSTRING_FLOATINGPOINT
  355. /// Returns a wide string representing the value \p val
  356. template <typename T>
  357. inline wstring to_wstring(T val)
  358. {
  359. return utf8_to_wide(to_string(val));
  360. }
  361. }
  362. #endif
  363. /// Returns a string representing the decimal value of the 32-bit value \p i.
  364. inline std::string itos(s32 i) { return std::to_string(i); }
  365. /// Returns a string representing the decimal value of the 64-bit value \p i.
  366. inline std::string i64tos(s64 i) { return std::to_string(i); }
  367. // std::to_string uses the '%.6f' conversion, which is inconsistent with
  368. // std::ostream::operator<<() and impractical too. ftos() uses the
  369. // more generic and std::ostream::operator<<()-compatible '%G' format.
  370. /// Returns a string representing the decimal value of the float value \p f.
  371. inline std::string ftos(float f)
  372. {
  373. std::ostringstream oss;
  374. oss << f;
  375. return oss.str();
  376. }
  377. /**
  378. * Replace all occurrences of \p pattern in \p str with \p replacement.
  379. *
  380. * @param str String to replace pattern with replacement within.
  381. * @param pattern The pattern to replace.
  382. * @param replacement What to replace the pattern with.
  383. */
  384. inline void str_replace(std::string &str, const std::string &pattern,
  385. const std::string &replacement)
  386. {
  387. std::string::size_type start = str.find(pattern, 0);
  388. while (start != str.npos) {
  389. str.replace(start, pattern.size(), replacement);
  390. start = str.find(pattern, start + replacement.size());
  391. }
  392. }
  393. /**
  394. * Escapes characters [ ] \ , ; that can not be used in formspecs
  395. */
  396. inline void str_formspec_escape(std::string &str)
  397. {
  398. str_replace(str, "\\", "\\\\");
  399. str_replace(str, "]", "\\]");
  400. str_replace(str, "[", "\\[");
  401. str_replace(str, ";", "\\;");
  402. str_replace(str, ",", "\\,");
  403. }
  404. /**
  405. * Replace all occurrences of the character \p from in \p str with \p to.
  406. *
  407. * @param str The string to (potentially) modify.
  408. * @param from The character in str to replace.
  409. * @param to The replacement character.
  410. */
  411. void str_replace(std::string &str, char from, char to);
  412. /**
  413. * Check that a string only contains whitelisted characters. This is the
  414. * opposite of string_allowed_blacklist().
  415. *
  416. * @param str The string to be checked.
  417. * @param allowed_chars A string containing permitted characters.
  418. * @return true if the string is allowed, otherwise false.
  419. *
  420. * @see string_allowed_blacklist()
  421. */
  422. inline bool string_allowed(const std::string &str, const std::string &allowed_chars)
  423. {
  424. return str.find_first_not_of(allowed_chars) == str.npos;
  425. }
  426. /**
  427. * Check that a string contains no blacklisted characters. This is the
  428. * opposite of string_allowed().
  429. *
  430. * @param str The string to be checked.
  431. * @param blacklisted_chars A string containing prohibited characters.
  432. * @return true if the string is allowed, otherwise false.
  433. * @see string_allowed()
  434. */
  435. inline bool string_allowed_blacklist(const std::string &str,
  436. const std::string &blacklisted_chars)
  437. {
  438. return str.find_first_of(blacklisted_chars) == str.npos;
  439. }
  440. /**
  441. * Create a string based on \p from where a newline is forcefully inserted
  442. * every \p row_len characters.
  443. *
  444. * @note This function does not honour word wraps and blindy inserts a newline
  445. * every \p row_len characters whether it breaks a word or not. It is
  446. * intended to be used for, for example, showing paths in the GUI.
  447. *
  448. * @note This function doesn't wrap inside utf-8 multibyte sequences and also
  449. * counts multibyte sequences correcly as single characters.
  450. *
  451. * @param from The (utf-8) string to be wrapped into rows.
  452. * @param row_len The row length (in characters).
  453. * @return A new string with the wrapping applied.
  454. */
  455. inline std::string wrap_rows(const std::string &from,
  456. unsigned row_len)
  457. {
  458. std::string to;
  459. size_t character_idx = 0;
  460. for (size_t i = 0; i < from.size(); i++) {
  461. if (!IS_UTF8_MULTB_INNER(from[i])) {
  462. // Wrap string after last inner byte of char
  463. if (character_idx > 0 && character_idx % row_len == 0)
  464. to += '\n';
  465. character_idx++;
  466. }
  467. to += from[i];
  468. }
  469. return to;
  470. }
  471. /**
  472. * Removes backslashes from an escaped string (FormSpec strings)
  473. */
  474. template <typename T>
  475. inline std::basic_string<T> unescape_string(const std::basic_string<T> &s)
  476. {
  477. std::basic_string<T> res;
  478. for (size_t i = 0; i < s.length(); i++) {
  479. if (s[i] == '\\') {
  480. i++;
  481. if (i >= s.length())
  482. break;
  483. }
  484. res += s[i];
  485. }
  486. return res;
  487. }
  488. /**
  489. * Remove all escape sequences in \p s.
  490. *
  491. * @param s The string in which to remove escape sequences.
  492. * @return \p s, with escape sequences removed.
  493. */
  494. template <typename T>
  495. std::basic_string<T> unescape_enriched(const std::basic_string<T> &s)
  496. {
  497. std::basic_string<T> output;
  498. size_t i = 0;
  499. while (i < s.length()) {
  500. if (s[i] == '\x1b') {
  501. ++i;
  502. if (i == s.length()) continue;
  503. if (s[i] == '(') {
  504. ++i;
  505. while (i < s.length() && s[i] != ')') {
  506. if (s[i] == '\\') {
  507. ++i;
  508. }
  509. ++i;
  510. }
  511. ++i;
  512. } else {
  513. ++i;
  514. }
  515. continue;
  516. }
  517. output += s[i];
  518. ++i;
  519. }
  520. return output;
  521. }
  522. template <typename T>
  523. std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
  524. {
  525. std::vector<std::basic_string<T> > tokens;
  526. std::basic_string<T> current;
  527. bool last_was_escape = false;
  528. for (size_t i = 0; i < s.length(); i++) {
  529. T si = s[i];
  530. if (last_was_escape) {
  531. current += '\\';
  532. current += si;
  533. last_was_escape = false;
  534. } else {
  535. if (si == delim) {
  536. tokens.push_back(current);
  537. current = std::basic_string<T>();
  538. last_was_escape = false;
  539. } else if (si == '\\') {
  540. last_was_escape = true;
  541. } else {
  542. current += si;
  543. last_was_escape = false;
  544. }
  545. }
  546. }
  547. //push last element
  548. tokens.push_back(current);
  549. return tokens;
  550. }
  551. std::wstring translate_string(const std::wstring &s);
  552. inline std::wstring unescape_translate(const std::wstring &s) {
  553. return unescape_enriched(translate_string(s));
  554. }
  555. /**
  556. * Checks that all characters in \p to_check are a decimal digits.
  557. *
  558. * @param to_check
  559. * @return true if to_check is not empty and all characters in to_check are
  560. * decimal digits, otherwise false
  561. */
  562. inline bool is_number(const std::string &to_check)
  563. {
  564. for (char i : to_check)
  565. if (!std::isdigit(i))
  566. return false;
  567. return !to_check.empty();
  568. }
  569. /**
  570. * Returns a C-string, either "true" or "false", corresponding to \p val.
  571. *
  572. * @return If \p val is true, then "true" is returned, otherwise "false".
  573. */
  574. inline const char *bool_to_cstr(bool val)
  575. {
  576. return val ? "true" : "false";
  577. }
  578. inline const std::string duration_to_string(int sec)
  579. {
  580. int min = sec / 60;
  581. sec %= 60;
  582. int hour = min / 60;
  583. min %= 60;
  584. std::stringstream ss;
  585. if (hour > 0) {
  586. ss << hour << "h ";
  587. }
  588. if (min > 0) {
  589. ss << min << "m ";
  590. }
  591. if (sec > 0) {
  592. ss << sec << "s ";
  593. }
  594. return ss.str();
  595. }