StringUtilities.cpp 15 KB

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