StringUtilities.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 bool UTF8toUCS2(const String& input, WString& output);
  36. static bool UCS2toUTF8(const WString& input, String& output);
  37. static int FormatString(String& string, size_t max_size, const char* format, va_list argument_list)
  38. {
  39. const int INTERNAL_BUFFER_SIZE = 1024;
  40. static char buffer[INTERNAL_BUFFER_SIZE];
  41. char* buffer_ptr = buffer;
  42. if (max_size + 1 > INTERNAL_BUFFER_SIZE)
  43. buffer_ptr = new char[max_size + 1];
  44. int length = vsnprintf(buffer_ptr, max_size, format, argument_list);
  45. buffer_ptr[length >= 0 ? length : max_size] = '\0';
  46. #ifdef RMLUI_DEBUG
  47. if (length == -1)
  48. {
  49. Log::Message(Log::LT_WARNING, "FormatString: String truncated to %d bytes when processing %s", max_size, format);
  50. }
  51. #endif
  52. string = buffer_ptr;
  53. if (buffer_ptr != buffer)
  54. delete[] buffer_ptr;
  55. return length;
  56. }
  57. int FormatString(String& string, size_t max_size, const char* format, ...)
  58. {
  59. va_list argument_list;
  60. va_start(argument_list, format);
  61. int result = FormatString(string, (int)max_size, format, argument_list);
  62. va_end(argument_list);
  63. return result;
  64. }
  65. String CreateString(size_t max_size, const char* format, ...)
  66. {
  67. String result;
  68. result.reserve(max_size);
  69. va_list argument_list;
  70. va_start(argument_list, format);
  71. FormatString(result, max_size, format, argument_list);
  72. va_end(argument_list);
  73. return result;
  74. }
  75. String StringUtilities::ToLower(const String& string) {
  76. String str_lower = string;
  77. std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(), ::tolower);
  78. return str_lower;
  79. }
  80. WString StringUtilities::ToUCS2(const String& str)
  81. {
  82. WString result;
  83. if (!UTF8toUCS2(str, result))
  84. Log::Message(Log::LT_WARNING, "Failed to convert UTF8 string to UCS2.");
  85. return result;
  86. }
  87. String StringUtilities::ToUTF8(const WString& wstr)
  88. {
  89. String result;
  90. if(!UCS2toUTF8(wstr, result))
  91. Log::Message(Log::LT_WARNING, "Failed to convert UCS2 string to UTF8.");
  92. return result;
  93. }
  94. String StringUtilities::Replace(String subject, const String& search, const String& replace)
  95. {
  96. size_t pos = 0;
  97. while ((pos = subject.find(search, pos)) != String::npos) {
  98. subject.replace(pos, search.length(), replace);
  99. pos += replace.length();
  100. }
  101. return subject;
  102. }
  103. String StringUtilities::Replace(String subject, char search, char replace)
  104. {
  105. const size_t size = subject.size();
  106. for (size_t i = 0; i < size; i++)
  107. {
  108. if (subject[i] == search)
  109. subject[i] = replace;
  110. }
  111. return subject;
  112. }
  113. // Expands character-delimited list of values in a single string to a whitespace-trimmed list of values.
  114. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter)
  115. {
  116. char quote = 0;
  117. bool last_char_delimiter = true;
  118. const char* ptr = string.c_str();
  119. const char* start_ptr = nullptr;
  120. const char* end_ptr = ptr;
  121. size_t num_delimiter_values = std::count(string.begin(), string.end(), delimiter);
  122. if (num_delimiter_values == 0)
  123. {
  124. string_list.push_back(StripWhitespace(string));
  125. return;
  126. }
  127. string_list.reserve(string_list.size() + num_delimiter_values + 1);
  128. while (*ptr)
  129. {
  130. // Switch into quote mode if the last char was a delimeter ( excluding whitespace )
  131. // and we're not already in quote mode
  132. if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\''))
  133. {
  134. quote = *ptr;
  135. }
  136. // Switch out of quote mode if we encounter a quote that hasn't been escaped
  137. else if (*ptr == quote && *(ptr-1) != '\\')
  138. {
  139. quote = 0;
  140. }
  141. // If we encouter a delimiter while not in quote mode, add the item to the list
  142. else if (*ptr == delimiter && !quote)
  143. {
  144. if (start_ptr)
  145. string_list.emplace_back(start_ptr, end_ptr + 1);
  146. else
  147. string_list.emplace_back();
  148. last_char_delimiter = true;
  149. start_ptr = nullptr;
  150. }
  151. // Otherwise if its not white space or we're in quote mode, advance the pointers
  152. else if (!isspace(*ptr) || quote)
  153. {
  154. if (!start_ptr)
  155. start_ptr = ptr;
  156. end_ptr = ptr;
  157. last_char_delimiter = false;
  158. }
  159. ptr++;
  160. }
  161. // If there's data pending, add it.
  162. if (start_ptr)
  163. string_list.emplace_back(start_ptr, end_ptr + 1);
  164. }
  165. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter, char quote_character, char unquote_character)
  166. {
  167. int quote_mode_depth = 0;
  168. const char* ptr = string.c_str();
  169. const char* start_ptr = nullptr;
  170. const char* end_ptr = ptr;
  171. while (*ptr)
  172. {
  173. // Increment the quote depth for each quote character encountered
  174. if (*ptr == quote_character)
  175. {
  176. ++quote_mode_depth;
  177. }
  178. // And decrement it for every unquote character
  179. else if (*ptr == unquote_character)
  180. {
  181. --quote_mode_depth;
  182. }
  183. // If we encouter a delimiter while not in quote mode, add the item to the list
  184. if (*ptr == delimiter && quote_mode_depth == 0)
  185. {
  186. if (start_ptr)
  187. string_list.emplace_back(start_ptr, end_ptr + 1);
  188. else
  189. string_list.emplace_back();
  190. start_ptr = nullptr;
  191. }
  192. // Otherwise if its not white space or we're in quote mode, advance the pointers
  193. else if (!isspace(*ptr) || quote_mode_depth > 0)
  194. {
  195. if (!start_ptr)
  196. start_ptr = ptr;
  197. end_ptr = ptr;
  198. }
  199. ptr++;
  200. }
  201. // If there's data pending, add it.
  202. if (start_ptr)
  203. string_list.emplace_back(start_ptr, end_ptr + 1);
  204. }
  205. // Joins a list of string values into a single string separated by a character delimiter.
  206. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter)
  207. {
  208. for (size_t i = 0; i < string_list.size(); i++)
  209. {
  210. string += string_list[i];
  211. if (delimiter != '\0' && i < string_list.size() - 1)
  212. string += delimiter;
  213. }
  214. }
  215. // Strip whitespace characters from the beginning and end of a string.
  216. String StringUtilities::StripWhitespace(const String& string)
  217. {
  218. const char* start = string.c_str();
  219. const char* end = start + string.size();
  220. while (start < end && IsWhitespace(*start))
  221. start++;
  222. while (end > start && IsWhitespace(*(end - 1)))
  223. end--;
  224. if (start < end)
  225. return String(start, end);
  226. return String();
  227. }
  228. // Operators for STL containers using strings.
  229. bool StringUtilities::StringComparei::operator()(const String& lhs, const String& rhs) const
  230. {
  231. return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
  232. }
  233. // Defines, helper functions for the UTF8 / UCS2 conversion functions.
  234. #define _NXT 0x80
  235. #define _SEQ2 0xc0
  236. #define _SEQ3 0xe0
  237. #define _SEQ4 0xf0
  238. #define _SEQ5 0xf8
  239. #define _SEQ6 0xfc
  240. #define _BOM 0xfeff
  241. static int __wchar_forbidden(unsigned int sym)
  242. {
  243. // Surrogate pairs
  244. if (sym >= 0xd800 && sym <= 0xdfff)
  245. return -1;
  246. return 0;
  247. }
  248. static int __utf8_forbidden(unsigned char octet)
  249. {
  250. switch (octet)
  251. {
  252. case 0xc0:
  253. case 0xc1:
  254. case 0xf5:
  255. case 0xff:
  256. return -1;
  257. default:
  258. return 0;
  259. }
  260. }
  261. // Converts a character array in UTF-8 encoding to a vector of words.
  262. static bool UTF8toUCS2(const String& input, WString& output)
  263. {
  264. if (input.empty())
  265. return true;
  266. output.reserve(input.size());
  267. unsigned char* p = (unsigned char*) input.c_str();
  268. unsigned char* lim = p + input.size();
  269. // Skip the UTF-8 byte order marker if it exists.
  270. if (input.substr(0, 3) == "\xEF\xBB\xBF")
  271. p += 3;
  272. int num_bytes;
  273. for (; p < lim; p += num_bytes)
  274. {
  275. if (__utf8_forbidden(*p) != 0)
  276. return false;
  277. // Get number of bytes for one wide character.
  278. word high;
  279. num_bytes = 1;
  280. if ((*p & 0x80) == 0)
  281. {
  282. high = (wchar_t)*p;
  283. }
  284. else if ((*p & 0xe0) == _SEQ2)
  285. {
  286. num_bytes = 2;
  287. high = (wchar_t)(*p & 0x1f);
  288. }
  289. else if ((*p & 0xf0) == _SEQ3)
  290. {
  291. num_bytes = 3;
  292. high = (wchar_t)(*p & 0x0f);
  293. }
  294. else if ((*p & 0xf8) == _SEQ4)
  295. {
  296. num_bytes = 4;
  297. high = (wchar_t)(*p & 0x07);
  298. }
  299. else if ((*p & 0xfc) == _SEQ5)
  300. {
  301. num_bytes = 5;
  302. high = (wchar_t)(*p & 0x03);
  303. }
  304. else if ((*p & 0xfe) == _SEQ6)
  305. {
  306. num_bytes = 6;
  307. high = (wchar_t)(*p & 0x01);
  308. }
  309. else
  310. {
  311. return false;
  312. }
  313. // Does the sequence header tell us the truth about length?
  314. if (lim - p <= num_bytes - 1)
  315. {
  316. return false;
  317. }
  318. // Validate the sequence. All symbols must have higher bits set to 10xxxxxx.
  319. if (num_bytes > 1)
  320. {
  321. int i;
  322. for (i = 1; i < num_bytes; i++)
  323. {
  324. if ((p[i] & 0xc0) != _NXT)
  325. break;
  326. }
  327. if (i != num_bytes)
  328. {
  329. return false;
  330. }
  331. }
  332. // Make up a single UCS-4 (32-bit) character from the required number of UTF-8 tokens. The first byte has
  333. // been determined earlier, the second and subsequent bytes contribute the first six of their bits into the
  334. // final character code.
  335. unsigned int ucs4_char = 0;
  336. int num_bits = 0;
  337. for (int i = 1; i < num_bytes; i++)
  338. {
  339. ucs4_char |= (word)(p[num_bytes - i] & 0x3f) << num_bits;
  340. num_bits += 6;
  341. }
  342. ucs4_char |= high << num_bits;
  343. // Check for surrogate pairs.
  344. if (__wchar_forbidden(ucs4_char) != 0)
  345. {
  346. return false;
  347. }
  348. // Only add the character to the output if it exists in the Basic Multilingual Plane (ie, fits in a single
  349. // word).
  350. if (ucs4_char <= 0xffff)
  351. output.push_back((word) ucs4_char);
  352. }
  353. return true;
  354. }
  355. // Converts an array of words in UCS-2 encoding into a character array in UTF-8 encoding.
  356. static bool UCS2toUTF8(const WString& input, String& output)
  357. {
  358. unsigned char *oc;
  359. size_t n;
  360. output.reserve(input.size());
  361. const word* w = input.data();
  362. const word* wlim = w + input.size();
  363. //Log::Message(LC_CORE, Log::LT_ALWAYS, "UCS2TOUTF8 size: %d", input_size);
  364. for (; w < wlim; w++)
  365. {
  366. if (__wchar_forbidden(*w) != 0)
  367. return false;
  368. if (*w == _BOM)
  369. continue;
  370. //if (*w < 0)
  371. // return false;
  372. if (*w <= 0x007f)
  373. n = 1;
  374. else if (*w <= 0x07ff)
  375. n = 2;
  376. else //if (*w <= 0x0000ffff)
  377. n = 3;
  378. /*else if (*w <= 0x001fffff)
  379. n = 4;
  380. else if (*w <= 0x03ffffff)
  381. n = 5;
  382. else // if (*w <= 0x7fffffff)
  383. n = 6;*/
  384. // Convert to little endian.
  385. word ch = (*w >> 8) & 0x00FF;
  386. ch |= (*w << 8) & 0xFF00;
  387. // word ch = EMPConvertEndian(*w, RMLUI_ENDIAN_BIG);
  388. oc = (unsigned char *)&ch;
  389. switch (n)
  390. {
  391. case 1:
  392. output += oc[1];
  393. break;
  394. case 2:
  395. output += (_SEQ2 | (oc[1] >> 6) | ((oc[0] & 0x07) << 2));
  396. output += (_NXT | (oc[1] & 0x3f));
  397. break;
  398. case 3:
  399. output += (_SEQ3 | ((oc[0] & 0xf0) >> 4));
  400. output += (_NXT | (oc[1] >> 6) | ((oc[0] & 0x0f) << 2));
  401. output += (_NXT | (oc[1] & 0x3f));
  402. break;
  403. case 4:
  404. break;
  405. case 5:
  406. break;
  407. case 6:
  408. break;
  409. }
  410. //Log::Message(LC_CORE, Log::LT_ALWAYS, "Converting...%c(%d) %d -> %d", *w, *w, w - input, output.size());
  411. }
  412. return true;
  413. }
  414. }
  415. }