utf8.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. Basic UTF-8 manipulation routines
  3. by Jeff Bezanson
  4. placed in the public domain Fall 2005
  5. This code is designed to provide the utilities you need to manipulate
  6. UTF-8 as an internal string encoding. These functions do not perform the
  7. error checking normally needed when handling UTF-8 data, so if you happen
  8. to be from the Unicode Consortium you will want to flay me alive.
  9. I do this because error checking can be performed at the boundaries (I/O),
  10. with these routines reserved for higher performance on data known to be
  11. valid.
  12. */
  13. #ifdef _WIN32
  14. #include <windows.h>
  15. #undef min
  16. #undef max
  17. #endif
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <stdarg.h>
  22. #include <algorithm>
  23. #include <string>
  24. #include "common/common_types.h"
  25. #include "common/utf8.h"
  26. // is start of UTF sequence
  27. inline bool isutf(char c) {
  28. return (c & 0xC0) != 0x80;
  29. }
  30. static const u32 offsetsFromUTF8[6] = {
  31. 0x00000000UL, 0x00003080UL, 0x000E2080UL,
  32. 0x03C82080UL, 0xFA082080UL, 0x82082080UL
  33. };
  34. static const u8 trailingBytesForUTF8[256] = {
  35. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  36. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  37. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  38. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  39. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  40. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  41. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  42. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,
  43. };
  44. /* returns length of next utf-8 sequence */
  45. int u8_seqlen(const char *s)
  46. {
  47. return trailingBytesForUTF8[(unsigned int)(unsigned char)s[0]] + 1;
  48. }
  49. /* conversions without error checking
  50. only works for valid UTF-8, i.e. no 5- or 6-byte sequences
  51. srcsz = source size in bytes, or -1 if 0-terminated
  52. sz = dest size in # of wide characters
  53. returns # characters converted
  54. dest will always be L'\0'-terminated, even if there isn't enough room
  55. for all the characters.
  56. if sz = srcsz+1 (i.e. 4*srcsz+4 bytes), there will always be enough space.
  57. */
  58. int u8_toucs(u32 *dest, int sz, const char *src, int srcsz)
  59. {
  60. u32 ch;
  61. const char *src_end = src + srcsz;
  62. int nb;
  63. int i=0;
  64. while (i < sz-1) {
  65. nb = trailingBytesForUTF8[(unsigned char)*src];
  66. if (srcsz == -1) {
  67. if (*src == 0)
  68. goto done_toucs;
  69. }
  70. else {
  71. if (src + nb >= src_end)
  72. goto done_toucs;
  73. }
  74. ch = 0;
  75. switch (nb) {
  76. /* these fall through deliberately */
  77. case 3: ch += (unsigned char)*src++; ch <<= 6;
  78. case 2: ch += (unsigned char)*src++; ch <<= 6;
  79. case 1: ch += (unsigned char)*src++; ch <<= 6;
  80. case 0: ch += (unsigned char)*src++;
  81. }
  82. ch -= offsetsFromUTF8[nb];
  83. dest[i++] = ch;
  84. }
  85. done_toucs:
  86. dest[i] = 0;
  87. return i;
  88. }
  89. /* srcsz = number of source characters, or -1 if 0-terminated
  90. sz = size of dest buffer in bytes
  91. returns # characters converted
  92. dest will only be '\0'-terminated if there is enough space. this is
  93. for consistency; imagine there are 2 bytes of space left, but the next
  94. character requires 3 bytes. in this case we could NUL-terminate, but in
  95. general we can't when there's insufficient space. therefore this function
  96. only NUL-terminates if all the characters fit, and there's space for
  97. the NUL as well.
  98. the destination string will never be bigger than the source string.
  99. */
  100. int u8_toutf8(char *dest, int sz, u32 *src, int srcsz)
  101. {
  102. u32 ch;
  103. int i = 0;
  104. char *dest_end = dest + sz;
  105. while (srcsz<0 ? src[i]!=0 : i < srcsz) {
  106. ch = src[i];
  107. if (ch < 0x80) {
  108. if (dest >= dest_end)
  109. return i;
  110. *dest++ = (char)ch;
  111. }
  112. else if (ch < 0x800) {
  113. if (dest >= dest_end-1)
  114. return i;
  115. *dest++ = (ch>>6) | 0xC0;
  116. *dest++ = (ch & 0x3F) | 0x80;
  117. }
  118. else if (ch < 0x10000) {
  119. if (dest >= dest_end-2)
  120. return i;
  121. *dest++ = (ch>>12) | 0xE0;
  122. *dest++ = ((ch>>6) & 0x3F) | 0x80;
  123. *dest++ = (ch & 0x3F) | 0x80;
  124. }
  125. else if (ch < 0x110000) {
  126. if (dest >= dest_end-3)
  127. return i;
  128. *dest++ = (ch>>18) | 0xF0;
  129. *dest++ = ((ch>>12) & 0x3F) | 0x80;
  130. *dest++ = ((ch>>6) & 0x3F) | 0x80;
  131. *dest++ = (ch & 0x3F) | 0x80;
  132. }
  133. i++;
  134. }
  135. if (dest < dest_end)
  136. *dest = '\0';
  137. return i;
  138. }
  139. int u8_wc_toutf8(char *dest, u32 ch)
  140. {
  141. if (ch < 0x80) {
  142. dest[0] = (char)ch;
  143. return 1;
  144. }
  145. if (ch < 0x800) {
  146. dest[0] = (ch>>6) | 0xC0;
  147. dest[1] = (ch & 0x3F) | 0x80;
  148. return 2;
  149. }
  150. if (ch < 0x10000) {
  151. dest[0] = (ch>>12) | 0xE0;
  152. dest[1] = ((ch>>6) & 0x3F) | 0x80;
  153. dest[2] = (ch & 0x3F) | 0x80;
  154. return 3;
  155. }
  156. if (ch < 0x110000) {
  157. dest[0] = (ch>>18) | 0xF0;
  158. dest[1] = ((ch>>12) & 0x3F) | 0x80;
  159. dest[2] = ((ch>>6) & 0x3F) | 0x80;
  160. dest[3] = (ch & 0x3F) | 0x80;
  161. return 4;
  162. }
  163. return 0;
  164. }
  165. /* charnum => byte offset */
  166. int u8_offset(const char *str, int charnum)
  167. {
  168. int offs=0;
  169. while (charnum > 0 && str[offs]) {
  170. (void)(isutf(str[++offs]) || isutf(str[++offs]) ||
  171. isutf(str[++offs]) || ++offs);
  172. charnum--;
  173. }
  174. return offs;
  175. }
  176. /* byte offset => charnum */
  177. int u8_charnum(const char *s, int offset)
  178. {
  179. int charnum = 0, offs=0;
  180. while (offs < offset && s[offs]) {
  181. (void)(isutf(s[++offs]) || isutf(s[++offs]) ||
  182. isutf(s[++offs]) || ++offs);
  183. charnum++;
  184. }
  185. return charnum;
  186. }
  187. /* number of characters */
  188. int u8_strlen(const char *s)
  189. {
  190. int count = 0;
  191. int i = 0;
  192. while (u8_nextchar(s, &i) != 0)
  193. count++;
  194. return count;
  195. }
  196. /* reads the next utf-8 sequence out of a string, updating an index */
  197. u32 u8_nextchar(const char *s, int *i)
  198. {
  199. u32 ch = 0;
  200. int sz = 0;
  201. do {
  202. ch <<= 6;
  203. ch += (unsigned char)s[(*i)++];
  204. sz++;
  205. } while (s[*i] && !isutf(s[*i]));
  206. ch -= offsetsFromUTF8[sz-1];
  207. return ch;
  208. }
  209. void u8_inc(const char *s, int *i)
  210. {
  211. (void)(isutf(s[++(*i)]) || isutf(s[++(*i)]) ||
  212. isutf(s[++(*i)]) || ++(*i));
  213. }
  214. void u8_dec(const char *s, int *i)
  215. {
  216. (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) ||
  217. isutf(s[--(*i)]) || --(*i));
  218. }
  219. int octal_digit(char c)
  220. {
  221. return (c >= '0' && c <= '7');
  222. }
  223. int hex_digit(char c)
  224. {
  225. return ((c >= '0' && c <= '9') ||
  226. (c >= 'A' && c <= 'F') ||
  227. (c >= 'a' && c <= 'f'));
  228. }
  229. /* assumes that src points to the character after a backslash
  230. returns number of input characters processed */
  231. int u8_read_escape_sequence(const char *str, u32 *dest)
  232. {
  233. u32 ch;
  234. char digs[9]="\0\0\0\0\0\0\0\0";
  235. int dno=0, i=1;
  236. ch = (u32)str[0]; /* take literal character */
  237. if (str[0] == 'n')
  238. ch = L'\n';
  239. else if (str[0] == 't')
  240. ch = L'\t';
  241. else if (str[0] == 'r')
  242. ch = L'\r';
  243. else if (str[0] == 'b')
  244. ch = L'\b';
  245. else if (str[0] == 'f')
  246. ch = L'\f';
  247. else if (str[0] == 'v')
  248. ch = L'\v';
  249. else if (str[0] == 'a')
  250. ch = L'\a';
  251. else if (octal_digit(str[0])) {
  252. i = 0;
  253. do {
  254. digs[dno++] = str[i++];
  255. } while (octal_digit(str[i]) && dno < 3);
  256. ch = strtol(digs, NULL, 8);
  257. }
  258. else if (str[0] == 'x') {
  259. while (hex_digit(str[i]) && dno < 2) {
  260. digs[dno++] = str[i++];
  261. }
  262. if (dno > 0)
  263. ch = strtol(digs, NULL, 16);
  264. }
  265. else if (str[0] == 'u') {
  266. while (hex_digit(str[i]) && dno < 4) {
  267. digs[dno++] = str[i++];
  268. }
  269. if (dno > 0)
  270. ch = strtol(digs, NULL, 16);
  271. }
  272. else if (str[0] == 'U') {
  273. while (hex_digit(str[i]) && dno < 8) {
  274. digs[dno++] = str[i++];
  275. }
  276. if (dno > 0)
  277. ch = strtol(digs, NULL, 16);
  278. }
  279. *dest = ch;
  280. return i;
  281. }
  282. /* convert a string with literal \uxxxx or \Uxxxxxxxx characters to UTF-8
  283. example: u8_unescape(mybuf, 256, "hello\\u220e")
  284. note the double backslash is needed if called on a C string literal */
  285. int u8_unescape(char *buf, int sz, char *src)
  286. {
  287. int c=0, amt;
  288. u32 ch;
  289. char temp[4];
  290. while (*src && c < sz) {
  291. if (*src == '\\') {
  292. src++;
  293. amt = u8_read_escape_sequence(src, &ch);
  294. }
  295. else {
  296. ch = (u32)*src;
  297. amt = 1;
  298. }
  299. src += amt;
  300. amt = u8_wc_toutf8(temp, ch);
  301. if (amt > sz-c)
  302. break;
  303. memcpy(&buf[c], temp, amt);
  304. c += amt;
  305. }
  306. if (c < sz)
  307. buf[c] = '\0';
  308. return c;
  309. }
  310. const char *u8_strchr(const char *s, u32 ch, int *charn)
  311. {
  312. int i = 0, lasti=0;
  313. u32 c;
  314. *charn = 0;
  315. while (s[i]) {
  316. c = u8_nextchar(s, &i);
  317. if (c == ch) {
  318. return &s[lasti];
  319. }
  320. lasti = i;
  321. (*charn)++;
  322. }
  323. return NULL;
  324. }
  325. const char *u8_memchr(const char *s, u32 ch, size_t sz, int *charn)
  326. {
  327. u32 i = 0, lasti=0;
  328. u32 c;
  329. int csz;
  330. *charn = 0;
  331. while (i < sz) {
  332. c = csz = 0;
  333. do {
  334. c <<= 6;
  335. c += (unsigned char)s[i++];
  336. csz++;
  337. } while (i < sz && !isutf(s[i]));
  338. c -= offsetsFromUTF8[csz-1];
  339. if (c == ch) {
  340. return &s[lasti];
  341. }
  342. lasti = i;
  343. (*charn)++;
  344. }
  345. return NULL;
  346. }
  347. int u8_is_locale_utf8(const char *locale)
  348. {
  349. /* this code based on libutf8 */
  350. const char* cp = locale;
  351. for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++) {
  352. if (*cp == '.') {
  353. const char* encoding = ++cp;
  354. for (; *cp != '\0' && *cp != '@' && *cp != '+' && *cp != ','; cp++)
  355. ;
  356. if ((cp-encoding == 5 && !strncmp(encoding, "UTF-8", 5))
  357. || (cp-encoding == 4 && !strncmp(encoding, "utf8", 4)))
  358. return 1; /* it's UTF-8 */
  359. break;
  360. }
  361. }
  362. return 0;
  363. }
  364. int UTF8StringNonASCIICount(const char *utf8string) {
  365. UTF8 utf(utf8string);
  366. int count = 0;
  367. while (!utf.end()) {
  368. int c = utf.next();
  369. if (c > 127)
  370. ++count;
  371. }
  372. return count;
  373. }
  374. bool UTF8StringHasNonASCII(const char *utf8string) {
  375. return UTF8StringNonASCIICount(utf8string) > 0;
  376. }
  377. #ifdef _WIN32
  378. std::string ConvertWStringToUTF8(const wchar_t *wstr) {
  379. int len = (int)wcslen(wstr);
  380. int size = (int)WideCharToMultiByte(CP_UTF8, 0, wstr, len, 0, 0, NULL, NULL);
  381. std::string s;
  382. s.resize(size);
  383. if (size > 0) {
  384. WideCharToMultiByte(CP_UTF8, 0, wstr, len, &s[0], size, NULL, NULL);
  385. }
  386. return s;
  387. }
  388. std::string ConvertWStringToUTF8(const std::wstring &wstr) {
  389. int len = (int)wstr.size();
  390. int size = (int)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, 0, 0, NULL, NULL);
  391. std::string s;
  392. s.resize(size);
  393. if (size > 0) {
  394. WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), len, &s[0], size, NULL, NULL);
  395. }
  396. return s;
  397. }
  398. void ConvertUTF8ToWString(wchar_t *dest, size_t destSize, const std::string &source) {
  399. int len = (int)source.size();
  400. int size = (int)MultiByteToWideChar(CP_UTF8, 0, source.c_str(), len, NULL, 0);
  401. MultiByteToWideChar(CP_UTF8, 0, source.c_str(), len, dest, std::min((int)destSize, size));
  402. }
  403. std::wstring ConvertUTF8ToWString(const std::string &source) {
  404. int len = (int)source.size();
  405. int size = (int)MultiByteToWideChar(CP_UTF8, 0, source.c_str(), len, NULL, 0);
  406. std::wstring str;
  407. str.resize(size);
  408. if (size > 0) {
  409. MultiByteToWideChar(CP_UTF8, 0, source.c_str(), len, &str[0], size);
  410. }
  411. return str;
  412. }
  413. #endif