StringUtilities.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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 (i > 0)
  56. {
  57. RMLUI_ASSERT(string.size() == (size_t)length);
  58. break;
  59. }
  60. if ((size_t)length < max_size)
  61. {
  62. string = buffer_ptr;
  63. break;
  64. }
  65. string.resize((size_t)length);
  66. max_size = (size_t)length + 1;
  67. buffer_ptr = &(*string.begin()); // C++17 Upgrade: Replace with string.data()
  68. }
  69. return length;
  70. }
  71. int FormatString(String& string, const char* format, ...)
  72. {
  73. va_list argument_list;
  74. va_start(argument_list, format);
  75. int result = FormatString(string, format, argument_list);
  76. va_end(argument_list);
  77. return result;
  78. }
  79. String CreateString(const char* format, ...)
  80. {
  81. String result;
  82. va_list argument_list;
  83. va_start(argument_list, format);
  84. FormatString(result, format, argument_list);
  85. va_end(argument_list);
  86. return result;
  87. }
  88. static inline char CharToLower(char c)
  89. {
  90. if (c >= 'A' && c <= 'Z')
  91. c += char('a' - 'A');
  92. return c;
  93. }
  94. String StringUtilities::ToLower(String string)
  95. {
  96. std::transform(string.begin(), string.end(), string.begin(), &CharToLower);
  97. return string;
  98. }
  99. String StringUtilities::ToUpper(String string)
  100. {
  101. std::transform(string.begin(), string.end(), string.begin(), [](char c) {
  102. if (c >= 'a' && c <= 'z')
  103. c -= char('a' - 'A');
  104. return c;
  105. });
  106. return string;
  107. }
  108. RMLUICORE_API String StringUtilities::EncodeRml(const String& string)
  109. {
  110. String result;
  111. result.reserve(string.size());
  112. for (char c : string)
  113. {
  114. switch (c)
  115. {
  116. case '<': result += "&lt;"; break;
  117. case '>': result += "&gt;"; break;
  118. case '&': result += "&amp;"; break;
  119. case '"': result += "&quot;"; break;
  120. default: result += c; break;
  121. }
  122. }
  123. return result;
  124. }
  125. String StringUtilities::DecodeRml(const String& s)
  126. {
  127. String result;
  128. result.reserve(s.size());
  129. for (size_t i = 0; i < s.size();)
  130. {
  131. if (s[i] == '&')
  132. {
  133. if (s[i + 1] == 'l' && s[i + 2] == 't' && s[i + 3] == ';')
  134. {
  135. result += "<";
  136. i += 4;
  137. continue;
  138. }
  139. else if (s[i + 1] == 'g' && s[i + 2] == 't' && s[i + 3] == ';')
  140. {
  141. result += ">";
  142. i += 4;
  143. continue;
  144. }
  145. else if (s[i + 1] == 'a' && s[i + 2] == 'm' && s[i + 3] == 'p' && s[i + 4] == ';')
  146. {
  147. result += "&";
  148. i += 5;
  149. continue;
  150. }
  151. else if (s[i + 1] == 'q' && s[i + 2] == 'u' && s[i + 3] == 'o' && s[i + 4] == 't' && s[i + 5] == ';')
  152. {
  153. result += "\"";
  154. i += 6;
  155. continue;
  156. }
  157. else if (s[i + 1] == '#')
  158. {
  159. size_t start = i + 2;
  160. if (s[i + 2] == 'x')
  161. {
  162. start++;
  163. size_t j = 0;
  164. for (; j < 8; j++)
  165. {
  166. const auto& c = s[start + j];
  167. if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))
  168. break;
  169. }
  170. if (j > 0 && s[start + j] == ';')
  171. {
  172. String tmp = s.substr(start, j);
  173. const char* begin = tmp.c_str();
  174. char* end;
  175. unsigned long code_point = strtoul(begin, &end, 16);
  176. if (code_point != 0 && code_point != ULONG_MAX)
  177. {
  178. result += ToUTF8(static_cast<Character>(code_point));
  179. i = start + (end - begin) + 1;
  180. continue;
  181. }
  182. }
  183. }
  184. else
  185. {
  186. size_t j = 0;
  187. for (; j < 8; j++)
  188. {
  189. const auto& c = s[start + j];
  190. if (!(c >= '0' && c <= '9'))
  191. break;
  192. }
  193. if (j > 0 && s[start + j] == ';')
  194. {
  195. String tmp = s.substr(start, j);
  196. const char* begin = tmp.c_str();
  197. char* end;
  198. unsigned long code_point = strtoul(begin, &end, 10);
  199. if (code_point != 0 && code_point != ULONG_MAX)
  200. {
  201. result += ToUTF8(static_cast<Character>(code_point));
  202. i = start + (end - begin) + 1;
  203. continue;
  204. }
  205. }
  206. }
  207. }
  208. }
  209. result += s[i];
  210. i += 1;
  211. }
  212. return result;
  213. }
  214. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  215. {
  216. size_t pos = 0;
  217. while ((pos = subject.find(search, pos)) != String::npos)
  218. {
  219. subject.replace(pos, search.length(), replace);
  220. pos += replace.length();
  221. }
  222. return subject;
  223. }
  224. String StringUtilities::Replace(String subject, char search, char replace)
  225. {
  226. const size_t size = subject.size();
  227. for (size_t i = 0; i < size; i++)
  228. {
  229. if (subject[i] == search)
  230. subject[i] = replace;
  231. }
  232. return subject;
  233. }
  234. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, bool ignore_repeated_delimiters)
  235. {
  236. char quote = 0;
  237. bool last_char_delimiter = true;
  238. const char* ptr = string.c_str();
  239. const char* start_ptr = nullptr;
  240. const char* end_ptr = ptr;
  241. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  242. if (num_delimiter_values == 0)
  243. {
  244. string_list.push_back(StripWhitespace(string));
  245. return;
  246. }
  247. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  248. while (*ptr)
  249. {
  250. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  251. // and we're not already in quote mode
  252. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  253. {
  254. quote = *ptr;
  255. }
  256. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  257. else if (*ptr == quote && *(ptr - 1) != '\\')
  258. {
  259. quote = 0;
  260. }
  261. // If we encounter a delimiter while not in quote mode, add the item to the list
  262. else if (*ptr == delimiter && !quote)
  263. {
  264. if (start_ptr)
  265. string_list.emplace_back(start_ptr, end_ptr + 1);
  266. else if (!ignore_repeated_delimiters)
  267. string_list.emplace_back();
  268. last_char_delimiter = true;
  269. start_ptr = nullptr;
  270. }
  271. // Otherwise if its not white space or we're in quote mode, advance the pointers
  272. else if (!IsWhitespace(*ptr) || quote)
  273. {
  274. if (!start_ptr)
  275. start_ptr = ptr;
  276. end_ptr = ptr;
  277. last_char_delimiter = false;
  278. }
  279. ptr++;
  280. }
  281. // If there's data pending, add it.
  282. if (start_ptr)
  283. string_list.emplace_back(start_ptr, end_ptr + 1);
  284. }
  285. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character,
  286. bool ignore_repeated_delimiters)
  287. {
  288. int quote_mode_depth = 0;
  289. const char* ptr = string.c_str();
  290. const char* start_ptr = nullptr;
  291. const char* end_ptr = ptr;
  292. while (*ptr)
  293. {
  294. // Increment the quote depth for each quote character encountered
  295. if (*ptr == quote_character)
  296. {
  297. ++quote_mode_depth;
  298. }
  299. // And decrement it for every unquote character
  300. else if (*ptr == unquote_character)
  301. {
  302. --quote_mode_depth;
  303. }
  304. // If we encounter a delimiter while not in quote mode, add the item to the list
  305. if (*ptr == delimiter && quote_mode_depth == 0)
  306. {
  307. if (start_ptr)
  308. string_list.emplace_back(start_ptr, end_ptr + 1);
  309. else if (!ignore_repeated_delimiters)
  310. string_list.emplace_back();
  311. start_ptr = nullptr;
  312. }
  313. // Otherwise if its not white space or we're in quote mode, advance the pointers
  314. else if (!IsWhitespace(*ptr) || quote_mode_depth > 0)
  315. {
  316. if (!start_ptr)
  317. start_ptr = ptr;
  318. end_ptr = ptr;
  319. }
  320. ptr++;
  321. }
  322. // If there's data pending, add it.
  323. if (start_ptr)
  324. string_list.emplace_back(start_ptr, end_ptr + 1);
  325. }
  326. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  327. {
  328. for (size_t i = 0; i < string_list.size(); i++)
  329. {
  330. string += string_list[i];
  331. if (delimiter != '\0' && i < string_list.size() - 1)
  332. string += delimiter;
  333. }
  334. }
  335. String StringUtilities::StripWhitespace(const String& string)
  336. {
  337. return StripWhitespace(StringView(string));
  338. }
  339. RMLUICORE_API String StringUtilities::StripWhitespace(StringView string)
  340. {
  341. const char* start = string.begin();
  342. const char* end = string.end();
  343. while (start < end && IsWhitespace(*start))
  344. start++;
  345. while (end > start && IsWhitespace(*(end - 1)))
  346. end--;
  347. if (start < end)
  348. return String(start, end);
  349. return String();
  350. }
  351. void StringUtilities::TrimTrailingDotZeros(String& string)
  352. {
  353. size_t new_size = string.size();
  354. for (size_t i = string.size() - 1; i < string.size(); i--)
  355. {
  356. if (string[i] == '.')
  357. {
  358. new_size = i;
  359. break;
  360. }
  361. else if (string[i] == '0')
  362. new_size = i;
  363. else
  364. break;
  365. }
  366. if (new_size < string.size())
  367. string.resize(new_size);
  368. }
  369. bool StringUtilities::StartsWith(StringView string, StringView start)
  370. {
  371. if (string.size() < start.size())
  372. return false;
  373. StringView substring(string.begin(), string.begin() + start.size());
  374. return substring == start;
  375. }
  376. bool StringUtilities::EndsWith(StringView string, StringView end)
  377. {
  378. if (string.size() < end.size())
  379. return false;
  380. StringView substring(string.end() - end.size(), string.end());
  381. return substring == end;
  382. }
  383. bool StringUtilities::StringCompareCaseInsensitive(const StringView lhs, const StringView rhs)
  384. {
  385. if (lhs.size() != rhs.size())
  386. return false;
  387. const char* left = lhs.begin();
  388. const char* right = rhs.begin();
  389. const char* const left_end = lhs.end();
  390. for (; left != left_end; ++left, ++right)
  391. {
  392. if (CharToLower(*left) != CharToLower(*right))
  393. return false;
  394. }
  395. return true;
  396. }
  397. Character StringUtilities::ToCharacter(const char* p, const char* p_end)
  398. {
  399. RMLUI_ASSERTMSG(p && p != p_end, "ToCharacter expects a valid, non-empty input string");
  400. if ((*p & (1 << 7)) == 0)
  401. return static_cast<Character>(*p);
  402. int num_bytes = 0;
  403. int code = 0;
  404. if ((*p & 0b1110'0000) == 0b1100'0000)
  405. {
  406. num_bytes = 2;
  407. code = (*p & 0b0001'1111);
  408. }
  409. else if ((*p & 0b1111'0000) == 0b1110'0000)
  410. {
  411. num_bytes = 3;
  412. code = (*p & 0b0000'1111);
  413. }
  414. else if ((*p & 0b1111'1000) == 0b1111'0000)
  415. {
  416. num_bytes = 4;
  417. code = (*p & 0b0000'0111);
  418. }
  419. else
  420. {
  421. // Invalid begin byte
  422. return Character::Null;
  423. }
  424. if (p_end - p < num_bytes)
  425. return Character::Null;
  426. for (int i = 1; i < num_bytes; i++)
  427. {
  428. const char byte = *(p + i);
  429. if ((byte & 0b1100'0000) != 0b1000'0000)
  430. {
  431. // Invalid continuation byte
  432. return Character::Null;
  433. }
  434. code = ((code << 6) | (byte & 0b0011'1111));
  435. }
  436. return static_cast<Character>(code);
  437. }
  438. size_t StringUtilities::BytesUTF8(Character character)
  439. {
  440. char32_t c = (char32_t)character;
  441. if (c < 0x80)
  442. return 1;
  443. else if (c < 0x800)
  444. return 2;
  445. else if (c < 0x10000)
  446. return 3;
  447. else if (c <= 0x10FFFF)
  448. return 4;
  449. else
  450. // Invalid character.
  451. return 0;
  452. }
  453. String StringUtilities::ToUTF8(Character character)
  454. {
  455. return ToUTF8(&character, 1);
  456. }
  457. String StringUtilities::ToUTF8(const Character* characters, int num_characters)
  458. {
  459. String result;
  460. result.reserve(num_characters);
  461. bool invalid_character = false;
  462. for (int i = 0; i < num_characters; i++)
  463. {
  464. char32_t c = (char32_t)characters[i];
  465. constexpr int l3 = 0b0000'0111;
  466. constexpr int l4 = 0b0000'1111;
  467. constexpr int l5 = 0b0001'1111;
  468. constexpr int l6 = 0b0011'1111;
  469. constexpr int h1 = 0b1000'0000;
  470. constexpr int h2 = 0b1100'0000;
  471. constexpr int h3 = 0b1110'0000;
  472. constexpr int h4 = 0b1111'0000;
  473. if (c < 0x80)
  474. result += (char)c;
  475. else if (c < 0x800)
  476. result += {char(((c >> 6) & l5) | h2), char((c & l6) | h1)};
  477. else if (c < 0x10000)
  478. result += {char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  479. else if (c <= 0x10FFFF)
  480. result += {char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  481. else
  482. invalid_character = true;
  483. }
  484. if (invalid_character)
  485. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  486. return result;
  487. }
  488. size_t StringUtilities::LengthUTF8(StringView string_view)
  489. {
  490. const char* const p_end = string_view.end();
  491. // Skip any continuation bytes at the beginning
  492. const char* p = string_view.begin();
  493. size_t num_continuation_bytes = 0;
  494. while (p != p_end)
  495. {
  496. if ((*p & 0b1100'0000) == 0b1000'0000)
  497. ++num_continuation_bytes;
  498. ++p;
  499. }
  500. return string_view.size() - num_continuation_bytes;
  501. }
  502. int StringUtilities::ConvertCharacterOffsetToByteOffset(StringView string, int character_offset)
  503. {
  504. if (character_offset >= (int)string.size())
  505. return (int)string.size();
  506. int character_count = 0;
  507. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  508. {
  509. character_count += 1;
  510. if (character_count > character_offset)
  511. return (int)it.offset();
  512. }
  513. return (int)string.size();
  514. }
  515. int StringUtilities::ConvertByteOffsetToCharacterOffset(StringView string, int byte_offset)
  516. {
  517. int character_count = 0;
  518. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  519. {
  520. if (it.offset() >= byte_offset)
  521. break;
  522. character_count += 1;
  523. }
  524. return character_count;
  525. }
  526. StringView::StringView()
  527. {
  528. const char* empty_string = "";
  529. p_begin = empty_string;
  530. p_end = empty_string;
  531. }
  532. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  533. {
  534. RMLUI_ASSERT(p_end >= p_begin);
  535. }
  536. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size()) {}
  537. StringView::StringView(const String& string, size_t offset) : p_begin(string.data() + offset), p_end(string.data() + string.size()) {}
  538. StringView::StringView(const String& string, size_t offset, size_t count) :
  539. p_begin(string.data() + offset), p_end(string.data() + std::min<size_t>(offset + count, string.size()))
  540. {}
  541. bool StringView::operator==(const StringView& other) const
  542. {
  543. return size() == other.size() && strncmp(p_begin, other.p_begin, size()) == 0;
  544. }
  545. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p) {}
  546. StringIteratorU8::StringIteratorU8(StringView string) : view(string), p(view.begin()) {}
  547. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data()) {}
  548. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset) {}
  549. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset) {}
  550. StringIteratorU8& StringIteratorU8::operator++()
  551. {
  552. RMLUI_ASSERT(p < view.end());
  553. ++p;
  554. SeekForward();
  555. return *this;
  556. }
  557. StringIteratorU8& StringIteratorU8::operator--()
  558. {
  559. RMLUI_ASSERT(p >= view.begin());
  560. --p;
  561. SeekBack();
  562. return *this;
  563. }
  564. inline void StringIteratorU8::SeekBack()
  565. {
  566. p = StringUtilities::SeekBackwardUTF8(p, view.begin());
  567. }
  568. inline void StringIteratorU8::SeekForward()
  569. {
  570. p = StringUtilities::SeekForwardUTF8(p, view.end());
  571. }
  572. } // namespace Rml