StringUtilities.cpp 14 KB

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