replace own unicode functions with versions from glib which support more unicode...
[blender.git] / source / blender / blenlib / intern / string_utf8.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2011 Blender Foundation.
21  * All rights reserved.
22  *
23  * Contributor(s): Campbell Barton.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  */
28
29  /** \file blender/blenlib/intern/string_utf8.c
30  *  \ingroup bli
31  */
32
33 #include <string.h>
34 #include <wchar.h>
35 #include <wctype.h>
36
37 #include "BLI_string_utf8.h"
38
39 /* from libswish3, originally called u8_isvalid(),
40  * modified to return the index of the bad character (byte index not utf).
41  * http://svn.swish-e.org/libswish3/trunk/src/libswish3/utf8.c r3044 - campbell */
42
43 /* based on the valid_utf8 routine from the PCRE library by Philip Hazel
44
45    length is in bytes, since without knowing whether the string is valid
46    it's hard to know how many characters there are! */
47
48 static const char trailingBytesForUTF8[256] = {
49         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,
50         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,
51         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,
52         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,
53         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,
54         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,
55         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,
56         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
57 };
58
59 int BLI_utf8_invalid_byte(const char *str, int length)
60 {
61         const unsigned char *p, *pend = (unsigned char*)str + length;
62         unsigned char c;
63         int ab;
64
65         for (p = (unsigned char*)str; p < pend; p++) {
66                 c = *p;
67                 if (c < 128)
68                         continue;
69                 if ((c & 0xc0) != 0xc0)
70                         goto utf8_error;
71                 ab = trailingBytesForUTF8[c];
72                 if (length < ab)
73                         goto utf8_error;
74                 length -= ab;
75
76                 p++;
77                 /* Check top bits in the second byte */
78                 if ((*p & 0xc0) != 0x80)
79                         goto utf8_error;
80
81                 /* Check for overlong sequences for each different length */
82                 switch (ab) {
83                         /* Check for xx00 000x */
84                 case 1:
85                         if ((c & 0x3e) == 0) goto utf8_error;
86                         continue;   /* We know there aren't any more bytes to check */
87
88                         /* Check for 1110 0000, xx0x xxxx */
89                 case 2:
90                         if (c == 0xe0 && (*p & 0x20) == 0) goto utf8_error;
91                         break;
92
93                         /* Check for 1111 0000, xx00 xxxx */
94                 case 3:
95                         if (c == 0xf0 && (*p & 0x30) == 0) goto utf8_error;
96                         break;
97
98                         /* Check for 1111 1000, xx00 0xxx */
99                 case 4:
100                         if (c == 0xf8 && (*p & 0x38) == 0) goto utf8_error;
101                         break;
102
103                         /* Check for leading 0xfe or 0xff,
104                            and then for 1111 1100, xx00 00xx */
105                 case 5:
106                         if (c == 0xfe || c == 0xff ||
107                                 (c == 0xfc && (*p & 0x3c) == 0)) goto utf8_error;
108                         break;
109                 }
110
111                 /* Check for valid bytes after the 2nd, if any; all must start 10 */
112                 while (--ab > 0) {
113                         if ((*(p+1) & 0xc0) != 0x80) goto utf8_error;
114                         p++; /* do this after so we get usable offset - campbell */
115                 }
116         }
117
118         return -1;
119
120 utf8_error:
121
122         return (int)((char *)p - (char *)str) - 1;
123 }
124
125 int BLI_utf8_invalid_strip(char *str, int length)
126 {
127         int bad_char, tot= 0;
128
129         while((bad_char= BLI_utf8_invalid_byte(str, length)) != -1) {
130                 str += bad_char;
131                 length -= bad_char;
132
133                 if(length == 0) {
134                         /* last character bad, strip it */
135                         *str= '\0';
136                         tot++;
137                         break;
138                 }
139                 else {
140                         /* strip, keep looking */
141                         memmove(str, str + 1, length);
142                         tot++;
143                 }
144         }
145
146         return tot;
147 }
148
149
150 /* compatible with BLI_strncpy, but esnure no partial utf8 chars */
151
152 /* array copied from glib's gutf8.c,
153  * note: this looks to be at odd's with 'trailingBytesForUTF8',
154  * need to find out what gives here! - campbell */
155 static const size_t utf8_skip_data[256] = {
156     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,
157     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,
158     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,
159     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,
160     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,
161     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,
162     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
163     3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
164 };
165
166 char *BLI_strncpy_utf8(char *dst, const char *src, size_t maxncpy)
167 {
168         char *dst_r= dst;
169         size_t utf8_size;
170
171         /* note: currently we dont attempt to deal with invalid utf8 chars */
172
173         while(*src != '\0' && (utf8_size= utf8_skip_data[*src]) < maxncpy) {
174                 maxncpy -= utf8_size;
175                 switch(utf8_size) {
176                         case 6: *dst ++ = *src ++;
177                         case 5: *dst ++ = *src ++;
178                         case 4: *dst ++ = *src ++;
179                         case 3: *dst ++ = *src ++;
180                         case 2: *dst ++ = *src ++;
181                         case 1: *dst ++ = *src ++;
182                 }
183         }
184         *dst= '\0';
185         return dst_r;
186 }
187
188
189 /* --------------------------------------------------------------------------*/
190 /* wchar_t / utf8 functions  */
191
192 size_t BLI_strncpy_wchar_as_utf8(char *dst, const wchar_t *src, const size_t maxcpy)
193 {
194         size_t len = 0;
195         while(*src && len < maxcpy) { /* XXX can still run over the buffer because utf8 size isnt known :| */
196                 len += BLI_str_utf8_from_unicode(*src++, dst+len);
197         }
198
199         dst[len]= '\0';
200
201         return len;
202 }
203
204 /* wchar len in utf8 */
205 size_t BLI_wstrlen_utf8(const wchar_t *src)
206 {
207         size_t len = 0;
208
209         while(*src) {
210                 len += BLI_str_utf8_from_unicode(*src++, NULL);
211         }
212
213         return len;
214 }
215
216 // utf8slen
217 size_t BLI_strlen_utf8(const char *strc)
218 {
219         int len=0;
220
221         while(*strc) {
222                 if ((*strc & 0xe0) == 0xc0) {
223                         if((strc[1] & 0x80) && (strc[1] & 0x40) == 0x00)
224                                 strc++;
225                 } else if ((*strc & 0xf0) == 0xe0) {
226                         if((strc[1] & strc[2] & 0x80) && ((strc[1] | strc[2]) & 0x40) == 0x00)
227                                 strc += 2;
228                 } else if ((*strc & 0xf8) == 0xf0) {
229                         if((strc[1] & strc[2] & strc[3] & 0x80) && ((strc[1] | strc[2] | strc[3]) & 0x40) == 0x00)
230                                 strc += 3;
231                 }
232
233                 strc++;
234                 len++;
235         }
236
237         return len;
238 }
239
240 size_t BLI_strncpy_wchar_from_utf8(wchar_t *dst_w, const char *src_c, const size_t maxcpy)
241 {
242         int len=0;
243
244         if(dst_w==NULL || src_c==NULL) return(0);
245
246         while(*src_c && len < maxcpy) {
247                 size_t step= 0;
248                 unsigned int unicode= BLI_str_utf8_as_unicode_and_size(src_c, &step);
249                 if (unicode != (unsigned int)-1) {
250                         *dst_w= (wchar_t)unicode;
251                         src_c += step;
252                 }
253                 else {
254                         *dst_w = '?';
255                         src_c= BLI_str_find_next_char_utf8(src_c, NULL);
256                 }
257                 dst_w++;
258                 len++;
259         }
260         return len;
261 }
262
263 /* end wchar_t / utf8 functions  */
264 /* --------------------------------------------------------------------------*/
265
266 /* copied from glib */
267
268 /* note, glib uses unsigned int for unicode, best we do the same,
269  * though we dont typedef it - campbell */
270
271 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
272         if (Char < 128) {                                                         \
273                 Len = 1;                                                              \
274                 Mask = 0x7f;                                                          \
275         }                                                                         \
276         else if ((Char & 0xe0) == 0xc0) {                                         \
277                 Len = 2;                                                              \
278                 Mask = 0x1f;                                                          \
279         }                                                                         \
280         else if ((Char & 0xf0) == 0xe0) {                                         \
281                 Len = 3;                                                              \
282                 Mask = 0x0f;                                                          \
283         }                                                                         \
284         else if ((Char & 0xf8) == 0xf0) {                                         \
285                 Len = 4;                                                              \
286                 Mask = 0x07;                                                          \
287         }                                                                         \
288         else if ((Char & 0xfc) == 0xf8) {                                         \
289                 Len = 5;                                                              \
290                 Mask = 0x03;                                                          \
291         }                                                                         \
292         else if ((Char & 0xfe) == 0xfc) {                                         \
293                 Len = 6;                                                              \
294                 Mask = 0x01;                                                          \
295         }                                                                         \
296         else {                                                                    \
297                 Len = -1;                                                             \
298         }
299
300
301 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
302         (Result) = (Chars)[0] & (Mask);                                           \
303         for ((Count) = 1; (Count) < (Len); ++(Count)) {                           \
304                 if (((Chars)[(Count)] & 0xc0) != 0x80) {                              \
305                         (Result) = -1;                                                    \
306                         break;                                                            \
307                 }                                                                     \
308                 (Result) <<= 6;                                                       \
309                 (Result) |= ((Chars)[(Count)] & 0x3f);                                \
310         }
311
312
313 /* was g_utf8_get_char */
314 /**
315  * BLI_str_utf8_as_unicode:
316  * @p: a pointer to Unicode character encoded as UTF-8
317  *
318  * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
319  * If @p does not point to a valid UTF-8 encoded character, results are
320  * undefined. If you are not sure that the bytes are complete
321  * valid Unicode characters, you should use g_utf8_get_char_validated()
322  * instead.
323  *
324  * Return value: the resulting character
325  **/
326 unsigned int BLI_str_utf8_as_unicode(const char *p)
327 {
328   int i, mask = 0, len;
329   unsigned int result;
330   unsigned char c = (unsigned char) *p;
331
332   UTF8_COMPUTE (c, mask, len);
333   if (len == -1)
334     return (unsigned int)-1;
335   UTF8_GET (result, p, i, mask, len);
336
337   return result;
338 }
339
340 /* varient that increments the length */
341 unsigned int BLI_str_utf8_as_unicode_and_size(const char *p, size_t *index)
342 {
343         int i, mask = 0, len;
344         unsigned int result;
345         unsigned char c = (unsigned char) *p;
346
347         UTF8_COMPUTE (c, mask, len);
348         if (len == -1)
349                 return (unsigned int)-1;
350         UTF8_GET (result, p, i, mask, len);
351         *index += len;
352         return result;
353 }
354
355 /* another varient that steps over the index */
356 unsigned int BLI_str_utf8_as_unicode_step(const char *p, size_t *index)
357 {
358         int i, mask = 0, len;
359         unsigned int result;
360         unsigned char c;
361
362         p += *index;
363         c= (unsigned char) *p;
364
365         UTF8_COMPUTE (c, mask, len);
366         if (len == -1) {
367                 /* when called with NULL end, result will never be NULL,
368                  * checks for a NULL character */
369                 char *p_next= BLI_str_find_next_char_utf8(p, NULL);
370                 /* will never return the same pointer unless '\0',
371                  * eternal loop is prevented */
372                 *index += (size_t)(p_next - p);
373                 return (unsigned int)-1;
374         }
375         UTF8_GET (result, p, i, mask, len);
376         *index += len;
377         return result;
378 }
379
380 /* was g_unichar_to_utf8 */
381 /**
382  * BLI_str_utf8_from_unicode:
383  * @c: a Unicode character code
384  * @outbuf: output buffer, must have at least 6 bytes of space.
385  *       If %NULL, the length will be computed and returned
386  *       and nothing will be written to @outbuf.
387  *
388  * Converts a single character to UTF-8.
389  *
390  * Return value: number of bytes written
391  **/
392 size_t BLI_str_utf8_from_unicode(unsigned int c, char *outbuf)
393 {
394         /* If this gets modified, also update the copy in g_string_insert_unichar() */
395         unsigned int len = 0;
396         int first;
397         int i;
398
399         if (c < 0x80) {
400                 first = 0;
401                 len = 1;
402         }
403         else if (c < 0x800) {
404                 first = 0xc0;
405                 len = 2;
406         }
407         else if (c < 0x10000) {
408                 first = 0xe0;
409                 len = 3;
410         }
411         else if (c < 0x200000) {
412                 first = 0xf0;
413                 len = 4;
414         }
415         else if (c < 0x4000000) {
416                 first = 0xf8;
417                 len = 5;
418         }
419         else {
420                 first = 0xfc;
421                 len = 6;
422         }
423
424         if (outbuf) {
425                 for (i = len - 1; i > 0; --i) {
426                         outbuf[i] = (c & 0x3f) | 0x80;
427                         c >>= 6;
428                 }
429                 outbuf[0] = c | first;
430         }
431
432         return len;
433 }
434
435 /* was g_utf8_find_prev_char */
436 /**
437  * BLI_str_find_prev_char_utf8:
438  * @str: pointer to the beginning of a UTF-8 encoded string
439  * @p: pointer to some position within @str
440  *
441  * Given a position @p with a UTF-8 encoded string @str, find the start
442  * of the previous UTF-8 character starting before @p. Returns %NULL if no
443  * UTF-8 characters are present in @str before @p.
444  *
445  * @p does not have to be at the beginning of a UTF-8 character. No check
446  * is made to see if the character found is actually valid other than
447  * it starts with an appropriate byte.
448  *
449  * Return value: a pointer to the found character or %NULL.
450  **/
451 char * BLI_str_find_prev_char_utf8(const char *str, const char *p)
452 {
453         for (--p; p >= str; --p) {
454                 if ((*p & 0xc0) != 0x80) {
455                         return (char *)p;
456                 }
457         }
458         return NULL;
459 }
460
461 /* was g_utf8_find_next_char */
462 /**
463  * BLI_str_find_next_char_utf8:
464  * @p: a pointer to a position within a UTF-8 encoded string
465  * @end: a pointer to the byte following the end of the string,
466  * or %NULL to indicate that the string is nul-terminated.
467  *
468  * Finds the start of the next UTF-8 character in the string after @p.
469  *
470  * @p does not have to be at the beginning of a UTF-8 character. No check
471  * is made to see if the character found is actually valid other than
472  * it starts with an appropriate byte.
473  *
474  * Return value: a pointer to the found character or %NULL
475  **/
476 char *BLI_str_find_next_char_utf8(const char *p, const char *end)
477 {
478         if (*p) {
479                 if (end) {
480                         for (++p; p < end && (*p & 0xc0) == 0x80; ++p) {
481                                 /* do nothing */
482                         }
483                 }
484                 else {
485                         for (++p; (*p & 0xc0) == 0x80; ++p) {
486                                 /* do nothing */
487                         }
488                 }
489         }
490         return (p == end) ? NULL : (char *)p;
491 }
492
493 /* was g_utf8_prev_char */
494 /**
495  * BLI_str_prev_char_utf8:
496  * @p: a pointer to a position within a UTF-8 encoded string
497  *
498  * Finds the previous UTF-8 character in the string before @p.
499  *
500  * @p does not have to be at the beginning of a UTF-8 character. No check
501  * is made to see if the character found is actually valid other than
502  * it starts with an appropriate byte. If @p might be the first
503  * character of the string, you must use g_utf8_find_prev_char() instead.
504  *
505  * Return value: a pointer to the found character.
506  **/
507 char *BLI_str_prev_char_utf8(const char *p)
508 {
509         while (1) {
510                 p--;
511                 if ((*p & 0xc0) != 0x80) {
512                         return (char *)p;
513                 }
514         }
515 }
516 /* end glib copy */