1 /* gutf8.c - Operations on UTF-8 strings.
3 * Copyright (C) 1999 Tom Tromey
4 * Copyright (C) 2000 Red Hat, Inc.
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.
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.
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/>.
28 #ifdef G_PLATFORM_WIN32
37 #include "gstrfuncs.h"
38 #include "gtestutils.h"
42 #include "gunicodeprivate.h"
44 #define UTF8_COMPUTE(Char, Mask, Len) \
50 else if ((Char & 0xe0) == 0xc0) \
55 else if ((Char & 0xf0) == 0xe0) \
60 else if ((Char & 0xf8) == 0xf0) \
65 else if ((Char & 0xfc) == 0xf8) \
70 else if ((Char & 0xfe) == 0xfc) \
78 #define UTF8_LENGTH(Char) \
79 ((Char) < 0x80 ? 1 : \
80 ((Char) < 0x800 ? 2 : \
81 ((Char) < 0x10000 ? 3 : \
82 ((Char) < 0x200000 ? 4 : \
83 ((Char) < 0x4000000 ? 5 : 6)))))
86 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
87 (Result) = (Chars)[0] & (Mask); \
88 for ((Count) = 1; (Count) < (Len); ++(Count)) \
90 if (((Chars)[(Count)] & 0xc0) != 0x80) \
96 (Result) |= ((Chars)[(Count)] & 0x3f); \
100 * Check whether a Unicode (5.2) char is in a valid range.
102 * The first check comes from the Unicode guarantee to never encode
103 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
105 * The second check covers surrogate pairs (category Cs).
107 * @param Char the character
109 #define UNICODE_VALID(Char) \
110 ((Char) < 0x110000 && \
111 (((Char) & 0xFFFFF800) != 0xD800))
114 static const gchar utf8_skip_data[256] = {
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 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,
121 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,
122 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
125 const gchar * const g_utf8_skip = utf8_skip_data;
128 * g_utf8_find_prev_char:
129 * @str: pointer to the beginning of a UTF-8 encoded string
130 * @p: pointer to some position within @str
132 * Given a position @p with a UTF-8 encoded string @str, find the start
133 * of the previous UTF-8 character starting before @p. Returns %NULL if no
134 * UTF-8 characters are present in @str before @p.
136 * @p does not have to be at the beginning of a UTF-8 character. No check
137 * is made to see if the character found is actually valid other than
138 * it starts with an appropriate byte.
140 * Returns: a pointer to the found character or %NULL.
143 g_utf8_find_prev_char (const char *str,
146 for (--p; p >= str; --p)
148 if ((*p & 0xc0) != 0x80)
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
160 * Finds the start of the next UTF-8 character in the string after @p.
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.
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
171 * Returns: (nullable): a pointer to the found character or %NULL if @end is
175 g_utf8_find_next_char (const gchar *p,
180 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
182 return (p >= end) ? NULL : (gchar *)p;
186 for (++p; (*p & 0xc0) == 0x80; ++p)
194 * @p: a pointer to a position within a UTF-8 encoded string
196 * Finds the previous UTF-8 character in the string before @p.
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.
203 * Returns: a pointer to the found character
206 g_utf8_prev_char (const gchar *p)
211 if ((*p & 0xc0) != 0x80)
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
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.
229 * Returns: the length of the string in characters
232 g_utf8_strlen (const gchar *p,
236 const gchar *start = p;
237 g_return_val_if_fail (p != NULL || max == 0, 0);
243 p = g_utf8_next_char (p);
252 p = g_utf8_next_char (p);
254 while (p - start < max && *p)
257 p = g_utf8_next_char (p);
260 /* only do the last len increment if we got a complete
261 * char (don't count partial chars)
263 if (p - start <= max)
272 * @str: a UTF-8 encoded string
273 * @start_pos: a character offset within @str
274 * @end_pos: another character offset within @str
276 * Copies a substring out of a UTF-8 encoded string.
277 * The substring will contain @end_pos - @start_pos characters.
279 * Returns: a newly allocated copy of the requested
280 * substring. Free with g_free() when no longer needed.
285 g_utf8_substring (const gchar *str,
289 gchar *start, *end, *out;
291 start = g_utf8_offset_to_pointer (str, start_pos);
292 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
294 out = g_malloc (end - start + 1);
295 memcpy (out, start, end - start);
296 out[end - start] = 0;
303 * @p: a pointer to Unicode character encoded as UTF-8
305 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
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()
312 * Returns: the resulting character
315 g_utf8_get_char (const gchar *p)
317 int i, mask = 0, len;
319 unsigned char c = (unsigned char) *p;
321 UTF8_COMPUTE (c, mask, len);
324 UTF8_GET (result, p, i, mask, len);
330 * g_utf8_offset_to_pointer:
331 * @str: a UTF-8 encoded string
332 * @offset: a character offset within @str
334 * Converts from an integer character offset to a pointer to a position
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.
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.
348 * Returns: the resulting pointer
351 g_utf8_offset_to_pointer (const gchar *str,
354 const gchar *s = str;
358 s = g_utf8_next_char (s);
363 /* This nice technique for fast backwards stepping
364 * through a UTF-8 string was dubbed "stutter stepping"
365 * by its inventor, Larry Ewing.
371 while ((*s & 0xc0) == 0x80)
374 offset += g_utf8_pointer_to_offset (s, s1);
382 * g_utf8_pointer_to_offset:
383 * @str: a UTF-8 encoded string
384 * @pos: a pointer to a position within @str
386 * Converts from a pointer to position within a string to a integer
389 * Since 2.10, this function allows @pos to be before @str, and returns
390 * a negative offset in this case.
392 * Returns: the resulting character offset
395 g_utf8_pointer_to_offset (const gchar *str,
398 const gchar *s = str;
402 offset = - g_utf8_pointer_to_offset (pos, str);
406 s = g_utf8_next_char (s);
416 * @dest: buffer to fill with characters from @src
417 * @src: UTF-8 encoded string
418 * @n: character count
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.)
425 * Note you must ensure @dest is at least 4 * @n to fit the
426 * largest possible UTF-8 characters
431 g_utf8_strncpy (gchar *dest,
435 const gchar *s = src;
438 s = g_utf8_next_char(s);
441 strncpy(dest, src, s - src);
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.
455 * Converts a single character to UTF-8.
457 * Returns: number of bytes written
460 g_unichar_to_utf8 (gunichar c,
463 /* If this gets modified, also update the copy in g_string_insert_unichar() */
478 else if (c < 0x10000)
483 else if (c < 0x200000)
488 else if (c < 0x4000000)
501 for (i = len - 1; i > 0; --i)
503 outbuf[i] = (c & 0x3f) | 0x80;
506 outbuf[0] = c | first;
514 * @p: a nul-terminated UTF-8 encoded string
515 * @len: the maximum length of @p
516 * @c: a Unicode character
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.
522 * Returns: %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.
527 g_utf8_strchr (const char *p,
533 gint charlen = g_unichar_to_utf8 (c, ch);
536 return g_strstr_len (p, len, ch);
542 * @p: a nul-terminated UTF-8 encoded string
543 * @len: the maximum length of @p
544 * @c: a Unicode character
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.
550 * Returns: %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.
555 g_utf8_strrchr (const char *p,
561 gint charlen = g_unichar_to_utf8 (c, ch);
564 return g_strrstr_len (p, len, ch);
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.
573 static inline gunichar
574 g_utf8_get_char_extended (const gchar *p,
579 gunichar wc = (guchar) *p;
580 const gunichar partial_sequence = (gunichar) -2;
581 const gunichar malformed_sequence = (gunichar) -1;
587 else if (G_UNLIKELY (wc < 0xc0))
589 return malformed_sequence;
623 return malformed_sequence;
626 if (G_UNLIKELY (max_len >= 0 && len > max_len))
628 for (i = 1; i < max_len; i++)
630 if ((((guchar *)p)[i] & 0xc0) != 0x80)
631 return malformed_sequence;
633 return partial_sequence;
636 for (i = 1; i < len; ++i)
638 gunichar ch = ((guchar *)p)[i];
640 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
643 return malformed_sequence;
645 return partial_sequence;
652 if (G_UNLIKELY (wc < min_code))
653 return malformed_sequence;
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
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.
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
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.
679 g_utf8_get_char_validated (const gchar *p,
687 result = g_utf8_get_char_extended (p, max_len);
689 if (result & 0x80000000)
691 else if (!UNICODE_VALID (result))
697 #define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
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.
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.
713 * Returns: a pointer to a newly allocated UCS-4 string.
714 * This value must be freed with g_free().
717 g_utf8_to_ucs4_fast (const gchar *str,
719 glong *items_written)
725 g_return_val_if_fail (str != NULL, NULL);
733 p = g_utf8_next_char (p);
739 while (p < str + len && *p)
741 p = g_utf8_next_char (p);
746 result = g_new (gunichar, n_chars + 1);
749 for (i=0; i < n_chars; i++)
751 guchar first = (guchar)*p++;
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. */
764 gunichar c1 = CONT_BYTE_FAST(p);
767 wc = ((first & 0x1f) << 6) | c1;
771 gunichar c2 = CONT_BYTE_FAST(p);
774 wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
778 gunichar c3 = CONT_BYTE_FAST(p);
779 wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
780 if (G_UNLIKELY (first >= 0xf8))
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)
788 wc |= CONT_BYTE_FAST(p);
807 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
809 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
811 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
812 _("Failed to allocate memory"));
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.
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.
838 * Returns: 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.
843 g_utf8_to_ucs4 (const gchar *str,
846 glong *items_written,
849 gunichar *result = NULL;
855 while ((len < 0 || str + len - in > 0) && *in)
857 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
860 if (wc == (gunichar)-2)
865 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
866 _("Partial character sequence at end of input"));
869 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
870 _("Invalid byte sequence in conversion input"));
877 in = g_utf8_next_char (in);
880 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
885 for (i=0; i < n_chars; i++)
887 result[i] = g_utf8_get_char (in);
888 in = g_utf8_next_char (in);
893 *items_written = n_chars;
897 *items_read = in - str;
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
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.
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.
919 * Returns: 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.
925 g_ucs4_to_utf8 (const gunichar *str,
928 glong *items_written,
932 gchar *result = NULL;
937 for (i = 0; len < 0 || i < len ; i++)
942 if (str[i] >= 0x80000000)
944 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
945 _("Character out of range for UTF-8"));
949 result_length += UTF8_LENGTH (str[i]);
952 result = try_malloc_n (result_length + 1, 1, error);
959 while (p < result + result_length)
960 p += g_unichar_to_utf8 (str[i++], p);
965 *items_written = p - result;
974 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
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
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.
992 * Convert a string from UTF-16 to UTF-8. The result will be
993 * terminated with a 0 byte.
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.
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.
1006 * Returns: 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.
1011 g_utf16_to_utf8 (const gunichar2 *str,
1014 glong *items_written,
1017 /* This function and g_utf16_to_ucs4 are almost exactly identical -
1018 * The lines that differ are marked.
1020 const gunichar2 *in;
1022 gchar *result = NULL;
1024 gunichar high_surrogate;
1026 g_return_val_if_fail (str != NULL, NULL);
1031 while ((len < 0 || in - str < len) && *in)
1036 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1040 wc = SURROGATE_VALUE (high_surrogate, c);
1045 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1046 _("Invalid sequence in conversion input"));
1054 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1055 _("Invalid sequence in conversion input"));
1059 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1068 /********** DIFFERENT for UTF8/UCS4 **********/
1069 n_bytes += UTF8_LENGTH (wc);
1075 if (high_surrogate && !items_read)
1077 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1078 _("Partial character sequence at end of input"));
1082 /* At this point, everything is valid, and we just need to convert
1084 /********** DIFFERENT for UTF8/UCS4 **********/
1085 result = try_malloc_n (n_bytes + 1, 1, error);
1092 while (out < result + n_bytes)
1097 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1099 wc = SURROGATE_VALUE (high_surrogate, c);
1102 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1110 /********** DIFFERENT for UTF8/UCS4 **********/
1111 out += g_unichar_to_utf8 (wc, out);
1117 /********** DIFFERENT for UTF8/UCS4 **********/
1121 /********** DIFFERENT for UTF8/UCS4 **********/
1122 *items_written = out - result;
1126 *items_read = in - str;
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.
1147 * Convert a string from UTF-16 to UCS-4. The result will be
1150 * Returns: 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.
1155 g_utf16_to_ucs4 (const gunichar2 *str,
1158 glong *items_written,
1161 const gunichar2 *in;
1163 gchar *result = NULL;
1165 gunichar high_surrogate;
1167 g_return_val_if_fail (str != NULL, NULL);
1172 while ((len < 0 || in - str < len) && *in)
1176 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1184 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1185 _("Invalid sequence in conversion input"));
1193 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1194 _("Invalid sequence in conversion input"));
1198 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1205 /********** DIFFERENT for UTF8/UCS4 **********/
1206 n_bytes += sizeof (gunichar);
1212 if (high_surrogate && !items_read)
1214 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1215 _("Partial character sequence at end of input"));
1219 /* At this point, everything is valid, and we just need to convert
1221 /********** DIFFERENT for UTF8/UCS4 **********/
1222 result = try_malloc_n (n_bytes + 4, 1, error);
1229 while (out < result + n_bytes)
1234 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1236 wc = SURROGATE_VALUE (high_surrogate, c);
1239 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1247 /********** DIFFERENT for UTF8/UCS4 **********/
1248 *(gunichar *)out = wc;
1249 out += sizeof (gunichar);
1255 /********** DIFFERENT for UTF8/UCS4 **********/
1256 *(gunichar *)out = 0;
1259 /********** DIFFERENT for UTF8/UCS4 **********/
1260 *items_written = (out - result) / sizeof (gunichar);
1264 *items_read = in - str;
1266 return (gunichar *)result;
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
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.
1285 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1286 * added to the result after the converted text.
1288 * Returns: 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.
1293 g_utf8_to_utf16 (const gchar *str,
1296 glong *items_written,
1299 gunichar2 *result = NULL;
1304 g_return_val_if_fail (str != NULL, NULL);
1308 while ((len < 0 || str + len - in > 0) && *in)
1310 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1311 if (wc & 0x80000000)
1313 if (wc == (gunichar)-2)
1318 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1319 _("Partial character sequence at end of input"));
1322 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1323 _("Invalid byte sequence in conversion input"));
1330 else if (wc < 0xe000)
1332 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1333 _("Invalid sequence in conversion input"));
1337 else if (wc < 0x10000)
1339 else if (wc < 0x110000)
1343 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1344 _("Character out of range for UTF-16"));
1349 in = g_utf8_next_char (in);
1352 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1357 for (i = 0; i < n16;)
1359 gunichar wc = g_utf8_get_char (in);
1367 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1368 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1371 in = g_utf8_next_char (in);
1377 *items_written = n16;
1381 *items_read = in - str;
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
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.
1401 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1402 * added to the result after the converted text.
1404 * Returns: 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.
1409 g_ucs4_to_utf16 (const gunichar *str,
1412 glong *items_written,
1415 gunichar2 *result = NULL;
1421 while ((len < 0 || i < len) && str[i])
1423 gunichar wc = str[i];
1427 else if (wc < 0xe000)
1429 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1430 _("Invalid sequence in conversion input"));
1434 else if (wc < 0x10000)
1436 else if (wc < 0x110000)
1440 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1441 _("Character out of range for UTF-16"));
1449 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1453 for (i = 0, j = 0; j < n16; i++)
1455 gunichar wc = str[i];
1463 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1464 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1470 *items_written = n16;
1479 #define VALIDATE_BYTE(mask, expect) \
1481 if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1485 /* see IETF RFC 3629 Section 4 */
1487 static const gchar *
1488 fast_validate (const char *str)
1493 for (p = str; *p; p++)
1495 if (*(guchar *)p < 128)
1502 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1504 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1509 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1511 switch (*(guchar *)p++ & 0x0f)
1514 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1517 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1520 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1523 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1525 switch (*(guchar *)p++ & 0x07)
1528 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1529 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1533 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1536 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1539 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1546 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1558 static const gchar *
1559 fast_validate_len (const char *str,
1565 g_assert (max_len >= 0);
1567 for (p = str; ((p - str) < max_len) && *p; p++)
1569 if (*(guchar *)p < 128)
1576 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1578 if (G_UNLIKELY (max_len - (p - str) < 2))
1581 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1586 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1588 if (G_UNLIKELY (max_len - (p - str) < 3))
1591 switch (*(guchar *)p++ & 0x0f)
1594 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1597 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1600 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1603 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1605 if (G_UNLIKELY (max_len - (p - str) < 4))
1608 switch (*(guchar *)p++ & 0x07)
1611 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1612 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1616 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1619 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1622 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1629 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
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
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).
1655 * Note that g_utf8_validate() returns %FALSE if @max_len is
1656 * positive and any of the @max_len bytes are nul.
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.
1663 * Returns: %TRUE if the text was valid UTF-8
1666 g_utf8_validate (const char *str,
1674 return _g_utf8_validate_len (str, max_len, end);
1676 p = fast_validate (str);
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
1693 * Validates UTF-8 encoded text.
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.
1698 * Returns: %TRUE if the text was valid UTF-8
1699 * Since: 2.60 (backported to 2.58)
1702 _g_utf8_validate_len (const char *str,
1709 p = fast_validate_len (str, max_len);
1714 if (p != str + max_len)
1721 * g_unichar_validate:
1722 * @ch: a Unicode character
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.
1728 * Returns: %TRUE if @ch is a valid Unicode character
1731 g_unichar_validate (gunichar ch)
1733 return UNICODE_VALID (ch);
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.
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.)
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.
1752 * Note that unlike g_strreverse(), this function returns
1753 * newly-allocated memory, which should be freed with g_free() when
1756 * Returns: a newly-allocated string which is the reverse of @str
1761 g_utf8_strreverse (const gchar *str,
1770 result = g_new (gchar, len + 1);
1775 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1777 for (m = r; skip; skip--)
1786 * g_utf8_make_valid:
1787 * @str: string to coerce into UTF-8
1788 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1789 * then the string is nul-terminated.
1791 * If the provided string is valid UTF-8, return a copy of it. If not,
1792 * return a copy in which bytes that could not be interpreted as valid Unicode
1793 * are replaced with the Unicode replacement character (U+FFFD).
1795 * For example, this is an appropriate function to use if you have received
1796 * a string that was incorrectly declared to be UTF-8, and you need a valid
1797 * UTF-8 version of it that can be logged or displayed to the user, with the
1798 * assumption that it is close enough to ASCII or UTF-8 to be mostly
1801 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
1806 g_utf8_make_valid (const gchar *str,
1810 const gchar *remainder, *invalid;
1811 gsize remaining_bytes, valid_bytes;
1813 g_return_val_if_fail (str != NULL, NULL);
1820 remaining_bytes = len;
1822 while (remaining_bytes != 0)
1824 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1826 valid_bytes = invalid - remainder;
1829 string = g_string_sized_new (remaining_bytes);
1831 g_string_append_len (string, remainder, valid_bytes);
1832 /* append U+FFFD REPLACEMENT CHARACTER */
1833 g_string_append (string, "\357\277\275");
1835 remaining_bytes -= valid_bytes + 1;
1836 remainder = invalid + 1;
1840 return g_strndup (str, len);
1842 g_string_append_len (string, remainder, remaining_bytes);
1843 g_string_append_c (string, '\0');
1845 g_assert (g_utf8_validate (string->str, -1, NULL));
1847 return g_string_free (string, FALSE);