1 /* gutf8.c - Operations on UTF-8 strings.
2 *
3 * Copyright (C) 1999 Tom Tromey
4 * Copyright (C) 2000 Red Hat, Inc.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library 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 GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "config.h"
21
22 #include <stdlib.h>
23 #ifdef HAVE_CODESET
24 #include <langinfo.h>
25 #endif
26 #include <string.h>
27
28 #ifdef G_PLATFORM_WIN32
29 #include <stdio.h>
30 #define STRICT
31 #include <windows.h>
32 #undef STRICT
33 #endif
34
35 #include "gconvert.h"
36 #include "ghash.h"
37 #include "gstrfuncs.h"
38 #include "gtestutils.h"
39 #include "gtypes.h"
40 #include "gthread.h"
41 #include "glibintl.h"
42
43 #define UTF8_COMPUTE(Char, Mask, Len) \
44 if (Char < 128) \
45 { \
46 Len = 1; \
47 Mask = 0x7f; \
48 } \
49 else if ((Char & 0xe0) == 0xc0) \
50 { \
51 Len = 2; \
52 Mask = 0x1f; \
53 } \
54 else if ((Char & 0xf0) == 0xe0) \
55 { \
56 Len = 3; \
57 Mask = 0x0f; \
58 } \
59 else if ((Char & 0xf8) == 0xf0) \
60 { \
61 Len = 4; \
62 Mask = 0x07; \
63 } \
64 else if ((Char & 0xfc) == 0xf8) \
65 { \
66 Len = 5; \
67 Mask = 0x03; \
68 } \
69 else if ((Char & 0xfe) == 0xfc) \
70 { \
71 Len = 6; \
72 Mask = 0x01; \
73 } \
74 else \
75 Len = -1;
76
77 #define UTF8_LENGTH(Char) \
78 ((Char) < 0x80 ? 1 : \
79 ((Char) < 0x800 ? 2 : \
80 ((Char) < 0x10000 ? 3 : \
81 ((Char) < 0x200000 ? 4 : \
82 ((Char) < 0x4000000 ? 5 : 6)))))
83
84
85 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
86 (Result) = (Chars)[0] & (Mask); \
87 for ((Count) = 1; (Count) < (Len); ++(Count)) \
88 { \
89 if (((Chars)[(Count)] & 0xc0) != 0x80) \
90 { \
91 (Result) = -1; \
92 break; \
93 } \
94 (Result) <<= 6; \
95 (Result) |= ((Chars)[(Count)] & 0x3f); \
96 }
97
98 /*
99 * Check whether a Unicode (5.2) char is in a valid range.
100 *
101 * The first check comes from the Unicode guarantee to never encode
102 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
103 *
104 * The second check covers surrogate pairs (category Cs).
105 *
106 * @param Char the character
107 */
108 #define UNICODE_VALID(Char) \
109 ((Char) < 0x110000 && \
110 (((Char) & 0xFFFFF800) != 0xD800))
111
112
113 static const gchar utf8_skip_data[256] = {
114 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,
115 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,
116 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,
117 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,
118 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,
119 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,
120 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,
121 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
122 };
123
124 const gchar * const g_utf8_skip = utf8_skip_data;
125
126 /**
127 * g_utf8_find_prev_char:
128 * @str: pointer to the beginning of a UTF-8 encoded string
129 * @p: pointer to some position within @str
130 *
131 * Given a position @p with a UTF-8 encoded string @str, find the start
132 * of the previous UTF-8 character starting before @p. Returns %NULL if no
133 * UTF-8 characters are present in @str before @p.
134 *
135 * @p does not have to be at the beginning of a UTF-8 character. No check
136 * is made to see if the character found is actually valid other than
137 * it starts with an appropriate byte.
138 *
139 * Returns: (transfer none) (nullable): a pointer to the found character or %NULL.
140 */
141 gchar *
g_utf8_find_prev_char(const gchar * str,const gchar * p)142 g_utf8_find_prev_char (const gchar *str,
143 const gchar *p)
144 {
145 while (p > str)
146 {
147 --p;
148 if ((*p & 0xc0) != 0x80)
149 return (gchar *)p;
150 }
151 return NULL;
152 }
153
154 /**
155 * g_utf8_find_next_char:
156 * @p: a pointer to a position within a UTF-8 encoded string
157 * @end: (nullable): a pointer to the byte following the end of the string,
158 * or %NULL to indicate that the string is nul-terminated
159 *
160 * Finds the start of the next UTF-8 character in the string after @p.
161 *
162 * @p does not have to be at the beginning of a UTF-8 character. No check
163 * is made to see if the character found is actually valid other than
164 * it starts with an appropriate byte.
165 *
166 * If @end is %NULL, the return value will never be %NULL: if the end of the
167 * string is reached, a pointer to the terminating nul byte is returned. If
168 * @end is non-%NULL, the return value will be %NULL if the end of the string
169 * is reached.
170 *
171 * Returns: (transfer none) (nullable): a pointer to the found character or %NULL if @end is
172 * set and is reached
173 */
174 gchar *
g_utf8_find_next_char(const gchar * p,const gchar * end)175 g_utf8_find_next_char (const gchar *p,
176 const gchar *end)
177 {
178 if (end)
179 {
180 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
181 ;
182 return (p >= end) ? NULL : (gchar *)p;
183 }
184 else
185 {
186 for (++p; (*p & 0xc0) == 0x80; ++p)
187 ;
188 return (gchar *)p;
189 }
190 }
191
192 /**
193 * g_utf8_prev_char:
194 * @p: a pointer to a position within a UTF-8 encoded string
195 *
196 * Finds the previous UTF-8 character in the string before @p.
197 *
198 * @p does not have to be at the beginning of a UTF-8 character. No check
199 * is made to see if the character found is actually valid other than
200 * it starts with an appropriate byte. If @p might be the first
201 * character of the string, you must use g_utf8_find_prev_char() instead.
202 *
203 * Returns: (transfer none) (not nullable): a pointer to the found character
204 */
205 gchar *
g_utf8_prev_char(const gchar * p)206 g_utf8_prev_char (const gchar *p)
207 {
208 while (TRUE)
209 {
210 p--;
211 if ((*p & 0xc0) != 0x80)
212 return (gchar *)p;
213 }
214 }
215
216 /**
217 * g_utf8_strlen:
218 * @p: pointer to the start of a UTF-8 encoded string
219 * @max: the maximum number of bytes to examine. If @max
220 * is less than 0, then the string is assumed to be
221 * nul-terminated. If @max is 0, @p will not be examined and
222 * may be %NULL. If @max is greater than 0, up to @max
223 * bytes are examined
224 *
225 * Computes the length of the string in characters, not including
226 * the terminating nul character. If the @max'th byte falls in the
227 * middle of a character, the last (partial) character is not counted.
228 *
229 * Returns: the length of the string in characters
230 */
231 glong
g_utf8_strlen(const gchar * p,gssize max)232 g_utf8_strlen (const gchar *p,
233 gssize max)
234 {
235 glong len = 0;
236 const gchar *start = p;
237 g_return_val_if_fail (p != NULL || max == 0, 0);
238
239 if (max < 0)
240 {
241 while (*p)
242 {
243 p = g_utf8_next_char (p);
244 ++len;
245 }
246 }
247 else
248 {
249 if (max == 0 || !*p)
250 return 0;
251
252 p = g_utf8_next_char (p);
253
254 while (p - start < max && *p)
255 {
256 ++len;
257 p = g_utf8_next_char (p);
258 }
259
260 /* only do the last len increment if we got a complete
261 * char (don't count partial chars)
262 */
263 if (p - start <= max)
264 ++len;
265 }
266
267 return len;
268 }
269
270 /**
271 * g_utf8_substring:
272 * @str: a UTF-8 encoded string
273 * @start_pos: a character offset within @str
274 * @end_pos: another character offset within @str
275 *
276 * Copies a substring out of a UTF-8 encoded string.
277 * The substring will contain @end_pos - @start_pos characters.
278 *
279 * Returns: (transfer full): a newly allocated copy of the requested
280 * substring. Free with g_free() when no longer needed.
281 *
282 * Since: 2.30
283 */
284 gchar *
g_utf8_substring(const gchar * str,glong start_pos,glong end_pos)285 g_utf8_substring (const gchar *str,
286 glong start_pos,
287 glong end_pos)
288 {
289 gchar *start, *end, *out;
290
291 start = g_utf8_offset_to_pointer (str, start_pos);
292 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
293
294 out = g_malloc (end - start + 1);
295 memcpy (out, start, end - start);
296 out[end - start] = 0;
297
298 return out;
299 }
300
301 /**
302 * g_utf8_get_char:
303 * @p: a pointer to Unicode character encoded as UTF-8
304 *
305 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
306 *
307 * If @p does not point to a valid UTF-8 encoded character, results
308 * are undefined. If you are not sure that the bytes are complete
309 * valid Unicode characters, you should use g_utf8_get_char_validated()
310 * instead.
311 *
312 * Returns: the resulting character
313 */
314 gunichar
g_utf8_get_char(const gchar * p)315 g_utf8_get_char (const gchar *p)
316 {
317 int i, mask = 0, len;
318 gunichar result;
319 unsigned char c = (unsigned char) *p;
320
321 UTF8_COMPUTE (c, mask, len);
322 if (len == -1)
323 return (gunichar)-1;
324 UTF8_GET (result, p, i, mask, len);
325
326 return result;
327 }
328
329 /**
330 * g_utf8_offset_to_pointer:
331 * @str: a UTF-8 encoded string
332 * @offset: a character offset within @str
333 *
334 * Converts from an integer character offset to a pointer to a position
335 * within the string.
336 *
337 * Since 2.10, this function allows to pass a negative @offset to
338 * step backwards. It is usually worth stepping backwards from the end
339 * instead of forwards if @offset is in the last fourth of the string,
340 * since moving forward is about 3 times faster than moving backward.
341 *
342 * Note that this function doesn't abort when reaching the end of @str.
343 * Therefore you should be sure that @offset is within string boundaries
344 * before calling that function. Call g_utf8_strlen() when unsure.
345 * This limitation exists as this function is called frequently during
346 * text rendering and therefore has to be as fast as possible.
347 *
348 * Returns: (transfer none): the resulting pointer
349 */
350 gchar *
g_utf8_offset_to_pointer(const gchar * str,glong offset)351 g_utf8_offset_to_pointer (const gchar *str,
352 glong offset)
353 {
354 const gchar *s = str;
355
356 if (offset > 0)
357 while (offset--)
358 s = g_utf8_next_char (s);
359 else
360 {
361 const char *s1;
362
363 /* This nice technique for fast backwards stepping
364 * through a UTF-8 string was dubbed "stutter stepping"
365 * by its inventor, Larry Ewing.
366 */
367 while (offset)
368 {
369 s1 = s;
370 s += offset;
371 while ((*s & 0xc0) == 0x80)
372 s--;
373
374 offset += g_utf8_pointer_to_offset (s, s1);
375 }
376 }
377
378 return (gchar *)s;
379 }
380
381 /**
382 * g_utf8_pointer_to_offset:
383 * @str: a UTF-8 encoded string
384 * @pos: a pointer to a position within @str
385 *
386 * Converts from a pointer to position within a string to an integer
387 * character offset.
388 *
389 * Since 2.10, this function allows @pos to be before @str, and returns
390 * a negative offset in this case.
391 *
392 * Returns: the resulting character offset
393 */
394 glong
g_utf8_pointer_to_offset(const gchar * str,const gchar * pos)395 g_utf8_pointer_to_offset (const gchar *str,
396 const gchar *pos)
397 {
398 const gchar *s = str;
399 glong offset = 0;
400
401 if (pos < str)
402 offset = - g_utf8_pointer_to_offset (pos, str);
403 else
404 while (s < pos)
405 {
406 s = g_utf8_next_char (s);
407 offset++;
408 }
409
410 return offset;
411 }
412
413
414 /**
415 * g_utf8_strncpy:
416 * @dest: (transfer none): buffer to fill with characters from @src
417 * @src: UTF-8 encoded string
418 * @n: character count
419 *
420 * Like the standard C strncpy() function, but copies a given number
421 * of characters instead of a given number of bytes. The @src string
422 * must be valid UTF-8 encoded text. (Use g_utf8_validate() on all
423 * text before trying to use UTF-8 utility functions with it.)
424 *
425 * Note you must ensure @dest is at least 4 * @n to fit the
426 * largest possible UTF-8 characters
427 *
428 * Returns: (transfer none): @dest
429 */
430 gchar *
g_utf8_strncpy(gchar * dest,const gchar * src,gsize n)431 g_utf8_strncpy (gchar *dest,
432 const gchar *src,
433 gsize n)
434 {
435 const gchar *s = src;
436 while (n && *s)
437 {
438 s = g_utf8_next_char(s);
439 n--;
440 }
441 strncpy(dest, src, s - src);
442 dest[s - src] = 0;
443 return dest;
444 }
445
446 /* unicode_strchr */
447
448 /**
449 * g_unichar_to_utf8:
450 * @c: a Unicode character code
451 * @outbuf: (out caller-allocates) (optional): output buffer, must have at
452 * least 6 bytes of space. If %NULL, the length will be computed and
453 * returned and nothing will be written to @outbuf.
454 *
455 * Converts a single character to UTF-8.
456 *
457 * Returns: number of bytes written
458 */
459 int
g_unichar_to_utf8(gunichar c,gchar * outbuf)460 g_unichar_to_utf8 (gunichar c,
461 gchar *outbuf)
462 {
463 /* If this gets modified, also update the copy in g_string_insert_unichar() */
464 guint len = 0;
465 int first;
466 int i;
467
468 if (c < 0x80)
469 {
470 first = 0;
471 len = 1;
472 }
473 else if (c < 0x800)
474 {
475 first = 0xc0;
476 len = 2;
477 }
478 else if (c < 0x10000)
479 {
480 first = 0xe0;
481 len = 3;
482 }
483 else if (c < 0x200000)
484 {
485 first = 0xf0;
486 len = 4;
487 }
488 else if (c < 0x4000000)
489 {
490 first = 0xf8;
491 len = 5;
492 }
493 else
494 {
495 first = 0xfc;
496 len = 6;
497 }
498
499 if (outbuf)
500 {
501 for (i = len - 1; i > 0; --i)
502 {
503 outbuf[i] = (c & 0x3f) | 0x80;
504 c >>= 6;
505 }
506 outbuf[0] = c | first;
507 }
508
509 return len;
510 }
511
512 /**
513 * g_utf8_strchr:
514 * @p: a nul-terminated UTF-8 encoded string
515 * @len: the maximum length of @p
516 * @c: a Unicode character
517 *
518 * Finds the leftmost occurrence of the given Unicode character
519 * in a UTF-8 encoded string, while limiting the search to @len bytes.
520 * If @len is -1, allow unbounded search.
521 *
522 * Returns: (transfer none) (nullable): %NULL if the string does not contain the character,
523 * otherwise, a pointer to the start of the leftmost occurrence
524 * of the character in the string.
525 */
526 gchar *
g_utf8_strchr(const char * p,gssize len,gunichar c)527 g_utf8_strchr (const char *p,
528 gssize len,
529 gunichar c)
530 {
531 gchar ch[10];
532
533 gint charlen = g_unichar_to_utf8 (c, ch);
534 ch[charlen] = '\0';
535
536 return g_strstr_len (p, len, ch);
537 }
538
539
540 /**
541 * g_utf8_strrchr:
542 * @p: a nul-terminated UTF-8 encoded string
543 * @len: the maximum length of @p
544 * @c: a Unicode character
545 *
546 * Find the rightmost occurrence of the given Unicode character
547 * in a UTF-8 encoded string, while limiting the search to @len bytes.
548 * If @len is -1, allow unbounded search.
549 *
550 * Returns: (transfer none) (nullable): %NULL if the string does not contain the character,
551 * otherwise, a pointer to the start of the rightmost occurrence
552 * of the character in the string.
553 */
554 gchar *
g_utf8_strrchr(const char * p,gssize len,gunichar c)555 g_utf8_strrchr (const char *p,
556 gssize len,
557 gunichar c)
558 {
559 gchar ch[10];
560
561 gint charlen = g_unichar_to_utf8 (c, ch);
562 ch[charlen] = '\0';
563
564 return g_strrstr_len (p, len, ch);
565 }
566
567
568 /* Like g_utf8_get_char, but take a maximum length
569 * and return (gunichar)-2 on incomplete trailing character;
570 * also check for malformed or overlong sequences
571 * and return (gunichar)-1 in this case.
572 */
573 static inline gunichar
g_utf8_get_char_extended(const gchar * p,gssize max_len)574 g_utf8_get_char_extended (const gchar *p,
575 gssize max_len)
576 {
577 guint i, len;
578 gunichar min_code;
579 gunichar wc = (guchar) *p;
580 const gunichar partial_sequence = (gunichar) -2;
581 const gunichar malformed_sequence = (gunichar) -1;
582
583 if (wc < 0x80)
584 {
585 return wc;
586 }
587 else if (G_UNLIKELY (wc < 0xc0))
588 {
589 return malformed_sequence;
590 }
591 else if (wc < 0xe0)
592 {
593 len = 2;
594 wc &= 0x1f;
595 min_code = 1 << 7;
596 }
597 else if (wc < 0xf0)
598 {
599 len = 3;
600 wc &= 0x0f;
601 min_code = 1 << 11;
602 }
603 else if (wc < 0xf8)
604 {
605 len = 4;
606 wc &= 0x07;
607 min_code = 1 << 16;
608 }
609 else if (wc < 0xfc)
610 {
611 len = 5;
612 wc &= 0x03;
613 min_code = 1 << 21;
614 }
615 else if (wc < 0xfe)
616 {
617 len = 6;
618 wc &= 0x01;
619 min_code = 1 << 26;
620 }
621 else
622 {
623 return malformed_sequence;
624 }
625
626 if (G_UNLIKELY (max_len >= 0 && len > max_len))
627 {
628 for (i = 1; i < max_len; i++)
629 {
630 if ((((guchar *)p)[i] & 0xc0) != 0x80)
631 return malformed_sequence;
632 }
633 return partial_sequence;
634 }
635
636 for (i = 1; i < len; ++i)
637 {
638 gunichar ch = ((guchar *)p)[i];
639
640 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
641 {
642 if (ch)
643 return malformed_sequence;
644 else
645 return partial_sequence;
646 }
647
648 wc <<= 6;
649 wc |= (ch & 0x3f);
650 }
651
652 if (G_UNLIKELY (wc < min_code))
653 return malformed_sequence;
654
655 return wc;
656 }
657
658 /**
659 * g_utf8_get_char_validated:
660 * @p: a pointer to Unicode character encoded as UTF-8
661 * @max_len: the maximum number of bytes to read, or -1 if @p is nul-terminated
662 *
663 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
664 * This function checks for incomplete characters, for invalid characters
665 * such as characters that are out of the range of Unicode, and for
666 * overlong encodings of valid characters.
667 *
668 * Note that g_utf8_get_char_validated() returns (gunichar)-2 if
669 * @max_len is positive and any of the bytes in the first UTF-8 character
670 * sequence are nul.
671 *
672 * Returns: the resulting character. If @p points to a partial
673 * sequence at the end of a string that could begin a valid
674 * character (or if @max_len is zero), returns (gunichar)-2;
675 * otherwise, if @p does not point to a valid UTF-8 encoded
676 * Unicode character, returns (gunichar)-1.
677 */
678 gunichar
g_utf8_get_char_validated(const gchar * p,gssize max_len)679 g_utf8_get_char_validated (const gchar *p,
680 gssize max_len)
681 {
682 gunichar result;
683
684 if (max_len == 0)
685 return (gunichar)-2;
686
687 result = g_utf8_get_char_extended (p, max_len);
688
689 if (result & 0x80000000)
690 return result;
691 else if (!UNICODE_VALID (result))
692 return (gunichar)-1;
693 else
694 return result;
695 }
696
697 #define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
698
699 /**
700 * g_utf8_to_ucs4_fast:
701 * @str: a UTF-8 encoded string
702 * @len: the maximum length of @str to use, in bytes. If @len < 0,
703 * then the string is nul-terminated.
704 * @items_written: (out caller-allocates) (optional): location to store the
705 * number of characters in the result, or %NULL.
706 *
707 * Convert a string from UTF-8 to a 32-bit fixed width
708 * representation as UCS-4, assuming valid UTF-8 input.
709 * This function is roughly twice as fast as g_utf8_to_ucs4()
710 * but does no error checking on the input. A trailing 0 character
711 * will be added to the string after the converted text.
712 *
713 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
714 * This value must be freed with g_free().
715 */
716 gunichar *
g_utf8_to_ucs4_fast(const gchar * str,glong len,glong * items_written)717 g_utf8_to_ucs4_fast (const gchar *str,
718 glong len,
719 glong *items_written)
720 {
721 gunichar *result;
722 gint n_chars, i;
723 const gchar *p;
724
725 g_return_val_if_fail (str != NULL, NULL);
726
727 p = str;
728 n_chars = 0;
729 if (len < 0)
730 {
731 while (*p)
732 {
733 p = g_utf8_next_char (p);
734 ++n_chars;
735 }
736 }
737 else
738 {
739 while (p < str + len && *p)
740 {
741 p = g_utf8_next_char (p);
742 ++n_chars;
743 }
744 }
745
746 result = g_new (gunichar, n_chars + 1);
747
748 p = str;
749 for (i=0; i < n_chars; i++)
750 {
751 guchar first = (guchar)*p++;
752 gunichar wc;
753
754 if (first < 0xc0)
755 {
756 /* We really hope first < 0x80, but we don't want to test an
757 * extra branch for invalid input, which this function
758 * does not care about. Handling unexpected continuation bytes
759 * here will do the least damage. */
760 wc = first;
761 }
762 else
763 {
764 gunichar c1 = CONT_BYTE_FAST(p);
765 if (first < 0xe0)
766 {
767 wc = ((first & 0x1f) << 6) | c1;
768 }
769 else
770 {
771 gunichar c2 = CONT_BYTE_FAST(p);
772 if (first < 0xf0)
773 {
774 wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
775 }
776 else
777 {
778 gunichar c3 = CONT_BYTE_FAST(p);
779 wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
780 if (G_UNLIKELY (first >= 0xf8))
781 {
782 /* This can't be valid UTF-8, but g_utf8_next_char()
783 * and company allow out-of-range sequences */
784 gunichar mask = 1 << 20;
785 while ((wc & mask) != 0)
786 {
787 wc <<= 6;
788 wc |= CONT_BYTE_FAST(p);
789 mask <<= 5;
790 }
791 wc &= mask - 1;
792 }
793 }
794 }
795 }
796 result[i] = wc;
797 }
798 result[i] = 0;
799
800 if (items_written)
801 *items_written = i;
802
803 return result;
804 }
805
806 static gpointer
try_malloc_n(gsize n_blocks,gsize n_block_bytes,GError ** error)807 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
808 {
809 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
810 if (ptr == NULL)
811 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
812 _("Failed to allocate memory"));
813 return ptr;
814 }
815
816 /**
817 * g_utf8_to_ucs4:
818 * @str: a UTF-8 encoded string
819 * @len: the maximum length of @str to use, in bytes. If @len < 0,
820 * then the string is nul-terminated.
821 * @items_read: (out caller-allocates) (optional): location to store number of
822 * bytes read, or %NULL.
823 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
824 * returned in case @str contains a trailing partial
825 * character. If an error occurs then the index of the
826 * invalid input is stored here.
827 * @items_written: (out caller-allocates) (optional): location to store number
828 * of characters written or %NULL. The value here stored does not include
829 * the trailing 0 character.
830 * @error: location to store the error occurring, or %NULL to ignore
831 * errors. Any of the errors in #GConvertError other than
832 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
833 *
834 * Convert a string from UTF-8 to a 32-bit fixed width
835 * representation as UCS-4. A trailing 0 character will be added to the
836 * string after the converted text.
837 *
838 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
839 * This value must be freed with g_free(). If an error occurs,
840 * %NULL will be returned and @error set.
841 */
842 gunichar *
g_utf8_to_ucs4(const gchar * str,glong len,glong * items_read,glong * items_written,GError ** error)843 g_utf8_to_ucs4 (const gchar *str,
844 glong len,
845 glong *items_read,
846 glong *items_written,
847 GError **error)
848 {
849 gunichar *result = NULL;
850 gint n_chars, i;
851 const gchar *in;
852
853 in = str;
854 n_chars = 0;
855 while ((len < 0 || str + len - in > 0) && *in)
856 {
857 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
858 if (wc & 0x80000000)
859 {
860 if (wc == (gunichar)-2)
861 {
862 if (items_read)
863 break;
864 else
865 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
866 _("Partial character sequence at end of input"));
867 }
868 else
869 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
870 _("Invalid byte sequence in conversion input"));
871
872 goto err_out;
873 }
874
875 n_chars++;
876
877 in = g_utf8_next_char (in);
878 }
879
880 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
881 if (result == NULL)
882 goto err_out;
883
884 in = str;
885 for (i=0; i < n_chars; i++)
886 {
887 result[i] = g_utf8_get_char (in);
888 in = g_utf8_next_char (in);
889 }
890 result[i] = 0;
891
892 if (items_written)
893 *items_written = n_chars;
894
895 err_out:
896 if (items_read)
897 *items_read = in - str;
898
899 return result;
900 }
901
902 /**
903 * g_ucs4_to_utf8:
904 * @str: a UCS-4 encoded string
905 * @len: the maximum length (number of characters) of @str to use.
906 * If @len < 0, then the string is nul-terminated.
907 * @items_read: (out caller-allocates) (optional): location to store number of
908 * characters read, or %NULL.
909 * @items_written: (out caller-allocates) (optional): location to store number
910 * of bytes written or %NULL. The value here stored does not include the
911 * trailing 0 byte.
912 * @error: location to store the error occurring, or %NULL to ignore
913 * errors. Any of the errors in #GConvertError other than
914 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
915 *
916 * Convert a string from a 32-bit fixed width representation as UCS-4.
917 * to UTF-8. The result will be terminated with a 0 byte.
918 *
919 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
920 * This value must be freed with g_free(). If an error occurs,
921 * %NULL will be returned and @error set. In that case, @items_read
922 * will be set to the position of the first invalid input character.
923 */
924 gchar *
g_ucs4_to_utf8(const gunichar * str,glong len,glong * items_read,glong * items_written,GError ** error)925 g_ucs4_to_utf8 (const gunichar *str,
926 glong len,
927 glong *items_read,
928 glong *items_written,
929 GError **error)
930 {
931 gint result_length;
932 gchar *result = NULL;
933 gchar *p;
934 gint i;
935
936 result_length = 0;
937 for (i = 0; len < 0 || i < len ; i++)
938 {
939 if (!str[i])
940 break;
941
942 if (str[i] >= 0x80000000)
943 {
944 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
945 _("Character out of range for UTF-8"));
946 goto err_out;
947 }
948
949 result_length += UTF8_LENGTH (str[i]);
950 }
951
952 result = try_malloc_n (result_length + 1, 1, error);
953 if (result == NULL)
954 goto err_out;
955
956 p = result;
957
958 i = 0;
959 while (p < result + result_length)
960 p += g_unichar_to_utf8 (str[i++], p);
961
962 *p = '\0';
963
964 if (items_written)
965 *items_written = p - result;
966
967 err_out:
968 if (items_read)
969 *items_read = i;
970
971 return result;
972 }
973
974 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
975
976 /**
977 * g_utf16_to_utf8:
978 * @str: a UTF-16 encoded string
979 * @len: the maximum length (number of #gunichar2) of @str to use.
980 * If @len < 0, then the string is nul-terminated.
981 * @items_read: (out caller-allocates) (optional): location to store number of
982 * words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
983 * be returned in case @str contains a trailing partial character. If
984 * an error occurs then the index of the invalid input is stored here.
985 * @items_written: (out caller-allocates) (optional): location to store number
986 * of bytes written, or %NULL. The value stored here does not include the
987 * trailing 0 byte.
988 * @error: location to store the error occurring, or %NULL to ignore
989 * errors. Any of the errors in #GConvertError other than
990 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
991 *
992 * Convert a string from UTF-16 to UTF-8. The result will be
993 * terminated with a 0 byte.
994 *
995 * Note that the input is expected to be already in native endianness,
996 * an initial byte-order-mark character is not handled specially.
997 * g_convert() can be used to convert a byte buffer of UTF-16 data of
998 * ambiguous endianess.
999 *
1000 * Further note that this function does not validate the result
1001 * string; it may e.g. include embedded NUL characters. The only
1002 * validation done by this function is to ensure that the input can
1003 * be correctly interpreted as UTF-16, i.e. it doesn't contain
1004 * things unpaired surrogates.
1005 *
1006 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
1007 * This value must be freed with g_free(). If an error occurs,
1008 * %NULL will be returned and @error set.
1009 **/
1010 gchar *
g_utf16_to_utf8(const gunichar2 * str,glong len,glong * items_read,glong * items_written,GError ** error)1011 g_utf16_to_utf8 (const gunichar2 *str,
1012 glong len,
1013 glong *items_read,
1014 glong *items_written,
1015 GError **error)
1016 {
1017 /* This function and g_utf16_to_ucs4 are almost exactly identical -
1018 * The lines that differ are marked.
1019 */
1020 const gunichar2 *in;
1021 gchar *out;
1022 gchar *result = NULL;
1023 gint n_bytes;
1024 gunichar high_surrogate;
1025
1026 g_return_val_if_fail (str != NULL, NULL);
1027
1028 n_bytes = 0;
1029 in = str;
1030 high_surrogate = 0;
1031 while ((len < 0 || in - str < len) && *in)
1032 {
1033 gunichar2 c = *in;
1034 gunichar wc;
1035
1036 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1037 {
1038 if (high_surrogate)
1039 {
1040 wc = SURROGATE_VALUE (high_surrogate, c);
1041 high_surrogate = 0;
1042 }
1043 else
1044 {
1045 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1046 _("Invalid sequence in conversion input"));
1047 goto err_out;
1048 }
1049 }
1050 else
1051 {
1052 if (high_surrogate)
1053 {
1054 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1055 _("Invalid sequence in conversion input"));
1056 goto err_out;
1057 }
1058
1059 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1060 {
1061 high_surrogate = c;
1062 goto next1;
1063 }
1064 else
1065 wc = c;
1066 }
1067
1068 /********** DIFFERENT for UTF8/UCS4 **********/
1069 n_bytes += UTF8_LENGTH (wc);
1070
1071 next1:
1072 in++;
1073 }
1074
1075 if (high_surrogate && !items_read)
1076 {
1077 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1078 _("Partial character sequence at end of input"));
1079 goto err_out;
1080 }
1081
1082 /* At this point, everything is valid, and we just need to convert
1083 */
1084 /********** DIFFERENT for UTF8/UCS4 **********/
1085 result = try_malloc_n (n_bytes + 1, 1, error);
1086 if (result == NULL)
1087 goto err_out;
1088
1089 high_surrogate = 0;
1090 out = result;
1091 in = str;
1092 while (out < result + n_bytes)
1093 {
1094 gunichar2 c = *in;
1095 gunichar wc;
1096
1097 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1098 {
1099 wc = SURROGATE_VALUE (high_surrogate, c);
1100 high_surrogate = 0;
1101 }
1102 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1103 {
1104 high_surrogate = c;
1105 goto next2;
1106 }
1107 else
1108 wc = c;
1109
1110 /********** DIFFERENT for UTF8/UCS4 **********/
1111 out += g_unichar_to_utf8 (wc, out);
1112
1113 next2:
1114 in++;
1115 }
1116
1117 /********** DIFFERENT for UTF8/UCS4 **********/
1118 *out = '\0';
1119
1120 if (items_written)
1121 /********** DIFFERENT for UTF8/UCS4 **********/
1122 *items_written = out - result;
1123
1124 err_out:
1125 if (items_read)
1126 *items_read = in - str;
1127
1128 return result;
1129 }
1130
1131 /**
1132 * g_utf16_to_ucs4:
1133 * @str: a UTF-16 encoded string
1134 * @len: the maximum length (number of #gunichar2) of @str to use.
1135 * If @len < 0, then the string is nul-terminated.
1136 * @items_read: (out caller-allocates) (optional): location to store number of
1137 * words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1138 * be returned in case @str contains a trailing partial character. If
1139 * an error occurs then the index of the invalid input is stored here.
1140 * @items_written: (out caller-allocates) (optional): location to store number
1141 * of characters written, or %NULL. The value stored here does not include
1142 * the trailing 0 character.
1143 * @error: location to store the error occurring, or %NULL to ignore
1144 * errors. Any of the errors in #GConvertError other than
1145 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1146 *
1147 * Convert a string from UTF-16 to UCS-4. The result will be
1148 * nul-terminated.
1149 *
1150 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
1151 * This value must be freed with g_free(). If an error occurs,
1152 * %NULL will be returned and @error set.
1153 */
1154 gunichar *
g_utf16_to_ucs4(const gunichar2 * str,glong len,glong * items_read,glong * items_written,GError ** error)1155 g_utf16_to_ucs4 (const gunichar2 *str,
1156 glong len,
1157 glong *items_read,
1158 glong *items_written,
1159 GError **error)
1160 {
1161 const gunichar2 *in;
1162 gchar *out;
1163 gchar *result = NULL;
1164 gint n_bytes;
1165 gunichar high_surrogate;
1166
1167 g_return_val_if_fail (str != NULL, NULL);
1168
1169 n_bytes = 0;
1170 in = str;
1171 high_surrogate = 0;
1172 while ((len < 0 || in - str < len) && *in)
1173 {
1174 gunichar2 c = *in;
1175
1176 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1177 {
1178 if (high_surrogate)
1179 {
1180 high_surrogate = 0;
1181 }
1182 else
1183 {
1184 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1185 _("Invalid sequence in conversion input"));
1186 goto err_out;
1187 }
1188 }
1189 else
1190 {
1191 if (high_surrogate)
1192 {
1193 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1194 _("Invalid sequence in conversion input"));
1195 goto err_out;
1196 }
1197
1198 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1199 {
1200 high_surrogate = c;
1201 goto next1;
1202 }
1203 }
1204
1205 /********** DIFFERENT for UTF8/UCS4 **********/
1206 n_bytes += sizeof (gunichar);
1207
1208 next1:
1209 in++;
1210 }
1211
1212 if (high_surrogate && !items_read)
1213 {
1214 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1215 _("Partial character sequence at end of input"));
1216 goto err_out;
1217 }
1218
1219 /* At this point, everything is valid, and we just need to convert
1220 */
1221 /********** DIFFERENT for UTF8/UCS4 **********/
1222 result = try_malloc_n (n_bytes + 4, 1, error);
1223 if (result == NULL)
1224 goto err_out;
1225
1226 high_surrogate = 0;
1227 out = result;
1228 in = str;
1229 while (out < result + n_bytes)
1230 {
1231 gunichar2 c = *in;
1232 gunichar wc;
1233
1234 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1235 {
1236 wc = SURROGATE_VALUE (high_surrogate, c);
1237 high_surrogate = 0;
1238 }
1239 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1240 {
1241 high_surrogate = c;
1242 goto next2;
1243 }
1244 else
1245 wc = c;
1246
1247 /********** DIFFERENT for UTF8/UCS4 **********/
1248 *(gunichar *)out = wc;
1249 out += sizeof (gunichar);
1250
1251 next2:
1252 in++;
1253 }
1254
1255 /********** DIFFERENT for UTF8/UCS4 **********/
1256 *(gunichar *)out = 0;
1257
1258 if (items_written)
1259 /********** DIFFERENT for UTF8/UCS4 **********/
1260 *items_written = (out - result) / sizeof (gunichar);
1261
1262 err_out:
1263 if (items_read)
1264 *items_read = in - str;
1265
1266 return (gunichar *)result;
1267 }
1268
1269 /**
1270 * g_utf8_to_utf16:
1271 * @str: a UTF-8 encoded string
1272 * @len: the maximum length (number of bytes) of @str to use.
1273 * If @len < 0, then the string is nul-terminated.
1274 * @items_read: (out caller-allocates) (optional): location to store number of
1275 * bytes read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1276 * be returned in case @str contains a trailing partial character. If
1277 * an error occurs then the index of the invalid input is stored here.
1278 * @items_written: (out caller-allocates) (optional): location to store number
1279 * of #gunichar2 written, or %NULL. The value stored here does not include
1280 * the trailing 0.
1281 * @error: location to store the error occurring, or %NULL to ignore
1282 * errors. Any of the errors in #GConvertError other than
1283 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1284 *
1285 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1286 * added to the result after the converted text.
1287 *
1288 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1289 * This value must be freed with g_free(). If an error occurs,
1290 * %NULL will be returned and @error set.
1291 */
1292 gunichar2 *
g_utf8_to_utf16(const gchar * str,glong len,glong * items_read,glong * items_written,GError ** error)1293 g_utf8_to_utf16 (const gchar *str,
1294 glong len,
1295 glong *items_read,
1296 glong *items_written,
1297 GError **error)
1298 {
1299 gunichar2 *result = NULL;
1300 gint n16;
1301 const gchar *in;
1302 gint i;
1303
1304 g_return_val_if_fail (str != NULL, NULL);
1305
1306 in = str;
1307 n16 = 0;
1308 while ((len < 0 || str + len - in > 0) && *in)
1309 {
1310 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1311 if (wc & 0x80000000)
1312 {
1313 if (wc == (gunichar)-2)
1314 {
1315 if (items_read)
1316 break;
1317 else
1318 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1319 _("Partial character sequence at end of input"));
1320 }
1321 else
1322 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1323 _("Invalid byte sequence in conversion input"));
1324
1325 goto err_out;
1326 }
1327
1328 if (wc < 0xd800)
1329 n16 += 1;
1330 else if (wc < 0xe000)
1331 {
1332 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1333 _("Invalid sequence in conversion input"));
1334
1335 goto err_out;
1336 }
1337 else if (wc < 0x10000)
1338 n16 += 1;
1339 else if (wc < 0x110000)
1340 n16 += 2;
1341 else
1342 {
1343 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1344 _("Character out of range for UTF-16"));
1345
1346 goto err_out;
1347 }
1348
1349 in = g_utf8_next_char (in);
1350 }
1351
1352 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1353 if (result == NULL)
1354 goto err_out;
1355
1356 in = str;
1357 for (i = 0; i < n16;)
1358 {
1359 gunichar wc = g_utf8_get_char (in);
1360
1361 if (wc < 0x10000)
1362 {
1363 result[i++] = wc;
1364 }
1365 else
1366 {
1367 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1368 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1369 }
1370
1371 in = g_utf8_next_char (in);
1372 }
1373
1374 result[i] = 0;
1375
1376 if (items_written)
1377 *items_written = n16;
1378
1379 err_out:
1380 if (items_read)
1381 *items_read = in - str;
1382
1383 return result;
1384 }
1385
1386 /**
1387 * g_ucs4_to_utf16:
1388 * @str: a UCS-4 encoded string
1389 * @len: the maximum length (number of characters) of @str to use.
1390 * If @len < 0, then the string is nul-terminated.
1391 * @items_read: (out caller-allocates) (optional): location to store number of
1392 * bytes read, or %NULL. If an error occurs then the index of the invalid
1393 * input is stored here.
1394 * @items_written: (out caller-allocates) (optional): location to store number
1395 * of #gunichar2 written, or %NULL. The value stored here does not include
1396 * the trailing 0.
1397 * @error: location to store the error occurring, or %NULL to ignore
1398 * errors. Any of the errors in #GConvertError other than
1399 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1400 *
1401 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1402 * added to the result after the converted text.
1403 *
1404 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1405 * This value must be freed with g_free(). If an error occurs,
1406 * %NULL will be returned and @error set.
1407 */
1408 gunichar2 *
g_ucs4_to_utf16(const gunichar * str,glong len,glong * items_read,glong * items_written,GError ** error)1409 g_ucs4_to_utf16 (const gunichar *str,
1410 glong len,
1411 glong *items_read,
1412 glong *items_written,
1413 GError **error)
1414 {
1415 gunichar2 *result = NULL;
1416 gint n16;
1417 gint i, j;
1418
1419 n16 = 0;
1420 i = 0;
1421 while ((len < 0 || i < len) && str[i])
1422 {
1423 gunichar wc = str[i];
1424
1425 if (wc < 0xd800)
1426 n16 += 1;
1427 else if (wc < 0xe000)
1428 {
1429 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1430 _("Invalid sequence in conversion input"));
1431
1432 goto err_out;
1433 }
1434 else if (wc < 0x10000)
1435 n16 += 1;
1436 else if (wc < 0x110000)
1437 n16 += 2;
1438 else
1439 {
1440 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1441 _("Character out of range for UTF-16"));
1442
1443 goto err_out;
1444 }
1445
1446 i++;
1447 }
1448
1449 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1450 if (result == NULL)
1451 goto err_out;
1452
1453 for (i = 0, j = 0; j < n16; i++)
1454 {
1455 gunichar wc = str[i];
1456
1457 if (wc < 0x10000)
1458 {
1459 result[j++] = wc;
1460 }
1461 else
1462 {
1463 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1464 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1465 }
1466 }
1467 result[j] = 0;
1468
1469 if (items_written)
1470 *items_written = n16;
1471
1472 err_out:
1473 if (items_read)
1474 *items_read = i;
1475
1476 return result;
1477 }
1478
1479 #define VALIDATE_BYTE(mask, expect) \
1480 G_STMT_START { \
1481 if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1482 goto error; \
1483 } G_STMT_END
1484
1485 /* see IETF RFC 3629 Section 4 */
1486
1487 static const gchar *
fast_validate(const char * str)1488 fast_validate (const char *str)
1489
1490 {
1491 const gchar *p;
1492
1493 for (p = str; *p; p++)
1494 {
1495 if (*(guchar *)p < 128)
1496 /* done */;
1497 else
1498 {
1499 const gchar *last;
1500
1501 last = p;
1502 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1503 {
1504 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1505 goto error;
1506 }
1507 else
1508 {
1509 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1510 {
1511 switch (*(guchar *)p++ & 0x0f)
1512 {
1513 case 0:
1514 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1515 break;
1516 case 0x0d:
1517 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1518 break;
1519 default:
1520 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1521 }
1522 }
1523 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1524 {
1525 switch (*(guchar *)p++ & 0x07)
1526 {
1527 case 0:
1528 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1529 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1530 goto error;
1531 break;
1532 case 4:
1533 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1534 break;
1535 default:
1536 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1537 }
1538 p++;
1539 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1540 }
1541 else
1542 goto error;
1543 }
1544
1545 p++;
1546 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1547
1548 continue;
1549
1550 error:
1551 return last;
1552 }
1553 }
1554
1555 return p;
1556 }
1557
1558 static const gchar *
fast_validate_len(const char * str,gssize max_len)1559 fast_validate_len (const char *str,
1560 gssize max_len)
1561
1562 {
1563 const gchar *p;
1564
1565 g_assert (max_len >= 0);
1566
1567 for (p = str; ((p - str) < max_len) && *p; p++)
1568 {
1569 if (*(guchar *)p < 128)
1570 /* done */;
1571 else
1572 {
1573 const gchar *last;
1574
1575 last = p;
1576 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1577 {
1578 if (G_UNLIKELY (max_len - (p - str) < 2))
1579 goto error;
1580
1581 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1582 goto error;
1583 }
1584 else
1585 {
1586 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1587 {
1588 if (G_UNLIKELY (max_len - (p - str) < 3))
1589 goto error;
1590
1591 switch (*(guchar *)p++ & 0x0f)
1592 {
1593 case 0:
1594 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1595 break;
1596 case 0x0d:
1597 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1598 break;
1599 default:
1600 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1601 }
1602 }
1603 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1604 {
1605 if (G_UNLIKELY (max_len - (p - str) < 4))
1606 goto error;
1607
1608 switch (*(guchar *)p++ & 0x07)
1609 {
1610 case 0:
1611 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1612 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1613 goto error;
1614 break;
1615 case 4:
1616 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1617 break;
1618 default:
1619 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1620 }
1621 p++;
1622 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1623 }
1624 else
1625 goto error;
1626 }
1627
1628 p++;
1629 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1630
1631 continue;
1632
1633 error:
1634 return last;
1635 }
1636 }
1637
1638 return p;
1639 }
1640
1641 /**
1642 * g_utf8_validate:
1643 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1644 * @max_len: max bytes to validate, or -1 to go until NUL
1645 * @end: (out) (optional) (transfer none): return location for end of valid data
1646 *
1647 * Validates UTF-8 encoded text. @str is the text to validate;
1648 * if @str is nul-terminated, then @max_len can be -1, otherwise
1649 * @max_len should be the number of bytes to validate.
1650 * If @end is non-%NULL, then the end of the valid range
1651 * will be stored there (i.e. the start of the first invalid
1652 * character if some bytes were invalid, or the end of the text
1653 * being validated otherwise).
1654 *
1655 * Note that g_utf8_validate() returns %FALSE if @max_len is
1656 * positive and any of the @max_len bytes are nul.
1657 *
1658 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1659 * routines require valid UTF-8 as input; so data read from a file
1660 * or the network should be checked with g_utf8_validate() before
1661 * doing anything else with it.
1662 *
1663 * Returns: %TRUE if the text was valid UTF-8
1664 */
1665 gboolean
g_utf8_validate(const char * str,gssize max_len,const gchar ** end)1666 g_utf8_validate (const char *str,
1667 gssize max_len,
1668 const gchar **end)
1669
1670 {
1671 const gchar *p;
1672
1673 if (max_len >= 0)
1674 return g_utf8_validate_len (str, max_len, end);
1675
1676 p = fast_validate (str);
1677
1678 if (end)
1679 *end = p;
1680
1681 if (*p != '\0')
1682 return FALSE;
1683 else
1684 return TRUE;
1685 }
1686
1687 /**
1688 * g_utf8_validate_len:
1689 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1690 * @max_len: max bytes to validate
1691 * @end: (out) (optional) (transfer none): return location for end of valid data
1692 *
1693 * Validates UTF-8 encoded text.
1694 *
1695 * As with g_utf8_validate(), but @max_len must be set, and hence this function
1696 * will always return %FALSE if any of the bytes of @str are nul.
1697 *
1698 * Returns: %TRUE if the text was valid UTF-8
1699 * Since: 2.60
1700 */
1701 gboolean
g_utf8_validate_len(const char * str,gsize max_len,const gchar ** end)1702 g_utf8_validate_len (const char *str,
1703 gsize max_len,
1704 const gchar **end)
1705
1706 {
1707 const gchar *p;
1708
1709 p = fast_validate_len (str, max_len);
1710
1711 if (end)
1712 *end = p;
1713
1714 if (p != str + max_len)
1715 return FALSE;
1716 else
1717 return TRUE;
1718 }
1719
1720 /**
1721 * g_unichar_validate:
1722 * @ch: a Unicode character
1723 *
1724 * Checks whether @ch is a valid Unicode character. Some possible
1725 * integer values of @ch will not be valid. 0 is considered a valid
1726 * character, though it's normally a string terminator.
1727 *
1728 * Returns: %TRUE if @ch is a valid Unicode character
1729 **/
1730 gboolean
g_unichar_validate(gunichar ch)1731 g_unichar_validate (gunichar ch)
1732 {
1733 return UNICODE_VALID (ch);
1734 }
1735
1736 /**
1737 * g_utf8_strreverse:
1738 * @str: a UTF-8 encoded string
1739 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1740 * then the string is nul-terminated.
1741 *
1742 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1743 * (Use g_utf8_validate() on all text before trying to use UTF-8
1744 * utility functions with it.)
1745 *
1746 * This function is intended for programmatic uses of reversed strings.
1747 * It pays no attention to decomposed characters, combining marks, byte
1748 * order marks, directional indicators (LRM, LRO, etc) and similar
1749 * characters which might need special handling when reversing a string
1750 * for display purposes.
1751 *
1752 * Note that unlike g_strreverse(), this function returns
1753 * newly-allocated memory, which should be freed with g_free() when
1754 * no longer needed.
1755 *
1756 * Returns: (transfer full): a newly-allocated string which is the reverse of @str
1757 *
1758 * Since: 2.2
1759 */
1760 gchar *
g_utf8_strreverse(const gchar * str,gssize len)1761 g_utf8_strreverse (const gchar *str,
1762 gssize len)
1763 {
1764 gchar *r, *result;
1765 const gchar *p;
1766
1767 if (len < 0)
1768 len = strlen (str);
1769
1770 result = g_new (gchar, len + 1);
1771 r = result + len;
1772 p = str;
1773 while (r > result)
1774 {
1775 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1776 r -= skip;
1777 g_assert (r >= result);
1778 for (m = r; skip; skip--)
1779 *m++ = *p++;
1780 }
1781 result[len] = 0;
1782
1783 return result;
1784 }
1785
1786 /**
1787 * g_utf8_make_valid:
1788 * @str: string to coerce into UTF-8
1789 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1790 * then the string is nul-terminated.
1791 *
1792 * If the provided string is valid UTF-8, return a copy of it. If not,
1793 * return a copy in which bytes that could not be interpreted as valid Unicode
1794 * are replaced with the Unicode replacement character (U+FFFD).
1795 *
1796 * For example, this is an appropriate function to use if you have received
1797 * a string that was incorrectly declared to be UTF-8, and you need a valid
1798 * UTF-8 version of it that can be logged or displayed to the user, with the
1799 * assumption that it is close enough to ASCII or UTF-8 to be mostly
1800 * readable as-is.
1801 *
1802 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
1803 *
1804 * Since: 2.52
1805 */
1806 gchar *
g_utf8_make_valid(const gchar * str,gssize len)1807 g_utf8_make_valid (const gchar *str,
1808 gssize len)
1809 {
1810 GString *string;
1811 const gchar *remainder, *invalid;
1812 gsize remaining_bytes, valid_bytes;
1813
1814 g_return_val_if_fail (str != NULL, NULL);
1815
1816 if (len < 0)
1817 len = strlen (str);
1818
1819 string = NULL;
1820 remainder = str;
1821 remaining_bytes = len;
1822
1823 while (remaining_bytes != 0)
1824 {
1825 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1826 break;
1827 valid_bytes = invalid - remainder;
1828
1829 if (string == NULL)
1830 string = g_string_sized_new (remaining_bytes);
1831
1832 g_string_append_len (string, remainder, valid_bytes);
1833 /* append U+FFFD REPLACEMENT CHARACTER */
1834 g_string_append (string, "\357\277\275");
1835
1836 remaining_bytes -= valid_bytes + 1;
1837 remainder = invalid + 1;
1838 }
1839
1840 if (string == NULL)
1841 return g_strndup (str, len);
1842
1843 g_string_append_len (string, remainder, remaining_bytes);
1844 g_string_append_c (string, '\0');
1845
1846 g_assert (g_utf8_validate (string->str, -1, NULL));
1847
1848 return g_string_free (string, FALSE);
1849 }
1850