StringUtilities.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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, StringView string, char delimiter)
  235. {
  236. ExpandString(string_list, string, delimiter, '\0', '\0');
  237. }
  238. void StringUtilities::ExpandString(StringList& string_list, StringView string, char delimiter, char quote_character, char unquote_character)
  239. {
  240. // Quote depth is incremented for each encountered quote character, and decremented on unquote character. If quote
  241. // and unquote are the same characters, then quote mode is instead toggled.
  242. int quote_mode_depth = 0;
  243. const char* start_ptr = nullptr;
  244. const char* last_ptr = nullptr;
  245. string_list.reserve(string_list.size() + std::count(string.begin(), string.end(), delimiter) + 1);
  246. for (const char& c : string)
  247. {
  248. if (c == quote_character)
  249. {
  250. if (quote_character == unquote_character)
  251. quote_mode_depth = (quote_mode_depth == 0 ? 1 : 0);
  252. else
  253. ++quote_mode_depth;
  254. }
  255. else if (c == unquote_character)
  256. {
  257. --quote_mode_depth;
  258. }
  259. if (c == delimiter && quote_mode_depth == 0)
  260. {
  261. if (start_ptr)
  262. string_list.emplace_back(start_ptr, last_ptr + 1);
  263. else if (!IsWhitespace(delimiter))
  264. string_list.emplace_back();
  265. start_ptr = nullptr;
  266. }
  267. else if (!IsWhitespace(c) || quote_mode_depth > 0)
  268. {
  269. if (!start_ptr)
  270. start_ptr = &c;
  271. last_ptr = &c;
  272. }
  273. }
  274. if (start_ptr)
  275. string_list.emplace_back(start_ptr, last_ptr + 1);
  276. else if (!IsWhitespace(delimiter) || std::all_of(string.begin(), string.end(), IsWhitespace))
  277. string_list.emplace_back();
  278. }
  279. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  280. {
  281. for (size_t i = 0; i < string_list.size(); i++)
  282. {
  283. string += string_list[i];
  284. if (delimiter != '\0' && i < string_list.size() - 1)
  285. string += delimiter;
  286. }
  287. }
  288. String StringUtilities::StripWhitespace(const String& string)
  289. {
  290. return StripWhitespace(StringView(string));
  291. }
  292. RMLUICORE_API String StringUtilities::StripWhitespace(StringView string)
  293. {
  294. const char* start = string.begin();
  295. const char* end = string.end();
  296. while (start < end && IsWhitespace(*start))
  297. start++;
  298. while (end > start && IsWhitespace(*(end - 1)))
  299. end--;
  300. if (start < end)
  301. return String(start, end);
  302. return String();
  303. }
  304. void StringUtilities::TrimTrailingDotZeros(String& string)
  305. {
  306. size_t new_size = string.size();
  307. for (size_t i = string.size() - 1; i < string.size(); i--)
  308. {
  309. if (string[i] == '.')
  310. {
  311. new_size = i;
  312. break;
  313. }
  314. else if (string[i] == '0')
  315. new_size = i;
  316. else
  317. break;
  318. }
  319. if (new_size < string.size())
  320. string.resize(new_size);
  321. }
  322. bool StringUtilities::StartsWith(StringView string, StringView start)
  323. {
  324. if (string.size() < start.size())
  325. return false;
  326. StringView substring(string.begin(), string.begin() + start.size());
  327. return substring == start;
  328. }
  329. bool StringUtilities::EndsWith(StringView string, StringView end)
  330. {
  331. if (string.size() < end.size())
  332. return false;
  333. StringView substring(string.end() - end.size(), string.end());
  334. return substring == end;
  335. }
  336. bool StringUtilities::StringCompareCaseInsensitive(const StringView lhs, const StringView rhs)
  337. {
  338. if (lhs.size() != rhs.size())
  339. return false;
  340. const char* left = lhs.begin();
  341. const char* right = rhs.begin();
  342. const char* const left_end = lhs.end();
  343. for (; left != left_end; ++left, ++right)
  344. {
  345. if (CharToLower(*left) != CharToLower(*right))
  346. return false;
  347. }
  348. return true;
  349. }
  350. Character StringUtilities::ToCharacter(const char* p, const char* p_end)
  351. {
  352. RMLUI_ASSERTMSG(p && p != p_end, "ToCharacter expects a valid, non-empty input string");
  353. if ((*p & (1 << 7)) == 0)
  354. return static_cast<Character>(*p);
  355. int num_bytes = 0;
  356. int code = 0;
  357. if ((*p & 0b1110'0000) == 0b1100'0000)
  358. {
  359. num_bytes = 2;
  360. code = (*p & 0b0001'1111);
  361. }
  362. else if ((*p & 0b1111'0000) == 0b1110'0000)
  363. {
  364. num_bytes = 3;
  365. code = (*p & 0b0000'1111);
  366. }
  367. else if ((*p & 0b1111'1000) == 0b1111'0000)
  368. {
  369. num_bytes = 4;
  370. code = (*p & 0b0000'0111);
  371. }
  372. else
  373. {
  374. // Invalid begin byte
  375. return Character::Null;
  376. }
  377. if (p_end - p < num_bytes)
  378. return Character::Null;
  379. for (int i = 1; i < num_bytes; i++)
  380. {
  381. const char byte = *(p + i);
  382. if ((byte & 0b1100'0000) != 0b1000'0000)
  383. {
  384. // Invalid continuation byte
  385. return Character::Null;
  386. }
  387. code = ((code << 6) | (byte & 0b0011'1111));
  388. }
  389. return static_cast<Character>(code);
  390. }
  391. size_t StringUtilities::BytesUTF8(Character character)
  392. {
  393. char32_t c = (char32_t)character;
  394. if (c < 0x80)
  395. return 1;
  396. else if (c < 0x800)
  397. return 2;
  398. else if (c < 0x10000)
  399. return 3;
  400. else if (c <= 0x10FFFF)
  401. return 4;
  402. else
  403. // Invalid character.
  404. return 0;
  405. }
  406. String StringUtilities::ToUTF8(Character character)
  407. {
  408. return ToUTF8(&character, 1);
  409. }
  410. String StringUtilities::ToUTF8(const Character* characters, int num_characters)
  411. {
  412. String result;
  413. result.reserve(num_characters);
  414. bool invalid_character = false;
  415. for (int i = 0; i < num_characters; i++)
  416. {
  417. char32_t c = (char32_t)characters[i];
  418. constexpr int l3 = 0b0000'0111;
  419. constexpr int l4 = 0b0000'1111;
  420. constexpr int l5 = 0b0001'1111;
  421. constexpr int l6 = 0b0011'1111;
  422. constexpr int h1 = 0b1000'0000;
  423. constexpr int h2 = 0b1100'0000;
  424. constexpr int h3 = 0b1110'0000;
  425. constexpr int h4 = 0b1111'0000;
  426. if (c < 0x80)
  427. result += (char)c;
  428. else if (c < 0x800)
  429. result += {char(((c >> 6) & l5) | h2), char((c & l6) | h1)};
  430. else if (c < 0x10000)
  431. result += {char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  432. else if (c <= 0x10FFFF)
  433. result += {char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1)};
  434. else
  435. invalid_character = true;
  436. }
  437. if (invalid_character)
  438. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  439. return result;
  440. }
  441. size_t StringUtilities::LengthUTF8(StringView string_view)
  442. {
  443. const char* const p_end = string_view.end();
  444. // Skip any continuation bytes at the beginning
  445. const char* p = string_view.begin();
  446. size_t num_continuation_bytes = 0;
  447. while (p != p_end)
  448. {
  449. if ((*p & 0b1100'0000) == 0b1000'0000)
  450. ++num_continuation_bytes;
  451. ++p;
  452. }
  453. return string_view.size() - num_continuation_bytes;
  454. }
  455. int StringUtilities::ConvertCharacterOffsetToByteOffset(StringView string, int character_offset)
  456. {
  457. if (character_offset >= (int)string.size())
  458. return (int)string.size();
  459. int character_count = 0;
  460. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  461. {
  462. character_count += 1;
  463. if (character_count > character_offset)
  464. return (int)it.offset();
  465. }
  466. return (int)string.size();
  467. }
  468. int StringUtilities::ConvertByteOffsetToCharacterOffset(StringView string, int byte_offset)
  469. {
  470. int character_count = 0;
  471. for (auto it = StringIteratorU8(string.begin(), string.begin(), string.end()); it; ++it)
  472. {
  473. if (it.offset() >= byte_offset)
  474. break;
  475. character_count += 1;
  476. }
  477. return character_count;
  478. }
  479. StringView::StringView()
  480. {
  481. const char* empty_string = "";
  482. p_begin = empty_string;
  483. p_end = empty_string;
  484. }
  485. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  486. {
  487. RMLUI_ASSERT(p_end >= p_begin);
  488. }
  489. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size()) {}
  490. StringView::StringView(const String& string, size_t offset) : p_begin(string.data() + offset), p_end(string.data() + string.size()) {}
  491. StringView::StringView(const String& string, size_t offset, size_t count) :
  492. p_begin(string.data() + offset), p_end(string.data() + std::min<size_t>(offset + count, string.size()))
  493. {}
  494. bool StringView::operator==(const StringView& other) const
  495. {
  496. return size() == other.size() && strncmp(p_begin, other.p_begin, size()) == 0;
  497. }
  498. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p) {}
  499. StringIteratorU8::StringIteratorU8(StringView string) : view(string), p(view.begin()) {}
  500. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data()) {}
  501. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset) {}
  502. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset) {}
  503. StringIteratorU8& StringIteratorU8::operator++()
  504. {
  505. RMLUI_ASSERT(p < view.end());
  506. ++p;
  507. SeekForward();
  508. return *this;
  509. }
  510. StringIteratorU8& StringIteratorU8::operator--()
  511. {
  512. RMLUI_ASSERT(p >= view.begin());
  513. --p;
  514. SeekBack();
  515. return *this;
  516. }
  517. inline void StringIteratorU8::SeekBack()
  518. {
  519. p = StringUtilities::SeekBackwardUTF8(p, view.begin());
  520. }
  521. inline void StringIteratorU8::SeekForward()
  522. {
  523. p = StringUtilities::SeekForwardUTF8(p, view.end());
  524. }
  525. } // namespace Rml