StringUtilities.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/StringUtilities.h"
  29. #include "../../Include/RmlUi/Core/Log.h"
  30. #include <algorithm>
  31. #include <limits.h>
  32. #include <sstream>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <string.h>
  36. namespace Rml {
  37. static int FormatString(String& string, const char* format, va_list argument_list)
  38. {
  39. constexpr size_t InternalBufferSize = 256;
  40. char buffer[InternalBufferSize];
  41. char* buffer_ptr = buffer;
  42. size_t max_size = InternalBufferSize;
  43. int length = 0;
  44. for (int i = 0; i < 2; i++)
  45. {
  46. va_list argument_list_copy;
  47. va_copy(argument_list_copy, argument_list);
  48. length = vsnprintf(buffer_ptr, max_size, format, argument_list_copy);
  49. va_end(argument_list_copy);
  50. if (length < 0)
  51. {
  52. RMLUI_ERRORMSG("Error while formatting string");
  53. return 0;
  54. }
  55. if ((size_t)length < max_size || i > 0)
  56. break;
  57. max_size = (size_t)length + 1;
  58. buffer_ptr = new char[max_size];
  59. }
  60. string = buffer_ptr;
  61. if (buffer_ptr != buffer)
  62. delete[] buffer_ptr;
  63. return length;
  64. }
  65. int FormatString(String& string, size_t /*max_size*/, const char* format, ...)
  66. {
  67. va_list argument_list;
  68. va_start(argument_list, format);
  69. int result = FormatString(string, format, argument_list);
  70. va_end(argument_list);
  71. return result;
  72. }
  73. String CreateString(size_t /*max_size*/, const char* format, ...)
  74. {
  75. String result;
  76. va_list argument_list;
  77. va_start(argument_list, format);
  78. FormatString(result, format, argument_list);
  79. va_end(argument_list);
  80. return result;
  81. }
  82. static inline char CharToLower(char c)
  83. {
  84. if (c >= 'A' && c <= 'Z')
  85. c += char('a' - 'A');
  86. return c;
  87. }
  88. String StringUtilities::ToLower(String string)
  89. {
  90. std::transform(string.begin(), string.end(), string.begin(), &CharToLower);
  91. return string;
  92. }
  93. String StringUtilities::ToUpper(String string)
  94. {
  95. std::transform(string.begin(), string.end(), string.begin(), [](char c) {
  96. if (c >= 'a' && c <= 'z')
  97. c -= char('a' - 'A');
  98. return c;
  99. });
  100. return string;
  101. }
  102. RMLUICORE_API String StringUtilities::EncodeRml(const String& string)
  103. {
  104. String result;
  105. result.reserve(string.size());
  106. for (char c : string)
  107. {
  108. switch (c)
  109. {
  110. case '<': result += "&lt;"; break;
  111. case '>': result += "&gt;"; break;
  112. case '&': result += "&amp;"; break;
  113. case '"': result += "&quot;"; break;
  114. default: result += c; break;
  115. }
  116. }
  117. return result;
  118. }
  119. String StringUtilities::DecodeRml(const String& s)
  120. {
  121. String result;
  122. result.reserve(s.size());
  123. for (size_t i = 0; i < s.size();)
  124. {
  125. if (s[i] == '&')
  126. {
  127. if (s[i + 1] == 'l' && s[i + 2] == 't' && s[i + 3] == ';')
  128. {
  129. result += "<";
  130. i += 4;
  131. continue;
  132. }
  133. else if (s[i + 1] == 'g' && s[i + 2] == 't' && s[i + 3] == ';')
  134. {
  135. result += ">";
  136. i += 4;
  137. continue;
  138. }
  139. else if (s[i + 1] == 'a' && s[i + 2] == 'm' && s[i + 3] == 'p' && s[i + 4] == ';')
  140. {
  141. result += "&";
  142. i += 5;
  143. continue;
  144. }
  145. else if (s[i + 1] == 'q' && s[i + 2] == 'u' && s[i + 3] == 'o' && s[i + 4] == 't' && s[i + 5] == ';')
  146. {
  147. result += "\"";
  148. i += 6;
  149. continue;
  150. }
  151. else if (s[i + 1] == '#')
  152. {
  153. size_t start = i + 2;
  154. if (s[i + 2] == 'x')
  155. {
  156. start++;
  157. size_t j = 0;
  158. for (; j < 8; j++)
  159. {
  160. const auto& c = s[start + j];
  161. if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))
  162. break;
  163. }
  164. if (j > 0 && s[start + j] == ';')
  165. {
  166. String tmp = s.substr(start, j);
  167. const char* begin = tmp.c_str();
  168. char* end;
  169. unsigned long code_point = strtoul(begin, &end, 16);
  170. if (code_point != 0 && code_point != ULONG_MAX)
  171. {
  172. result += ToUTF8(static_cast<Character>(code_point));
  173. i = start + (end - begin) + 1;
  174. continue;
  175. }
  176. }
  177. }
  178. else
  179. {
  180. size_t j = 0;
  181. for (; j < 8; j++)
  182. {
  183. const auto& c = s[start + j];
  184. if (!(c >= '0' && c <= '9'))
  185. break;
  186. }
  187. if (j > 0 && s[start + j] == ';')
  188. {
  189. String tmp = s.substr(start, j);
  190. const char* begin = tmp.c_str();
  191. char* end;
  192. unsigned long code_point = strtoul(begin, &end, 10);
  193. if (code_point != 0 && code_point != ULONG_MAX)
  194. {
  195. result += ToUTF8(static_cast<Character>(code_point));
  196. i = start + (end - begin) + 1;
  197. continue;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. result += s[i];
  204. i += 1;
  205. }
  206. return result;
  207. }
  208. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  209. {
  210. size_t pos = 0;
  211. while ((pos = subject.find(search, pos)) != String::npos)
  212. {
  213. subject.replace(pos, search.length(), replace);
  214. pos += replace.length();
  215. }
  216. return subject;
  217. }
  218. String StringUtilities::Replace(String subject, char search, char replace)
  219. {
  220. const size_t size = subject.size();
  221. for (size_t i = 0; i < size; i++)
  222. {
  223. if (subject[i] == search)
  224. subject[i] = replace;
  225. }
  226. return subject;
  227. }
  228. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter)
  229. {
  230. char quote = 0;
  231. bool last_char_delimiter = true;
  232. const char* ptr = string.c_str();
  233. const char* start_ptr = nullptr;
  234. const char* end_ptr = ptr;
  235. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  236. if (num_delimiter_values == 0)
  237. {
  238. string_list.push_back(StripWhitespace(string));
  239. return;
  240. }
  241. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  242. while (*ptr)
  243. {
  244. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  245. // and we're not already in quote mode
  246. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  247. {
  248. quote = *ptr;
  249. }
  250. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  251. else if (*ptr == quote && *(ptr - 1) != '\\')
  252. {
  253. quote = 0;
  254. }
  255. // If we encounter a delimiter while not in quote mode, add the item to the list
  256. else if (*ptr == delimiter && !quote)
  257. {
  258. if (start_ptr)
  259. string_list.emplace_back(start_ptr, end_ptr + 1);
  260. else
  261. string_list.emplace_back();
  262. last_char_delimiter = true;
  263. start_ptr = nullptr;
  264. }
  265. // Otherwise if its not white space or we're in quote mode, advance the pointers
  266. else if (!IsWhitespace(*ptr) || quote)
  267. {
  268. if (!start_ptr)
  269. start_ptr = ptr;
  270. end_ptr = ptr;
  271. last_char_delimiter = false;
  272. }
  273. ptr++;
  274. }
  275. // If there's data pending, add it.
  276. if (start_ptr)
  277. string_list.emplace_back(start_ptr, end_ptr + 1);
  278. }
  279. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character,
  280. bool ignore_repeated_delimiters)
  281. {
  282. int quote_mode_depth = 0;
  283. const char* ptr = string.c_str();
  284. const char* start_ptr = nullptr;
  285. const char* end_ptr = ptr;
  286. while (*ptr)
  287. {
  288. // Increment the quote depth for each quote character encountered
  289. if (*ptr == quote_character)
  290. {
  291. ++quote_mode_depth;
  292. }
  293. // And decrement it for every unquote character
  294. else if (*ptr == unquote_character)
  295. {
  296. --quote_mode_depth;
  297. }
  298. // If we encounter a delimiter while not in quote mode, add the item to the list
  299. if (*ptr == delimiter && quote_mode_depth == 0)
  300. {
  301. if (start_ptr)
  302. string_list.emplace_back(start_ptr, end_ptr + 1);
  303. else if (!ignore_repeated_delimiters)
  304. string_list.emplace_back();
  305. start_ptr = nullptr;
  306. }
  307. // Otherwise if its not white space or we're in quote mode, advance the pointers
  308. else if (!IsWhitespace(*ptr) || quote_mode_depth > 0)
  309. {
  310. if (!start_ptr)
  311. start_ptr = ptr;
  312. end_ptr = ptr;
  313. }
  314. ptr++;
  315. }
  316. // If there's data pending, add it.
  317. if (start_ptr)
  318. string_list.emplace_back(start_ptr, end_ptr + 1);
  319. }
  320. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  321. {
  322. for (size_t i = 0; i < string_list.size(); i++)
  323. {
  324. string += string_list[i];
  325. if (delimiter != '\0' && i < string_list.size() - 1)
  326. string += delimiter;
  327. }
  328. }
  329. String StringUtilities::StripWhitespace(const String& string)
  330. {
  331. return StripWhitespace(StringView(string));
  332. }
  333. RMLUICORE_API String StringUtilities::StripWhitespace(StringView string)
  334. {
  335. const char* start = string.begin();
  336. const char* end = string.end();
  337. while (start < end && IsWhitespace(*start))
  338. start++;
  339. while (end > start && IsWhitespace(*(end - 1)))
  340. end--;
  341. if (start < end)
  342. return String(start, end);
  343. return String();
  344. }
  345. void StringUtilities::TrimTrailingDotZeros(String& string)
  346. {
  347. size_t new_size = string.size();
  348. for (size_t i = string.size() - 1; i < string.size(); i--)
  349. {
  350. if (string[i] == '.')
  351. {
  352. new_size = i;
  353. break;
  354. }
  355. else if (string[i] == '0')
  356. new_size = i;
  357. else
  358. break;
  359. }
  360. if (new_size < string.size())
  361. string.resize(new_size);
  362. }
  363. bool StringUtilities::StartsWith(StringView string, StringView start)
  364. {
  365. if (string.size() < start.size())
  366. return false;
  367. StringView substring(string.begin(), string.begin() + start.size());
  368. return substring == start;
  369. }
  370. bool StringUtilities::StringCompareCaseInsensitive(const StringView lhs, const StringView rhs)
  371. {
  372. if (lhs.size() != rhs.size())
  373. return false;
  374. const char* left = lhs.begin();
  375. const char* right = rhs.begin();
  376. const char* const left_end = lhs.end();
  377. for (; left != left_end; ++left, ++right)
  378. {
  379. if (CharToLower(*left) != CharToLower(*right))
  380. return false;
  381. }
  382. return true;
  383. }
  384. Character StringUtilities::ToCharacter(const char* p)
  385. {
  386. if ((*p & (1 << 7)) == 0)
  387. return static_cast<Character>(*p);
  388. int num_bytes = 0;
  389. int code = 0;
  390. if ((*p & 0b1110'0000) == 0b1100'0000)
  391. {
  392. num_bytes = 2;
  393. code = (*p & 0b0001'1111);
  394. }
  395. else if ((*p & 0b1111'0000) == 0b1110'0000)
  396. {
  397. num_bytes = 3;
  398. code = (*p & 0b0000'1111);
  399. }
  400. else if ((*p & 0b1111'1000) == 0b1111'0000)
  401. {
  402. num_bytes = 4;
  403. code = (*p & 0b0000'0111);
  404. }
  405. else
  406. {
  407. // Invalid begin byte
  408. return Character::Null;
  409. }
  410. for (int i = 1; i < num_bytes; i++)
  411. {
  412. const char byte = *(p + i);
  413. if ((byte & 0b1100'0000) != 0b1000'0000)
  414. {
  415. // Invalid continuation byte
  416. return Character::Null;
  417. }
  418. code = ((code << 6) | (byte & 0b0011'1111));
  419. }
  420. return static_cast<Character>(code);
  421. }
  422. String StringUtilities::ToUTF8(Character character)
  423. {
  424. return ToUTF8(&character, 1);
  425. }
  426. String StringUtilities::ToUTF8(const Character* characters, int num_characters)
  427. {
  428. String result;
  429. result.reserve(num_characters);
  430. bool invalid_character = false;
  431. for (int i = 0; i < num_characters; i++)
  432. {
  433. char32_t c = (char32_t)characters[i];
  434. constexpr int l3 = 0b0000'0111;
  435. constexpr int l4 = 0b0000'1111;
  436. constexpr int l5 = 0b0001'1111;
  437. constexpr int l6 = 0b0011'1111;
  438. constexpr int h1 = 0b1000'0000;
  439. constexpr int h2 = 0b1100'0000;
  440. constexpr int h3 = 0b1110'0000;
  441. constexpr int h4 = 0b1111'0000;
  442. if (c < 0x80)
  443. result += (char)c;
  444. else if (c < 0x800)
  445. result += {char(((c >> 6) & l5) | h2), char((c & l6) | h1)};
  446. else if (c < 0x10000)
  447. result += {char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  448. else if (c <= 0x10FFFF)
  449. result += {char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  450. else
  451. invalid_character = true;
  452. }
  453. if (invalid_character)
  454. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  455. return result;
  456. }
  457. size_t StringUtilities::LengthUTF8(StringView string_view)
  458. {
  459. const char* const p_end = string_view.end();
  460. // Skip any continuation bytes at the beginning
  461. const char* p = string_view.begin();
  462. size_t num_continuation_bytes = 0;
  463. while (p != p_end)
  464. {
  465. if ((*p & 0b1100'0000) == 0b1000'0000)
  466. ++num_continuation_bytes;
  467. ++p;
  468. }
  469. return string_view.size() - num_continuation_bytes;
  470. }
  471. int StringUtilities::ConvertCharacterOffsetToByteOffset(StringView string, int character_offset)
  472. {
  473. if (character_offset >= (int)string.size())
  474. return (int)string.size();
  475. int character_count = 0;
  476. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  477. {
  478. character_count += 1;
  479. if (character_count > character_offset)
  480. return (int)it.offset();
  481. }
  482. return (int)string.size();
  483. }
  484. int StringUtilities::ConvertByteOffsetToCharacterOffset(StringView string, int byte_offset)
  485. {
  486. int character_count = 0;
  487. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  488. {
  489. if (it.offset() >= byte_offset)
  490. break;
  491. character_count += 1;
  492. }
  493. return character_count;
  494. }
  495. StringView::StringView()
  496. {
  497. const char* empty_string = "";
  498. p_begin = empty_string;
  499. p_end = empty_string;
  500. }
  501. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  502. {
  503. RMLUI_ASSERT(p_end >= p_begin);
  504. }
  505. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size()) {}
  506. StringView::StringView(const String& string, size_t offset) : p_begin(string.data() + offset), p_end(string.data() + string.size()) {}
  507. StringView::StringView(const String& string, size_t offset, size_t count) :
  508. p_begin(string.data() + offset), p_end(string.data() + std::min<size_t>(offset + count, string.size()))
  509. {}
  510. bool StringView::operator==(const StringView& other) const
  511. {
  512. return size() == other.size() && strncmp(p_begin, other.p_begin, size()) == 0;
  513. }
  514. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p) {}
  515. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data()) {}
  516. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset) {}
  517. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset) {}
  518. StringIteratorU8& StringIteratorU8::operator++()
  519. {
  520. RMLUI_ASSERT(p < view.end());
  521. ++p;
  522. SeekForward();
  523. return *this;
  524. }
  525. StringIteratorU8& StringIteratorU8::operator--()
  526. {
  527. RMLUI_ASSERT(p >= view.begin());
  528. --p;
  529. SeekBack();
  530. return *this;
  531. }
  532. inline void StringIteratorU8::SeekBack()
  533. {
  534. p = StringUtilities::SeekBackwardUTF8(p, view.begin());
  535. }
  536. inline void StringIteratorU8::SeekForward()
  537. {
  538. p = StringUtilities::SeekForwardUTF8(p, view.end());
  539. }
  540. } // namespace Rml