ccUTF8.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /****************************************************************************
  2. Copyright (c) 2014 cocos2d-x.org
  3. Copyright (c) 2014-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "base/ccUTF8.h"
  22. #include "platform/CCCommon.h"
  23. #include "base/CCConsole.h"
  24. #include "ConvertUTF.h"
  25. NS_CC_BEGIN
  26. namespace StringUtils {
  27. std::string format(const char* format, ...)
  28. {
  29. #define CC_MAX_STRING_LENGTH (1024*100)
  30. std::string ret;
  31. va_list ap;
  32. va_start(ap, format);
  33. char* buf = (char*)malloc(CC_MAX_STRING_LENGTH);
  34. if (buf != nullptr)
  35. {
  36. vsnprintf(buf, CC_MAX_STRING_LENGTH, format, ap);
  37. ret = buf;
  38. free(buf);
  39. }
  40. va_end(ap);
  41. return ret;
  42. }
  43. /*
  44. * @str: the string to search through.
  45. * @c: the character to not look for.
  46. *
  47. * Return value: the index of the last character that is not c.
  48. * */
  49. unsigned int getIndexOfLastNotChar16(const std::vector<char16_t>& str, char16_t c)
  50. {
  51. int len = static_cast<int>(str.size());
  52. int i = len - 1;
  53. for (; i >= 0; --i)
  54. if (str[i] != c) return i;
  55. return i;
  56. }
  57. /*
  58. * @str: the string to trim
  59. * @index: the index to start trimming from.
  60. *
  61. * Trims str st str=[0, index) after the operation.
  62. *
  63. * Return value: the trimmed string.
  64. * */
  65. static void trimUTF16VectorFromIndex(std::vector<char16_t>& str, int index)
  66. {
  67. int size = static_cast<int>(str.size());
  68. if (index >= size || index < 0)
  69. return;
  70. str.erase(str.begin() + index, str.begin() + size);
  71. }
  72. /*
  73. * @str: the string to trim
  74. * @index: the index to start trimming from.
  75. *
  76. * Trims str st str=[0, index) after the operation.
  77. *
  78. * Return value: the trimmed string.
  79. * */
  80. static void trimUTF32VectorFromIndex(std::vector<char32_t>& str, int index)
  81. {
  82. int size = static_cast<int>(str.size());
  83. if (index >= size || index < 0)
  84. return;
  85. str.erase(str.begin() + index, str.begin() + size);
  86. }
  87. /*
  88. * @ch is the unicode character whitespace?
  89. *
  90. * Reference: http://en.wikipedia.org/wiki/Whitespace_character#Unicode
  91. *
  92. * Return value: weather the character is a whitespace character.
  93. * */
  94. bool isUnicodeSpace(char32_t ch)
  95. {
  96. return (ch >= 0x0009 && ch <= 0x000D) || ch == 0x0020 || ch == 0x0085 || ch == 0x00A0 || ch == 0x1680
  97. || (ch >= 0x2000 && ch <= 0x200A) || ch == 0x2028 || ch == 0x2029 || ch == 0x202F
  98. || ch == 0x205F || ch == 0x3000;
  99. }
  100. bool isCJKUnicode(char32_t ch)
  101. {
  102. return (ch >= 0x4E00 && ch <= 0x9FBF) // CJK Unified Ideographs
  103. || (ch >= 0x2E80 && ch <= 0x2FDF) // CJK Radicals Supplement & Kangxi Radicals
  104. || (ch >= 0x2FF0 && ch <= 0x30FF) // Ideographic Description Characters, CJK Symbols and Punctuation & Japanese
  105. || (ch >= 0x3100 && ch <= 0x31BF) // Korean
  106. || (ch >= 0xAC00 && ch <= 0xD7AF) // Hangul Syllables
  107. || (ch >= 0xF900 && ch <= 0xFAFF) // CJK Compatibility Ideographs
  108. || (ch >= 0xFE30 && ch <= 0xFE4F) // CJK Compatibility Forms
  109. || (ch >= 0x31C0 && ch <= 0x4DFF) // Other extensions
  110. || (ch >= 0x1f004 && ch <= 0x1f682);// Emoji
  111. }
  112. void trimUTF16Vector(std::vector<char16_t>& str)
  113. {
  114. int len = static_cast<int>(str.size());
  115. if ( len <= 0 )
  116. return;
  117. int last_index = len - 1;
  118. // Only start trimming if the last character is whitespace..
  119. if (isUnicodeSpace(str[last_index]))
  120. {
  121. for (int i = last_index - 1; i >= 0; --i)
  122. {
  123. if (isUnicodeSpace(str[i]))
  124. last_index = i;
  125. else
  126. break;
  127. }
  128. trimUTF16VectorFromIndex(str, last_index);
  129. }
  130. }
  131. void trimUTF32Vector(std::vector<char32_t>& str)
  132. {
  133. int len = static_cast<int>(str.size());
  134. if ( len <= 0 )
  135. return;
  136. int last_index = len - 1;
  137. // Only start trimming if the last character is whitespace..
  138. if (isUnicodeSpace(str[last_index]))
  139. {
  140. for (int i = last_index - 1; i >= 0; --i)
  141. {
  142. if (isUnicodeSpace(str[i]))
  143. last_index = i;
  144. else
  145. break;
  146. }
  147. trimUTF32VectorFromIndex(str, last_index);
  148. }
  149. }
  150. template <typename T>
  151. struct ConvertTrait {
  152. typedef T ArgType;
  153. };
  154. template <>
  155. struct ConvertTrait<char> {
  156. typedef UTF8 ArgType;
  157. };
  158. template <>
  159. struct ConvertTrait<char16_t> {
  160. typedef UTF16 ArgType;
  161. };
  162. template <>
  163. struct ConvertTrait<char32_t> {
  164. typedef UTF32 ArgType;
  165. };
  166. template <typename From, typename To, typename FromTrait = ConvertTrait<From>, typename ToTrait = ConvertTrait<To>>
  167. bool utfConvert(
  168. const std::basic_string<From>& from, std::basic_string<To>& to,
  169. ConversionResult(*cvtfunc)(const typename FromTrait::ArgType**, const typename FromTrait::ArgType*,
  170. typename ToTrait::ArgType**, typename ToTrait::ArgType*,
  171. ConversionFlags)
  172. )
  173. {
  174. static_assert(sizeof(From) == sizeof(typename FromTrait::ArgType), "Error size mismatched");
  175. static_assert(sizeof(To) == sizeof(typename ToTrait::ArgType), "Error size mismatched");
  176. if (from.empty())
  177. {
  178. to.clear();
  179. return true;
  180. }
  181. // See: http://unicode.org/faq/utf_bom.html#gen6
  182. static const int most_bytes_per_character = 4;
  183. const size_t maxNumberOfChars = from.length(); // all UTFs at most one element represents one character.
  184. const size_t numberOfOut = maxNumberOfChars * most_bytes_per_character / sizeof(To);
  185. std::basic_string<To> working(numberOfOut, 0);
  186. auto inbeg = reinterpret_cast<const typename FromTrait::ArgType*>(&from[0]);
  187. auto inend = inbeg + from.length();
  188. auto outbeg = reinterpret_cast<typename ToTrait::ArgType*>(&working[0]);
  189. auto outend = outbeg + working.length();
  190. auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion);
  191. if (r != conversionOK)
  192. return false;
  193. working.resize(reinterpret_cast<To*>(outbeg) - &working[0]);
  194. to = std::move(working);
  195. return true;
  196. };
  197. bool UTF8ToUTF16(const std::string& utf8, std::u16string& outUtf16)
  198. {
  199. return utfConvert(utf8, outUtf16, ConvertUTF8toUTF16);
  200. }
  201. bool UTF8ToUTF32(const std::string& utf8, std::u32string& outUtf32)
  202. {
  203. return utfConvert(utf8, outUtf32, ConvertUTF8toUTF32);
  204. }
  205. bool UTF16ToUTF8(const std::u16string& utf16, std::string& outUtf8)
  206. {
  207. return utfConvert(utf16, outUtf8, ConvertUTF16toUTF8);
  208. }
  209. bool UTF16ToUTF32(const std::u16string& utf16, std::u32string& outUtf32)
  210. {
  211. return utfConvert(utf16, outUtf32, ConvertUTF16toUTF32);
  212. }
  213. bool UTF32ToUTF8(const std::u32string& utf32, std::string& outUtf8)
  214. {
  215. return utfConvert(utf32, outUtf8, ConvertUTF32toUTF8);
  216. }
  217. bool UTF32ToUTF16(const std::u32string& utf32, std::u16string& outUtf16)
  218. {
  219. return utfConvert(utf32, outUtf16, ConvertUTF32toUTF16);
  220. }
  221. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  222. std::string getStringUTFCharsJNI(JNIEnv* env, jstring srcjStr, bool* ret)
  223. {
  224. std::string utf8Str;
  225. if(srcjStr != nullptr)
  226. {
  227. const unsigned short * unicodeChar = ( const unsigned short *)env->GetStringChars(srcjStr, nullptr);
  228. size_t unicodeCharLength = env->GetStringLength(srcjStr);
  229. const std::u16string unicodeStr((const char16_t *)unicodeChar, unicodeCharLength);
  230. bool flag = UTF16ToUTF8(unicodeStr, utf8Str);
  231. if (ret)
  232. {
  233. *ret = flag;
  234. }
  235. if (!flag)
  236. {
  237. utf8Str = "";
  238. }
  239. env->ReleaseStringChars(srcjStr, unicodeChar);
  240. }
  241. else
  242. {
  243. if (ret)
  244. {
  245. *ret = false;
  246. }
  247. utf8Str = "";
  248. }
  249. return utf8Str;
  250. }
  251. jstring newStringUTFJNI(JNIEnv* env, const std::string& utf8Str, bool* ret)
  252. {
  253. std::u16string utf16Str;
  254. bool flag = cocos2d::StringUtils::UTF8ToUTF16(utf8Str, utf16Str);
  255. if (ret)
  256. {
  257. *ret = flag;
  258. }
  259. if(!flag)
  260. {
  261. utf16Str.clear();
  262. }
  263. jstring stringText = env->NewString((const jchar*)utf16Str.data(), utf16Str.length());
  264. return stringText;
  265. }
  266. #endif
  267. std::vector<char16_t> getChar16VectorFromUTF16String(const std::u16string& utf16)
  268. {
  269. return std::vector<char16_t>(utf16.begin(), utf16.end());
  270. }
  271. long getCharacterCountInUTF8String(const std::string& utf8)
  272. {
  273. return getUTF8StringLength((const UTF8*)utf8.c_str());
  274. }
  275. StringUTF8::StringUTF8()
  276. {
  277. }
  278. StringUTF8::StringUTF8(const std::string& newStr)
  279. {
  280. replace(newStr);
  281. }
  282. StringUTF8::~StringUTF8()
  283. {
  284. }
  285. std::size_t StringUTF8::length() const
  286. {
  287. return _str.size();
  288. }
  289. void StringUTF8::replace(const std::string& newStr)
  290. {
  291. _str.clear();
  292. if (!newStr.empty())
  293. {
  294. UTF8* sequenceUtf8 = (UTF8*)newStr.c_str();
  295. int lengthString = getUTF8StringLength(sequenceUtf8);
  296. if (lengthString == 0)
  297. {
  298. CCLOG("Bad utf-8 set string: %s", newStr.c_str());
  299. return;
  300. }
  301. while (*sequenceUtf8)
  302. {
  303. std::size_t lengthChar = getNumBytesForUTF8(*sequenceUtf8);
  304. CharUTF8 charUTF8;
  305. charUTF8._char.append((char*)sequenceUtf8, lengthChar);
  306. sequenceUtf8 += lengthChar;
  307. _str.push_back(charUTF8);
  308. }
  309. }
  310. }
  311. std::string StringUTF8::getAsCharSequence() const
  312. {
  313. std::string charSequence;
  314. for (auto& charUtf8 : _str)
  315. {
  316. charSequence.append(charUtf8._char);
  317. }
  318. return charSequence;
  319. }
  320. bool StringUTF8::deleteChar(std::size_t pos)
  321. {
  322. if (pos < _str.size())
  323. {
  324. _str.erase(_str.begin() + pos);
  325. return true;
  326. }
  327. else
  328. {
  329. return false;
  330. }
  331. }
  332. bool StringUTF8::insert(std::size_t pos, const std::string& insertStr)
  333. {
  334. StringUTF8 utf8(insertStr);
  335. return insert(pos, utf8);
  336. }
  337. bool StringUTF8::insert(std::size_t pos, const StringUTF8& insertStr)
  338. {
  339. if (pos <= _str.size())
  340. {
  341. _str.insert(_str.begin() + pos, insertStr._str.begin(), insertStr._str.end());
  342. return true;
  343. }
  344. else
  345. {
  346. return false;
  347. }
  348. }
  349. } //namespace StringUtils {
  350. namespace {
  351. inline int wcslen_internal(const unsigned short* str)
  352. {
  353. if (str == nullptr)
  354. return -1;
  355. int i=0;
  356. while(*str++) i++;
  357. return i;
  358. }
  359. }
  360. int cc_wcslen(const unsigned short* str)
  361. {
  362. return wcslen_internal(str);
  363. }
  364. void cc_utf8_trim_ws(std::vector<unsigned short>* str)
  365. {
  366. if (str == nullptr)
  367. return;
  368. // unsigned short and char16_t are both 2 bytes
  369. std::vector<char16_t>* ret = reinterpret_cast<std::vector<char16_t>*>(str);
  370. StringUtils::trimUTF16Vector(*ret);
  371. }
  372. bool isspace_unicode(unsigned short ch)
  373. {
  374. return StringUtils::isUnicodeSpace(static_cast<char32_t>(ch));
  375. }
  376. bool iscjk_unicode(unsigned short ch)
  377. {
  378. return StringUtils::isCJKUnicode(static_cast<char32_t>(ch));
  379. }
  380. long cc_utf8_strlen (const char * p, int /*max*/)
  381. {
  382. if (p == nullptr)
  383. return -1;
  384. return StringUtils::getCharacterCountInUTF8String(p);
  385. }
  386. unsigned int cc_utf8_find_last_not_char(const std::vector<unsigned short>& str, unsigned short c)
  387. {
  388. std::vector<char16_t> char16Vector;
  389. for (const auto& e : str)
  390. {
  391. char16Vector.push_back(e);
  392. }
  393. return StringUtils::getIndexOfLastNotChar16(char16Vector, c);
  394. }
  395. std::vector<unsigned short> cc_utf16_vec_from_utf16_str(const unsigned short* str)
  396. {
  397. std::vector<unsigned short> str_new;
  398. if (str == nullptr)
  399. return str_new;
  400. int len = wcslen_internal(str);
  401. for (int i = 0; i < len; ++i)
  402. {
  403. str_new.push_back(str[i]);
  404. }
  405. return str_new;
  406. }
  407. unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1*/, int* rUtf16Size/* = nullptr*/)
  408. {
  409. if (str_old == nullptr)
  410. return nullptr;
  411. unsigned short* ret = nullptr;
  412. std::u16string outUtf16;
  413. std::string inUtf8 = length == -1 ? std::string(str_old) : std::string(str_old, length);
  414. bool succeed = StringUtils::UTF8ToUTF16(inUtf8, outUtf16);
  415. if (succeed)
  416. {
  417. ret = new (std::nothrow) unsigned short[outUtf16.length() + 1];
  418. ret[outUtf16.length()] = 0;
  419. memcpy(ret, outUtf16.data(), outUtf16.length() * sizeof(unsigned short));
  420. if (rUtf16Size)
  421. {
  422. *rUtf16Size = static_cast<int>(outUtf16.length());
  423. }
  424. }
  425. return ret;
  426. }
  427. char * cc_utf16_to_utf8 (const unsigned short *str,
  428. int len,
  429. long * /*items_read*/,
  430. long * /*items_written*/)
  431. {
  432. if (str == nullptr)
  433. return nullptr;
  434. std::u16string utf16;
  435. int utf16Len = len < 0 ? wcslen_internal(str) : len;
  436. for (int i = 0; i < utf16Len; ++i)
  437. {
  438. utf16.push_back(str[i]);
  439. }
  440. char* ret = nullptr;
  441. std::string outUtf8;
  442. bool succeed = StringUtils::UTF16ToUTF8(utf16, outUtf8);
  443. if (succeed)
  444. {
  445. ret = new (std::nothrow) char[outUtf8.length() + 1];
  446. ret[outUtf8.length()] = '\0';
  447. memcpy(ret, outUtf8.data(), outUtf8.length());
  448. }
  449. return ret;
  450. }
  451. NS_CC_END