StringUtilities.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 "precompiled.h"
  29. #include "../../Include/RmlUi/Core/StringUtilities.h"
  30. #include <stdio.h>
  31. #include <stdarg.h>
  32. namespace Rml {
  33. namespace Core {
  34. static int FormatString(String& string, size_t max_size, const char* format, va_list argument_list)
  35. {
  36. const int INTERNAL_BUFFER_SIZE = 1024;
  37. static char buffer[INTERNAL_BUFFER_SIZE];
  38. char* buffer_ptr = buffer;
  39. if (max_size + 1 > INTERNAL_BUFFER_SIZE)
  40. buffer_ptr = new char[max_size + 1];
  41. int length = vsnprintf(buffer_ptr, max_size, format, argument_list);
  42. buffer_ptr[length >= 0 ? length : max_size] = '\0';
  43. #ifdef RMLUI_DEBUG
  44. if (length == -1)
  45. {
  46. Log::Message(Log::LT_WARNING, "FormatString: String truncated to %d bytes when processing %s", max_size, format);
  47. }
  48. #endif
  49. string = buffer_ptr;
  50. if (buffer_ptr != buffer)
  51. delete[] buffer_ptr;
  52. return length;
  53. }
  54. int FormatString(String& string, size_t max_size, const char* format, ...)
  55. {
  56. va_list argument_list;
  57. va_start(argument_list, format);
  58. int result = FormatString(string, (int)max_size, format, argument_list);
  59. va_end(argument_list);
  60. return result;
  61. }
  62. String CreateString(size_t max_size, const char* format, ...)
  63. {
  64. String result;
  65. result.reserve(max_size);
  66. va_list argument_list;
  67. va_start(argument_list, format);
  68. FormatString(result, max_size, format, argument_list);
  69. va_end(argument_list);
  70. return result;
  71. }
  72. String StringUtilities::ToLower(const String& string) {
  73. String str_lower = string;
  74. std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(), [](char c) {
  75. if (c >= 'A' && c <= 'Z')
  76. c += char( 'a' - 'A' );
  77. return c;
  78. }
  79. );
  80. return str_lower;
  81. }
  82. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  83. {
  84. size_t pos = 0;
  85. while ((pos = subject.find(search, pos)) != String::npos) {
  86. subject.replace(pos, search.length(), replace);
  87. pos += replace.length();
  88. }
  89. return subject;
  90. }
  91. String StringUtilities::Replace(String subject, char search, char replace)
  92. {
  93. const size_t size = subject.size();
  94. for (size_t i = 0; i < size; i++)
  95. {
  96. if (subject[i] == search)
  97. subject[i] = replace;
  98. }
  99. return subject;
  100. }
  101. // Expands character-delimited list of values in a single string to a whitespace-trimmed list of values.
  102. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter)
  103. {
  104. char quote = 0;
  105. bool last_char_delimiter = true;
  106. const char* ptr = string.c_str();
  107. const char* start_ptr = nullptr;
  108. const char* end_ptr = ptr;
  109. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  110. if (num_delimiter_values == 0)
  111. {
  112. string_list.push_back(StripWhitespace(string));
  113. return;
  114. }
  115. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  116. while (*ptr)
  117. {
  118. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  119. // and we're not already in quote mode
  120. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  121. {
  122. quote = *ptr;
  123. }
  124. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  125. else if (*ptr == quote && *(ptr-1) != '\\')
  126. {
  127. quote = 0;
  128. }
  129. // If we encounter a delimiter while not in quote mode, add the item to the list
  130. else if (*ptr == delimiter && !quote)
  131. {
  132. if (start_ptr)
  133. string_list.emplace_back(start_ptr, end_ptr + 1);
  134. else
  135. string_list.emplace_back();
  136. last_char_delimiter = true;
  137. start_ptr = nullptr;
  138. }
  139. // Otherwise if its not white space or we're in quote mode, advance the pointers
  140. else if (!IsWhitespace(*ptr) || quote)
  141. {
  142. if (!start_ptr)
  143. start_ptr = ptr;
  144. end_ptr = ptr;
  145. last_char_delimiter = false;
  146. }
  147. ptr++;
  148. }
  149. // If there's data pending, add it.
  150. if (start_ptr)
  151. string_list.emplace_back(start_ptr, end_ptr + 1);
  152. }
  153. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character, bool ignore_repeated_delimiters)
  154. {
  155. int quote_mode_depth = 0;
  156. const char* ptr = string.c_str();
  157. const char* start_ptr = nullptr;
  158. const char* end_ptr = ptr;
  159. while (*ptr)
  160. {
  161. // Increment the quote depth for each quote character encountered
  162. if (*ptr == quote_character)
  163. {
  164. ++quote_mode_depth;
  165. }
  166. // And decrement it for every unquote character
  167. else if (*ptr == unquote_character)
  168. {
  169. --quote_mode_depth;
  170. }
  171. // If we encounter a delimiter while not in quote mode, add the item to the list
  172. if (*ptr == delimiter && quote_mode_depth == 0)
  173. {
  174. if (start_ptr)
  175. string_list.emplace_back(start_ptr, end_ptr + 1);
  176. else if(!ignore_repeated_delimiters)
  177. string_list.emplace_back();
  178. start_ptr = nullptr;
  179. }
  180. // Otherwise if its not white space or we're in quote mode, advance the pointers
  181. else if (!IsWhitespace(*ptr) || quote_mode_depth > 0)
  182. {
  183. if (!start_ptr)
  184. start_ptr = ptr;
  185. end_ptr = ptr;
  186. }
  187. ptr++;
  188. }
  189. // If there's data pending, add it.
  190. if (start_ptr)
  191. string_list.emplace_back(start_ptr, end_ptr + 1);
  192. }
  193. // Joins a list of string values into a single string separated by a character delimiter.
  194. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  195. {
  196. for (size_t i = 0; i < string_list.size(); i++)
  197. {
  198. string += string_list[i];
  199. if (delimiter != '\0' && i < string_list.size() - 1)
  200. string += delimiter;
  201. }
  202. }
  203. // Strip whitespace characters from the beginning and end of a string.
  204. String StringUtilities::StripWhitespace(const String& string)
  205. {
  206. const char* start = string.c_str();
  207. const char* end = start + string.size();
  208. while (start < end && IsWhitespace(*start))
  209. start++;
  210. while (end > start && IsWhitespace(*(end - 1)))
  211. end--;
  212. if (start < end)
  213. return String(start, end);
  214. return String();
  215. }
  216. // Operators for STL containers using strings.
  217. bool StringUtilities::StringComparei::operator()(const String& lhs, const String& rhs) const
  218. {
  219. return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
  220. }
  221. Character StringUtilities::ToCharacter(const char* p)
  222. {
  223. if ((*p & (1 << 7)) == 0)
  224. return static_cast<Character>(*p);
  225. int num_bytes = 0;
  226. int code = 0;
  227. if ((*p & 0b1110'0000) == 0b1100'0000)
  228. {
  229. num_bytes = 2;
  230. code = (*p & 0b0001'1111);
  231. }
  232. else if ((*p & 0b1111'0000) == 0b1110'0000)
  233. {
  234. num_bytes = 3;
  235. code = (*p & 0b0000'1111);
  236. }
  237. else if ((*p & 0b1111'1000) == 0b1111'0000)
  238. {
  239. num_bytes = 4;
  240. code = (*p & 0b0000'0111);
  241. }
  242. else
  243. {
  244. // Invalid begin byte
  245. return Character::Null;
  246. }
  247. for (int i = 1; i < num_bytes; i++)
  248. {
  249. const char byte = *(p + i);
  250. if ((byte & 0b1100'0000) != 0b1000'0000)
  251. {
  252. // Invalid continuation byte
  253. ++p;
  254. return Character::Null;
  255. }
  256. code = ((code << 6) | (byte & 0b0011'1111));
  257. }
  258. return static_cast<Character>(code);
  259. }
  260. String StringUtilities::ToUTF8(Character character)
  261. {
  262. return ToUTF8(&character, 1);
  263. }
  264. String StringUtilities::ToUTF8(const Character* characters, int num_characters)
  265. {
  266. String result;
  267. result.reserve(num_characters);
  268. bool invalid_character = false;
  269. for (int i = 0; i < num_characters; i++)
  270. {
  271. char32_t c = (char32_t)characters[i];
  272. constexpr int l3 = 0b0000'0111;
  273. constexpr int l4 = 0b0000'1111;
  274. constexpr int l5 = 0b0001'1111;
  275. constexpr int l6 = 0b0011'1111;
  276. constexpr int h1 = 0b1000'0000;
  277. constexpr int h2 = 0b1100'0000;
  278. constexpr int h3 = 0b1110'0000;
  279. constexpr int h4 = 0b1111'0000;
  280. if (c < 0x80)
  281. result += (char)c;
  282. else if (c < 0x800)
  283. result += { char(((c >> 6) & l5) | h2), char((c & l6) | h1) };
  284. else if (c < 0x10000)
  285. result += { char(((c >> 12) & l4) | h3), char(((c >> 6) & l6) | h1), char((c & l6) | h1) };
  286. else if (c <= 0x10FFFF)
  287. result += { char(((c >> 18) & l3) | h4), char(((c >> 12) & l6) | h1), char(((c >> 6) & l6) | h1), char((c & l6) | h1) };
  288. else
  289. invalid_character = true;
  290. }
  291. if (invalid_character)
  292. Log::Message(Log::LT_WARNING, "One or more invalid code points encountered while encoding to UTF-8.");
  293. return result;
  294. }
  295. size_t StringUtilities::LengthUTF8(StringView string_view)
  296. {
  297. const char* const p_end = string_view.end();
  298. // Skip any continuation bytes at the beginning
  299. const char* p = string_view.begin();
  300. size_t num_continuation_bytes = 0;
  301. while (p != p_end)
  302. {
  303. if ((*p & 0b1100'0000) == 0b1000'0000)
  304. ++num_continuation_bytes;
  305. ++p;
  306. }
  307. return string_view.size() - num_continuation_bytes;
  308. }
  309. U16String StringUtilities::ToUTF16(const String& input)
  310. {
  311. U16String result;
  312. if (input.empty())
  313. return result;
  314. std::vector<Character> characters;
  315. characters.reserve(input.size());
  316. for (auto it = StringIteratorU8(input); it; ++it)
  317. characters.push_back(*it);
  318. result.reserve(input.size());
  319. bool valid_characters = true;
  320. for (Character character : characters)
  321. {
  322. char32_t c = (char32_t)character;
  323. if (c <= 0xD7FF || (c >= 0xE000 && c <= 0xFFFF))
  324. {
  325. // Single 16-bit code unit.
  326. result += (char16_t)c;
  327. }
  328. else if (c >= 0x10000 && c <= 0x10FFFF)
  329. {
  330. // Encode as two 16-bit code units.
  331. char32_t c_shift = c - 0x10000;
  332. char16_t w1 = (0xD800 | ((c_shift >> 10) & 0x3FF));
  333. char16_t w2 = (0xDC00 | (c_shift & 0x3FF));
  334. result += {w1, w2};
  335. }
  336. else
  337. {
  338. valid_characters = false;
  339. }
  340. }
  341. if (!valid_characters)
  342. Log::Message(Log::LT_WARNING, "Invalid characters encountered while converting UTF-8 string to UTF-16.");
  343. return result;
  344. }
  345. String StringUtilities::ToUTF8(const U16String& input)
  346. {
  347. std::vector<Character> characters;
  348. characters.reserve(input.size());
  349. bool valid_input = true;
  350. char16_t w1 = 0;
  351. for (char16_t w : input)
  352. {
  353. if (w <= 0xD7FF || w >= 0xE000)
  354. {
  355. // Single 16-bit code unit.
  356. characters.push_back((Character)(w));
  357. }
  358. else
  359. {
  360. // Two 16-bit code units.
  361. if (!w1 && w < 0xDC00)
  362. {
  363. w1 = w;
  364. }
  365. else if (w1 && w >= 0xDC00)
  366. {
  367. characters.push_back((Character)(((((char32_t)w1 & 0x3FF) << 10) | ((char32_t)(w) & 0x3FF)) + 0x10000u));
  368. w1 = 0;
  369. }
  370. else
  371. {
  372. valid_input = false;
  373. }
  374. }
  375. }
  376. String result;
  377. if (characters.size() > 0)
  378. result = StringUtilities::ToUTF8(characters.data(), (int)characters.size());
  379. if (!valid_input)
  380. Log::Message(Log::LT_WARNING, "Invalid characters encountered while converting UTF-16 string to UTF-8.");
  381. return result;
  382. }
  383. StringView::StringView(const char* p_begin, const char* p_end) : p_begin(p_begin), p_end(p_end)
  384. {
  385. RMLUI_ASSERT(p_end >= p_begin);
  386. }
  387. StringView::StringView(const String& string) : p_begin(string.data()), p_end(string.data() + string.size())
  388. {}
  389. StringView::StringView(const String& string, size_t offset) : p_begin(string.data()), p_end(string.data() + string.size())
  390. {}
  391. 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()))
  392. {}
  393. bool StringView::operator==(const StringView& other) const {
  394. return (p_end - p_begin) == (other.p_end - other.p_begin) && strcmp(p_begin, other.p_begin) == 0;
  395. }
  396. StringIteratorU8::StringIteratorU8(const char* p_begin, const char* p, const char* p_end) : view(p_begin, p_end), p(p)
  397. {}
  398. StringIteratorU8::StringIteratorU8(const String& string) : view(string), p(string.data())
  399. {}
  400. StringIteratorU8::StringIteratorU8(const String& string, size_t offset) : view(string), p(string.data() + offset)
  401. {}
  402. StringIteratorU8::StringIteratorU8(const String& string, size_t offset, size_t count) : view(string, 0, offset + count), p(string.data() + offset)
  403. {}
  404. StringIteratorU8& StringIteratorU8::operator++() {
  405. RMLUI_ASSERT(p != view.end());
  406. ++p;
  407. SeekForward();
  408. return *this;
  409. }
  410. StringIteratorU8& StringIteratorU8::operator--() {
  411. RMLUI_ASSERT(p - 1 != view.begin());
  412. --p;
  413. SeekBack();
  414. return *this;
  415. }
  416. inline void StringIteratorU8::SeekBack() {
  417. p = StringUtilities::SeekBackwardUTF8(p, view.end());
  418. }
  419. inline void StringIteratorU8::SeekForward() {
  420. p = StringUtilities::SeekForwardUTF8(p, view.end());
  421. }
  422. }
  423. }