StringUtilities.cpp 13 KB

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