StringUtilities.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  2. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  3. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  4. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  5. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  6. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  7. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  8. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  9. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  10. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  11. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  12. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  13. #include "..\..\Include\RmlUi\Core\StringUtilities.h"
  14. /*
  15. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  16. *
  17. * For the latest information, see http://github.com/mikke89/RmlUi
  18. *
  19. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  20. * Copyright (c) 2019 The RmlUi Team, and contributors
  21. *
  22. * Permission is hereby granted, free of charge, to any person obtaining a copy
  23. * of this software and associated documentation files (the "Software"), to deal
  24. * in the Software without restriction, including without limitation the rights
  25. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  26. * copies of the Software, and to permit persons to whom the Software is
  27. * furnished to do so, subject to the following conditions:
  28. *
  29. * The above copyright notice and this permission notice shall be included in
  30. * all copies or substantial portions of the Software.
  31. *
  32. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  33. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  34. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  35. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  36. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38. * THE SOFTWARE.
  39. *
  40. */
  41. #include "precompiled.h"
  42. #include "../../Include/RmlUi/Core/StringUtilities.h"
  43. #include <ctype.h>
  44. #include <stdio.h>
  45. #include <stdarg.h>
  46. namespace Rml {
  47. namespace Core {
  48. static bool UTF8toUCS2(const String& input, WString& output);
  49. static bool UTF16toUTF8(const WString& input, String& output);
  50. static int FormatString(String& string, size_t max_size, const char* format, va_list argument_list)
  51. {
  52. const int INTERNAL_BUFFER_SIZE = 1024;
  53. static char buffer[INTERNAL_BUFFER_SIZE];
  54. char* buffer_ptr = buffer;
  55. if (max_size + 1 > INTERNAL_BUFFER_SIZE)
  56. buffer_ptr = new char[max_size + 1];
  57. int length = vsnprintf(buffer_ptr, max_size, format, argument_list);
  58. buffer_ptr[length >= 0 ? length : max_size] = '\0';
  59. #ifdef RMLUI_DEBUG
  60. if (length == -1)
  61. {
  62. Log::Message(Log::LT_WARNING, "FormatString: String truncated to %d bytes when processing %s", max_size, format);
  63. }
  64. #endif
  65. string = buffer_ptr;
  66. if (buffer_ptr != buffer)
  67. delete[] buffer_ptr;
  68. return length;
  69. }
  70. int FormatString(String& string, size_t max_size, const char* format, ...)
  71. {
  72. va_list argument_list;
  73. va_start(argument_list, format);
  74. int result = FormatString(string, (int)max_size, format, argument_list);
  75. va_end(argument_list);
  76. return result;
  77. }
  78. String CreateString(size_t max_size, const char* format, ...)
  79. {
  80. String result;
  81. result.reserve(max_size);
  82. va_list argument_list;
  83. va_start(argument_list, format);
  84. FormatString(result, max_size, format, argument_list);
  85. va_end(argument_list);
  86. return result;
  87. }
  88. String StringUtilities::ToLower(const String& string) {
  89. String str_lower = string;
  90. std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(), ::tolower);
  91. return str_lower;
  92. }
  93. WString StringUtilities::ToUTF16(const String& str)
  94. {
  95. // TODO: Convert to UTF16 instead of UCS2
  96. WString result;
  97. if (!UTF8toUCS2(str, result))
  98. Log::Message(Log::LT_WARNING, "Failed to convert UTF8 string to UTF16.");
  99. return result;
  100. }
  101. String StringUtilities::ToUTF8(const WString& wstr)
  102. {
  103. /// TODO: Convert from UTF-16 instead.
  104. String result;
  105. if(!UTF16toUTF8(wstr, result))
  106. Log::Message(Log::LT_WARNING, "Failed to convert UCS2 string to UTF8.");
  107. return result;
  108. }
  109. size_t StringUtilities::LengthU8(StringView string_view)
  110. {
  111. const char* const p_end = string_view.end();
  112. // Skip any continuation bytes at the beginning
  113. const char* p = string_view.begin();
  114. size_t num_continuation_bytes = 0;
  115. while (p != p_end)
  116. {
  117. if ((*p & 0b1100'0000) == 0b1000'0000)
  118. ++num_continuation_bytes;
  119. ++p;
  120. }
  121. return string_view.size() - num_continuation_bytes;
  122. }
  123. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  124. {
  125. size_t pos = 0;
  126. while ((pos = subject.find(search, pos)) != String::npos) {
  127. subject.replace(pos, search.length(), replace);
  128. pos += replace.length();
  129. }
  130. return subject;
  131. }
  132. String StringUtilities::Replace(String subject, char search, char replace)
  133. {
  134. const size_t size = subject.size();
  135. for (size_t i = 0; i < size; i++)
  136. {
  137. if (subject[i] == search)
  138. subject[i] = replace;
  139. }
  140. return subject;
  141. }
  142. // Expands character-delimited list of values in a single string to a whitespace-trimmed list of values.
  143. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter)
  144. {
  145. char quote = 0;
  146. bool last_char_delimiter = true;
  147. const char* ptr = string.c_str();
  148. const char* start_ptr = nullptr;
  149. const char* end_ptr = ptr;
  150. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  151. if (num_delimiter_values == 0)
  152. {
  153. string_list.push_back(StripWhitespace(string));
  154. return;
  155. }
  156. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  157. while (*ptr)
  158. {
  159. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  160. // and we're not already in quote mode
  161. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  162. {
  163. quote = *ptr;
  164. }
  165. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  166. else if (*ptr == quote && *(ptr-1) != '\\')
  167. {
  168. quote = 0;
  169. }
  170. // If we encounter a delimiter while not in quote mode, add the item to the list
  171. else if (*ptr == delimiter && !quote)
  172. {
  173. if (start_ptr)
  174. string_list.emplace_back(start_ptr, end_ptr + 1);
  175. else
  176. string_list.emplace_back();
  177. last_char_delimiter = true;
  178. start_ptr = nullptr;
  179. }
  180. // Otherwise if its not white space or we're in quote mode, advance the pointers
  181. else if (!isspace(*ptr) || quote)
  182. {
  183. if (!start_ptr)
  184. start_ptr = ptr;
  185. end_ptr = ptr;
  186. last_char_delimiter = false;
  187. }
  188. ptr++;
  189. }
  190. // If there's data pending, add it.
  191. if (start_ptr)
  192. string_list.emplace_back(start_ptr, end_ptr + 1);
  193. }
  194. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, bool ignore_repeated_delimiters)
  195. {
  196. int quote_mode_depth = 0;
  197. const char* ptr = string.c_str();
  198. const char* start_ptr = nullptr;
  199. const char* end_ptr = ptr;
  200. while (*ptr)
  201. {
  202. // Increment the quote depth for each quote character encountered
  203. if (*ptr == quote_character)
  204. {
  205. ++quote_mode_depth;
  206. }
  207. // And decrement it for every unquote character
  208. else if (*ptr == unquote_character)
  209. {
  210. --quote_mode_depth;
  211. }
  212. // If we encounter a delimiter while not in quote mode, add the item to the list
  213. if (*ptr == delimiter && quote_mode_depth == 0)
  214. {
  215. if (start_ptr)
  216. string_list.emplace_back(start_ptr, end_ptr + 1);
  217. else if(!ignore_repeated_delimiters)
  218. string_list.emplace_back();
  219. start_ptr = nullptr;
  220. }
  221. // Otherwise if its not white space or we're in quote mode, advance the pointers
  222. else if (!isspace(*ptr) || quote_mode_depth > 0)
  223. {
  224. if (!start_ptr)
  225. start_ptr = ptr;
  226. end_ptr = ptr;
  227. }
  228. ptr++;
  229. }
  230. // If there's data pending, add it.
  231. if (start_ptr)
  232. string_list.emplace_back(start_ptr, end_ptr + 1);
  233. }
  234. // Joins a list of string values into a single string separated by a character delimiter.
  235. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  236. {
  237. for (size_t i = 0; i < string_list.size(); i++)
  238. {
  239. string += string_list[i];
  240. if (delimiter != '\0' && i < string_list.size() - 1)
  241. string += delimiter;
  242. }
  243. }
  244. // Strip whitespace characters from the beginning and end of a string.
  245. String StringUtilities::StripWhitespace(const String& string)
  246. {
  247. const char* start = string.c_str();
  248. const char* end = start + string.size();
  249. while (start < end && IsWhitespace(*start))
  250. start++;
  251. while (end > start && IsWhitespace(*(end - 1)))
  252. end--;
  253. if (start < end)
  254. return String(start, end);
  255. return String();
  256. }
  257. CodePoint StringUtilities::ToCodePoint(const char* p)
  258. {
  259. if ((*p & (1 << 7)) == 0)
  260. return static_cast<CodePoint>(*p);
  261. int num_bytes = 0;
  262. int code = 0;
  263. if ((*p & 0b1110'0000) == 0b1100'0000)
  264. {
  265. num_bytes = 2;
  266. code = (*p & 0b0001'1111);
  267. }
  268. else if ((*p & 0b1111'0000) == 0b1110'0000)
  269. {
  270. num_bytes = 3;
  271. code = (*p & 0b0000'1111);
  272. }
  273. else if ((*p & 0b1111'1000) == 0b1111'0000)
  274. {
  275. num_bytes = 4;
  276. code = (*p & 0b0000'0111);
  277. }
  278. else
  279. {
  280. // Invalid begin byte
  281. return CodePoint::Null;
  282. }
  283. for (int i = 1; i < num_bytes; i++)
  284. {
  285. const char byte = *(p + i);
  286. if ((byte & 0b1100'0000) != 0b1000'0000)
  287. {
  288. // Invalid continuation byte
  289. ++p;
  290. return CodePoint::Null;
  291. }
  292. code = ((code << 6) | (byte & 0b0011'1111));
  293. }
  294. return static_cast<CodePoint>(code);
  295. }
  296. String StringUtilities::ToUTF8(CodePoint code_point)
  297. {
  298. return ToUTF8(&code_point, 1);
  299. }
  300. String StringUtilities::ToUTF8(const CodePoint* code_points, int num_code_points)
  301. {
  302. String result;
  303. bool invalid_code_point = false;
  304. for (int i = 0; i < num_code_points; i++)
  305. {
  306. unsigned int c = (unsigned int)code_points[i];
  307. constexpr int l3 = 0b0000'0111;
  308. constexpr int l4 = 0b0000'1111;
  309. constexpr int l5 = 0b0001'1111;
  310. constexpr int l6 = 0b0011'1111;
  311. constexpr int h1 = 0b1000'0000;
  312. constexpr int h2 = 0b1100'0000;
  313. constexpr int h3 = 0b1110'0000;
  314. constexpr int h4 = 0b1111'0000;
  315. if (c < 0x80)
  316. result += (char)c;
  317. else if (c < 0x800)
  318. result += { char(((c >> 6)& l5) | h2), char((c& l6) | h1) };
  319. else if (c < 0x10000)
  320. result += { char(((c >> 12)& l4) | h3), char(((c >> 6)& l6) | h1), char((c& l6) | h1) };
  321. else if (c <= 0x10FFFF)
  322. result += { char(((c >> 18)& l3) | h4), char(((c >> 12)& l6) | h1), char(((c >> 6)& l6) | h1), char((c& l6) | h1) };
  323. else
  324. invalid_code_point = true;
  325. }
  326. if (invalid_code_point)
  327. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  328. return result;
  329. }
  330. // Operators for STL containers using strings.
  331. bool StringUtilities::StringComparei::operator()(const String& lhs, const String& rhs) const
  332. {
  333. return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
  334. }
  335. // Defines, helper functions for the UTF8 / UCS2 conversion functions.
  336. constexpr int _NXT = 0x80;
  337. constexpr int _SEQ2 = 0xc0;
  338. constexpr int _SEQ3 = 0xe0;
  339. constexpr int _SEQ4 = 0xf0;
  340. constexpr int _SEQ5 = 0xf8;
  341. constexpr int _SEQ6 = 0xfc;
  342. constexpr int _BOM = 0xfeff;
  343. static int __wchar_forbidden(unsigned int sym)
  344. {
  345. // Surrogate pairs
  346. if (sym >= 0xd800 && sym <= 0xdfff)
  347. return -1;
  348. return 0;
  349. }
  350. static int __utf8_forbidden(unsigned char octet)
  351. {
  352. switch (octet)
  353. {
  354. case 0xc0:
  355. case 0xc1:
  356. case 0xf5:
  357. case 0xff:
  358. return -1;
  359. default:
  360. return 0;
  361. }
  362. }
  363. // Converts a character array in UTF-8 encoding to a vector of words.
  364. static bool UTF8toUCS2(const String& input, WString& output)
  365. {
  366. if (input.empty())
  367. return true;
  368. output.reserve(input.size());
  369. unsigned char* p = (unsigned char*) input.c_str();
  370. unsigned char* end = p + input.size();
  371. // Skip the UTF-8 byte order marker if it exists.
  372. if (input.substr(0, 3) == "\xEF\xBB\xBF")
  373. p += 3;
  374. int num_bytes;
  375. for (; p < end; p += num_bytes)
  376. {
  377. if (__utf8_forbidden(*p) != 0)
  378. return false;
  379. // Get number of bytes for one wide character.
  380. wchar_t high;
  381. num_bytes = 1;
  382. if ((*p & 0x80) == 0)
  383. {
  384. high = (wchar_t)*p;
  385. }
  386. else if ((*p & 0xe0) == _SEQ2)
  387. {
  388. num_bytes = 2;
  389. high = (wchar_t)(*p & 0x1f);
  390. }
  391. else if ((*p & 0xf0) == _SEQ3)
  392. {
  393. num_bytes = 3;
  394. high = (wchar_t)(*p & 0x0f);
  395. }
  396. else if ((*p & 0xf8) == _SEQ4)
  397. {
  398. num_bytes = 4;
  399. high = (wchar_t)(*p & 0x07);
  400. }
  401. else if ((*p & 0xfc) == _SEQ5)
  402. {
  403. num_bytes = 5;
  404. high = (wchar_t)(*p & 0x03);
  405. }
  406. else if ((*p & 0xfe) == _SEQ6)
  407. {
  408. num_bytes = 6;
  409. high = (wchar_t)(*p & 0x01);
  410. }
  411. else
  412. {
  413. return false;
  414. }
  415. // Does the sequence header tell us the truth about length?
  416. if (end - p <= num_bytes - 1)
  417. {
  418. return false;
  419. }
  420. // Validate the sequence. All symbols must have higher bits set to 10xxxxxx.
  421. if (num_bytes > 1)
  422. {
  423. int i;
  424. for (i = 1; i < num_bytes; i++)
  425. {
  426. if ((p[i] & 0b1100'0000) != _NXT)
  427. break;
  428. }
  429. if (i != num_bytes)
  430. {
  431. return false;
  432. }
  433. }
  434. // Make up a single UCS-4 (32-bit) character from the required number of UTF-8 tokens. The first byte has
  435. // been determined earlier, the second and subsequent bytes contribute the first six of their bits into the
  436. // final character code.
  437. unsigned int ucs4_char = 0;
  438. int num_bits = 0;
  439. for (int i = 1; i < num_bytes; i++)
  440. {
  441. ucs4_char |= (wchar_t)(p[num_bytes - i] & 0x3f) << num_bits;
  442. num_bits += 6;
  443. }
  444. ucs4_char |= high << num_bits;
  445. // Check for surrogate pairs.
  446. if (__wchar_forbidden(ucs4_char) != 0)
  447. {
  448. return false;
  449. }
  450. // Only add the character to the output if it exists in the Basic Multilingual Plane (ie, fits in a single
  451. // word).
  452. if (ucs4_char <= 0xffff)
  453. output.push_back((wchar_t) ucs4_char);
  454. }
  455. return true;
  456. }
  457. // Converts an array of words in UCS-2 encoding into a character array in UTF-8 encoding.
  458. static bool UTF16toUTF8(const WString& input, String& output)
  459. {
  460. std::vector<CodePoint> code_points;
  461. code_points.reserve(input.size());
  462. bool valid_input = true;
  463. wchar_t w1 = 0;
  464. const wchar_t* w = input.data();
  465. const wchar_t* wlim = w + input.size();
  466. for (; w < wlim; w++)
  467. {
  468. if (*w <= 0xD7FF || *w >= 0xE000)
  469. {
  470. // Single 16-bit code unit.
  471. code_points.push_back((CodePoint)(*w));
  472. }
  473. else
  474. {
  475. // Two 16-bit code units.
  476. if (!w1 && *w < 0xDC00)
  477. {
  478. w1 = *w;
  479. }
  480. else if (w1 && *w >= 0xDC00)
  481. {
  482. code_points.push_back((CodePoint)(((((unsigned int)w1 & 0x3FF) << 10) | ((unsigned int)(*w) & 0x3FF)) + 0x10000u));
  483. w1 = 0;
  484. }
  485. else
  486. {
  487. valid_input = false;
  488. }
  489. }
  490. }
  491. if(code_points.size() > 0)
  492. output = StringUtilities::ToUTF8(code_points.data(), (int)code_points.size());
  493. return valid_input;
  494. }
  495. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  496. {}
  497. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size())
  498. {}
  499. StringView::StringView(const String& string, size_t offset) : p_begin(string.data()), p_end(string.data() + string.size())
  500. {}
  501. StringView::StringView(const String& string, size_t offset, size_t count) : p_begin(string.data()), p_end(string.data() + std::min(offset + count, string.size()))
  502. {}
  503. bool StringView::operator==(const StringView& other) const {
  504. return (p_end - p_begin) == (other.p_end - other.p_begin) && strcmp(p_begin, other.p_begin) == 0;
  505. }
  506. // TODO: Remove seek on construction
  507. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p)
  508. {
  509. SeekForward();
  510. }
  511. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data())
  512. {
  513. SeekForward();
  514. }
  515. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset)
  516. {
  517. SeekForward();
  518. }
  519. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset)
  520. {
  521. SeekForward();
  522. }
  523. StringIteratorU8& StringIteratorU8::operator++() {
  524. RMLUI_ASSERT(p != view.end());
  525. ++p;
  526. SeekForward();
  527. return *this;
  528. }
  529. StringIteratorU8& StringIteratorU8::operator--() {
  530. RMLUI_ASSERT(p - 1 != view.begin());
  531. --p;
  532. SeekBack();
  533. return *this;
  534. }
  535. inline void StringIteratorU8::SeekBack() {
  536. p = StringUtilities::SeekBackU8(p, view.end());
  537. }
  538. inline void StringIteratorU8::SeekForward() {
  539. p = StringUtilities::SeekForwardU8(p, view.end());
  540. }
  541. }
  542. }