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