StringUtilities.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 UTF8toUTF16(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. WString result;
  96. if (!UTF8toUTF16(str, result))
  97. Log::Message(Log::LT_WARNING, "Invalid characters encountered while converting UTF-8 string to UTF-16.");
  98. return result;
  99. }
  100. String StringUtilities::ToUTF8(const WString& wstr)
  101. {
  102. String result;
  103. if(!UTF16toUTF8(wstr, result))
  104. Log::Message(Log::LT_WARNING, "Invalid characters encountered while converting UTF-16 string to UTF-8.");
  105. return result;
  106. }
  107. size_t StringUtilities::LengthUTF8(StringView string_view)
  108. {
  109. const char* const p_end = string_view.end();
  110. // Skip any continuation bytes at the beginning
  111. const char* p = string_view.begin();
  112. size_t num_continuation_bytes = 0;
  113. while (p != p_end)
  114. {
  115. if ((*p & 0b1100'0000) == 0b1000'0000)
  116. ++num_continuation_bytes;
  117. ++p;
  118. }
  119. return string_view.size() - num_continuation_bytes;
  120. }
  121. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  122. {
  123. size_t pos = 0;
  124. while ((pos = subject.find(search, pos)) != String::npos) {
  125. subject.replace(pos, search.length(), replace);
  126. pos += replace.length();
  127. }
  128. return subject;
  129. }
  130. String StringUtilities::Replace(String subject, char search, char replace)
  131. {
  132. const size_t size = subject.size();
  133. for (size_t i = 0; i < size; i++)
  134. {
  135. if (subject[i] == search)
  136. subject[i] = replace;
  137. }
  138. return subject;
  139. }
  140. // Expands character-delimited list of values in a single string to a whitespace-trimmed list of values.
  141. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter)
  142. {
  143. char quote = 0;
  144. bool last_char_delimiter = true;
  145. const char* ptr = string.c_str();
  146. const char* start_ptr = nullptr;
  147. const char* end_ptr = ptr;
  148. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  149. if (num_delimiter_values == 0)
  150. {
  151. string_list.push_back(StripWhitespace(string));
  152. return;
  153. }
  154. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  155. while (*ptr)
  156. {
  157. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  158. // and we're not already in quote mode
  159. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  160. {
  161. quote = *ptr;
  162. }
  163. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  164. else if (*ptr == quote && *(ptr-1) != '\\')
  165. {
  166. quote = 0;
  167. }
  168. // If we encounter a delimiter while not in quote mode, add the item to the list
  169. else if (*ptr == delimiter && !quote)
  170. {
  171. if (start_ptr)
  172. string_list.emplace_back(start_ptr, end_ptr + 1);
  173. else
  174. string_list.emplace_back();
  175. last_char_delimiter = true;
  176. start_ptr = nullptr;
  177. }
  178. // Otherwise if its not white space or we're in quote mode, advance the pointers
  179. else if (!isspace(*ptr) || quote)
  180. {
  181. if (!start_ptr)
  182. start_ptr = ptr;
  183. end_ptr = ptr;
  184. last_char_delimiter = false;
  185. }
  186. ptr++;
  187. }
  188. // If there's data pending, add it.
  189. if (start_ptr)
  190. string_list.emplace_back(start_ptr, end_ptr + 1);
  191. }
  192. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, bool ignore_repeated_delimiters)
  193. {
  194. int quote_mode_depth = 0;
  195. const char* ptr = string.c_str();
  196. const char* start_ptr = nullptr;
  197. const char* end_ptr = ptr;
  198. while (*ptr)
  199. {
  200. // Increment the quote depth for each quote character encountered
  201. if (*ptr == quote_character)
  202. {
  203. ++quote_mode_depth;
  204. }
  205. // And decrement it for every unquote character
  206. else if (*ptr == unquote_character)
  207. {
  208. --quote_mode_depth;
  209. }
  210. // If we encounter a delimiter while not in quote mode, add the item to the list
  211. if (*ptr == delimiter && quote_mode_depth == 0)
  212. {
  213. if (start_ptr)
  214. string_list.emplace_back(start_ptr, end_ptr + 1);
  215. else if(!ignore_repeated_delimiters)
  216. string_list.emplace_back();
  217. start_ptr = nullptr;
  218. }
  219. // Otherwise if its not white space or we're in quote mode, advance the pointers
  220. else if (!isspace(*ptr) || quote_mode_depth > 0)
  221. {
  222. if (!start_ptr)
  223. start_ptr = ptr;
  224. end_ptr = ptr;
  225. }
  226. ptr++;
  227. }
  228. // If there's data pending, add it.
  229. if (start_ptr)
  230. string_list.emplace_back(start_ptr, end_ptr + 1);
  231. }
  232. // Joins a list of string values into a single string separated by a character delimiter.
  233. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  234. {
  235. for (size_t i = 0; i < string_list.size(); i++)
  236. {
  237. string += string_list[i];
  238. if (delimiter != '\0' && i < string_list.size() - 1)
  239. string += delimiter;
  240. }
  241. }
  242. // Strip whitespace characters from the beginning and end of a string.
  243. String StringUtilities::StripWhitespace(const String& string)
  244. {
  245. const char* start = string.c_str();
  246. const char* end = start + string.size();
  247. while (start < end && IsWhitespace(*start))
  248. start++;
  249. while (end > start && IsWhitespace(*(end - 1)))
  250. end--;
  251. if (start < end)
  252. return String(start, end);
  253. return String();
  254. }
  255. CodePoint StringUtilities::ToCodePoint(const char* p)
  256. {
  257. if ((*p & (1 << 7)) == 0)
  258. return static_cast<CodePoint>(*p);
  259. int num_bytes = 0;
  260. int code = 0;
  261. if ((*p & 0b1110'0000) == 0b1100'0000)
  262. {
  263. num_bytes = 2;
  264. code = (*p & 0b0001'1111);
  265. }
  266. else if ((*p & 0b1111'0000) == 0b1110'0000)
  267. {
  268. num_bytes = 3;
  269. code = (*p & 0b0000'1111);
  270. }
  271. else if ((*p & 0b1111'1000) == 0b1111'0000)
  272. {
  273. num_bytes = 4;
  274. code = (*p & 0b0000'0111);
  275. }
  276. else
  277. {
  278. // Invalid begin byte
  279. return CodePoint::Null;
  280. }
  281. for (int i = 1; i < num_bytes; i++)
  282. {
  283. const char byte = *(p + i);
  284. if ((byte & 0b1100'0000) != 0b1000'0000)
  285. {
  286. // Invalid continuation byte
  287. ++p;
  288. return CodePoint::Null;
  289. }
  290. code = ((code << 6) | (byte & 0b0011'1111));
  291. }
  292. return static_cast<CodePoint>(code);
  293. }
  294. String StringUtilities::ToUTF8(CodePoint code_point)
  295. {
  296. return ToUTF8(&code_point, 1);
  297. }
  298. String StringUtilities::ToUTF8(const CodePoint* code_points, int num_code_points)
  299. {
  300. String result;
  301. bool invalid_code_point = false;
  302. for (int i = 0; i < num_code_points; i++)
  303. {
  304. unsigned int c = (unsigned int)code_points[i];
  305. constexpr int l3 = 0b0000'0111;
  306. constexpr int l4 = 0b0000'1111;
  307. constexpr int l5 = 0b0001'1111;
  308. constexpr int l6 = 0b0011'1111;
  309. constexpr int h1 = 0b1000'0000;
  310. constexpr int h2 = 0b1100'0000;
  311. constexpr int h3 = 0b1110'0000;
  312. constexpr int h4 = 0b1111'0000;
  313. if (c < 0x80)
  314. result += (char)c;
  315. else if (c < 0x800)
  316. result += { char(((c >> 6)& l5) | h2), char((c& l6) | h1) };
  317. else if (c < 0x10000)
  318. result += { char(((c >> 12)& l4) | h3), char(((c >> 6)& l6) | h1), char((c& l6) | h1) };
  319. else if (c <= 0x10FFFF)
  320. result += { char(((c >> 18)& l3) | h4), char(((c >> 12)& l6) | h1), char(((c >> 6)& l6) | h1), char((c& l6) | h1) };
  321. else
  322. invalid_code_point = true;
  323. }
  324. if (invalid_code_point)
  325. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  326. return result;
  327. }
  328. // Operators for STL containers using strings.
  329. bool StringUtilities::StringComparei::operator()(const String& lhs, const String& rhs) const
  330. {
  331. return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
  332. }
  333. // Converts a character array in UTF-8 encoding to a wide string in UTF-16 encoding.
  334. static bool UTF8toUTF16(const String& input, WString& output)
  335. {
  336. if (input.empty())
  337. return true;
  338. std::vector<CodePoint> code_points;
  339. code_points.reserve(input.size());
  340. for (auto it = StringIteratorU8(input); it; ++it)
  341. code_points.push_back(*it);
  342. output.reserve(input.size());
  343. bool valid_characters = true;
  344. for (CodePoint code_point : code_points)
  345. {
  346. unsigned int c = (unsigned int)code_point;
  347. if (c <= 0xD7FF || (c >= 0xE000 && c <= 0xFFFF))
  348. {
  349. // Single 16-bit code unit.
  350. output += (wchar_t)c;
  351. }
  352. else if (c >= 0x10000 && c <= 0x10FFFF)
  353. {
  354. // Encode as two 16-bit code units.
  355. unsigned int c_shift = c - 0x10000;
  356. wchar_t w1 = (0xD800 | ((c_shift >> 10) & 0x3FF));
  357. wchar_t w2 = (0xDC00 | (c_shift & 0x3FF));
  358. output += {w1, w2};
  359. }
  360. else
  361. {
  362. valid_characters = false;
  363. }
  364. }
  365. return valid_characters;
  366. }
  367. // Converts a wide string in UTF-16 encoding into a string in UTF-8 encoding.
  368. static bool UTF16toUTF8(const WString& input, String& output)
  369. {
  370. std::vector<CodePoint> code_points;
  371. code_points.reserve(input.size());
  372. bool valid_input = true;
  373. wchar_t w1 = 0;
  374. for (wchar_t w : input)
  375. {
  376. if (w <= 0xD7FF || w >= 0xE000)
  377. {
  378. // Single 16-bit code unit.
  379. code_points.push_back((CodePoint)(w));
  380. }
  381. else
  382. {
  383. // Two 16-bit code units.
  384. if (!w1 && w < 0xDC00)
  385. {
  386. w1 = w;
  387. }
  388. else if (w1 && w >= 0xDC00)
  389. {
  390. code_points.push_back((CodePoint)(((((unsigned int)w1 & 0x3FF) << 10) | ((unsigned int)(w) & 0x3FF)) + 0x10000u));
  391. w1 = 0;
  392. }
  393. else
  394. {
  395. valid_input = false;
  396. }
  397. }
  398. }
  399. if(code_points.size() > 0)
  400. output = StringUtilities::ToUTF8(code_points.data(), (int)code_points.size());
  401. return valid_input;
  402. }
  403. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  404. {
  405. RMLUI_ASSERT(p_end >= p_begin);
  406. }
  407. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size())
  408. {}
  409. StringView::StringView(const String& string, size_t offset) : p_begin(string.data()), p_end(string.data() + string.size())
  410. {}
  411. 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()))
  412. {}
  413. bool StringView::operator==(const StringView& other) const {
  414. return (p_end - p_begin) == (other.p_end - other.p_begin) && strcmp(p_begin, other.p_begin) == 0;
  415. }
  416. // TODO: Remove seek on construction
  417. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p)
  418. {
  419. SeekForward();
  420. }
  421. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data())
  422. {
  423. SeekForward();
  424. }
  425. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset)
  426. {
  427. SeekForward();
  428. }
  429. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset)
  430. {
  431. SeekForward();
  432. }
  433. StringIteratorU8& StringIteratorU8::operator++() {
  434. RMLUI_ASSERT(p != view.end());
  435. ++p;
  436. SeekForward();
  437. return *this;
  438. }
  439. StringIteratorU8& StringIteratorU8::operator--() {
  440. RMLUI_ASSERT(p - 1 != view.begin());
  441. --p;
  442. SeekBack();
  443. return *this;
  444. }
  445. inline void StringIteratorU8::SeekBack() {
  446. p = StringUtilities::SeekBackU8(p, view.end());
  447. }
  448. inline void StringIteratorU8::SeekForward() {
  449. p = StringUtilities::SeekForwardU8(p, view.end());
  450. }
  451. }
  452. }