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 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, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
30 #ifdef G_PLATFORM_WIN32
39 #include "gstrfuncs.h"
40 #include "gtestutils.h"
45 #define UTF8_COMPUTE(Char, Mask, Len) \
51 else if ((Char & 0xe0) == 0xc0) \
56 else if ((Char & 0xf0) == 0xe0) \
61 else if ((Char & 0xf8) == 0xf0) \
66 else if ((Char & 0xfc) == 0xf8) \
71 else if ((Char & 0xfe) == 0xfc) \
79 #define UTF8_LENGTH(Char) \
80 ((Char) < 0x80 ? 1 : \
81 ((Char) < 0x800 ? 2 : \
82 ((Char) < 0x10000 ? 3 : \
83 ((Char) < 0x200000 ? 4 : \
84 ((Char) < 0x4000000 ? 5 : 6)))))
87 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
88 (Result) = (Chars)[0] & (Mask); \
89 for ((Count) = 1; (Count) < (Len); ++(Count)) \
91 if (((Chars)[(Count)] & 0xc0) != 0x80) \
97 (Result) |= ((Chars)[(Count)] & 0x3f); \
101 * Check whether a Unicode (5.2) char is in a valid range.
103 * The first check comes from the Unicode guarantee to never encode
104 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
106 * The second check covers surrogate pairs (category Cs).
108 * The last two checks cover "Noncharacter": defined as:
109 * "A code point that is permanently reserved for
110 * internal use, and that should never be interchanged. In
111 * Unicode 3.1, these consist of the values U+nFFFE and U+nFFFF
112 * (where n is from 0 to 10_16) and the values U+FDD0..U+FDEF."
114 * @param Char the character
116 #define UNICODE_VALID(Char) \
117 ((Char) < 0x110000 && \
118 (((Char) & 0xFFFFF800) != 0xD800) && \
119 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
120 ((Char) & 0xFFFE) != 0xFFFE)
123 static const gchar utf8_skip_data[256] = {
124 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,
125 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,
126 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,
127 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,
128 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,
129 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,
130 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,
131 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
134 const gchar * const g_utf8_skip = utf8_skip_data;
137 * g_utf8_find_prev_char:
138 * @str: pointer to the beginning of a UTF-8 encoded string
139 * @p: pointer to some position within @str
141 * Given a position @p with a UTF-8 encoded string @str, find the start
142 * of the previous UTF-8 character starting before @p. Returns %NULL if no
143 * UTF-8 characters are present in @str before @p.
145 * @p does not have to be at the beginning of a UTF-8 character. No check
146 * is made to see if the character found is actually valid other than
147 * it starts with an appropriate byte.
149 * Return value: a pointer to the found character or %NULL.
152 g_utf8_find_prev_char (const char *str,
155 for (--p; p >= str; --p)
157 if ((*p & 0xc0) != 0x80)
164 * g_utf8_find_next_char:
165 * @p: a pointer to a position within a UTF-8 encoded string
166 * @end: a pointer to the byte following the end of the string,
167 * or %NULL to indicate that the string is nul-terminated.
169 * Finds the start of the next UTF-8 character in the string after @p.
171 * @p does not have to be at the beginning of a UTF-8 character. No check
172 * is made to see if the character found is actually valid other than
173 * it starts with an appropriate byte.
175 * Return value: a pointer to the found character or %NULL
178 g_utf8_find_next_char (const gchar *p,
184 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
187 for (++p; (*p & 0xc0) == 0x80; ++p)
190 return (p == end) ? NULL : (gchar *)p;
195 * @p: a pointer to a position within a UTF-8 encoded string
197 * Finds the previous UTF-8 character in the string before @p.
199 * @p does not have to be at the beginning of a UTF-8 character. No check
200 * is made to see if the character found is actually valid other than
201 * it starts with an appropriate byte. If @p might be the first
202 * character of the string, you must use g_utf8_find_prev_char() instead.
204 * Return value: a pointer to the found character.
207 g_utf8_prev_char (const gchar *p)
212 if ((*p & 0xc0) != 0x80)
219 * @p: pointer to the start of a UTF-8 encoded string
220 * @max: the maximum number of bytes to examine. If @max
221 * is less than 0, then the string is assumed to be
222 * nul-terminated. If @max is 0, @p will not be examined and
223 * may be %NULL. If @max is greater than 0, up to @max
226 * Computes the length of the string in characters, not including
227 * the terminating nul character. If the @max'th byte falls in the
228 * middle of a character, the last (partial) character is not counted.
230 * Return value: the length of the string in characters
233 g_utf8_strlen (const gchar *p,
237 const gchar *start = p;
238 g_return_val_if_fail (p != NULL || max == 0, 0);
244 p = g_utf8_next_char (p);
253 p = g_utf8_next_char (p);
255 while (p - start < max && *p)
258 p = g_utf8_next_char (p);
261 /* only do the last len increment if we got a complete
262 * char (don't count partial chars)
264 if (p - start <= max)
273 * @str: a UTF-8 encoded string
274 * @start_pos: a character offset within @str
275 * @end_pos: another character offset within @str
277 * Copies a substring out of a UTF-8 encoded string.
278 * The substring will contain @end_pos - @start_pos
281 * Returns: a newly allocated copy of the requested
282 * substring. Free with g_free() when no longer needed.
287 g_utf8_substring (const gchar *str,
291 gchar *start, *end, *out;
293 start = g_utf8_offset_to_pointer (str, start_pos);
294 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
296 out = g_malloc (end - start + 1);
297 memcpy (out, start, end - start);
298 out[end - start] = 0;
305 * @p: a pointer to Unicode character encoded as UTF-8
307 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
308 * If @p does not point to a valid UTF-8 encoded character, results are
309 * undefined. If you are not sure that the bytes are complete
310 * valid Unicode characters, you should use g_utf8_get_char_validated()
313 * Return value: the resulting character
316 g_utf8_get_char (const gchar *p)
318 int i, mask = 0, len;
320 unsigned char c = (unsigned char) *p;
322 UTF8_COMPUTE (c, mask, len);
325 UTF8_GET (result, p, i, mask, len);
331 * g_utf8_offset_to_pointer:
332 * @str: a UTF-8 encoded string
333 * @offset: a character offset within @str
335 * Converts from an integer character offset to a pointer to a position
338 * Since 2.10, this function allows to pass a negative @offset to
339 * step backwards. It is usually worth stepping backwards from the end
340 * instead of forwards if @offset is in the last fourth of the string,
341 * since moving forward is about 3 times faster than moving backward.
344 * This function doesn't abort when reaching the end of @str. Therefore
345 * you should be sure that @offset is within string boundaries before
346 * calling that function. Call g_utf8_strlen() when unsure.
348 * This limitation exists as this function is called frequently during
349 * text rendering and therefore has to be as fast as possible.
352 * Return value: the resulting pointer
355 g_utf8_offset_to_pointer (const gchar *str,
358 const gchar *s = str;
362 s = g_utf8_next_char (s);
367 /* This nice technique for fast backwards stepping
368 * through a UTF-8 string was dubbed "stutter stepping"
369 * by its inventor, Larry Ewing.
375 while ((*s & 0xc0) == 0x80)
378 offset += g_utf8_pointer_to_offset (s, s1);
386 * g_utf8_pointer_to_offset:
387 * @str: a UTF-8 encoded string
388 * @pos: a pointer to a position within @str
390 * Converts from a pointer to position within a string to a integer
393 * Since 2.10, this function allows @pos to be before @str, and returns
394 * a negative offset in this case.
396 * Return value: the resulting character offset
399 g_utf8_pointer_to_offset (const gchar *str,
402 const gchar *s = str;
406 offset = - g_utf8_pointer_to_offset (pos, str);
410 s = g_utf8_next_char (s);
420 * @dest: buffer to fill with characters from @src
421 * @src: UTF-8 encoded string
422 * @n: character count
424 * Like the standard C strncpy() function, but
425 * copies a given number of characters instead of a given number of
426 * bytes. The @src string must be valid UTF-8 encoded text.
427 * (Use g_utf8_validate() on all text before trying to use UTF-8
428 * utility functions with it.)
430 * Return value: @dest
433 g_utf8_strncpy (gchar *dest,
437 const gchar *s = src;
440 s = g_utf8_next_char(s);
443 strncpy(dest, src, s - src);
452 * @c: a Unicode character code
453 * @outbuf: output buffer, must have at least 6 bytes of space.
454 * If %NULL, the length will be computed and returned
455 * and nothing will be written to @outbuf.
457 * Converts a single character to UTF-8.
459 * Return value: number of bytes written
462 g_unichar_to_utf8 (gunichar c,
465 /* If this gets modified, also update the copy in g_string_insert_unichar() */
480 else if (c < 0x10000)
485 else if (c < 0x200000)
490 else if (c < 0x4000000)
503 for (i = len - 1; i > 0; --i)
505 outbuf[i] = (c & 0x3f) | 0x80;
508 outbuf[0] = c | first;
516 * @p: a nul-terminated UTF-8 encoded string
517 * @len: the maximum length of @p
518 * @c: a Unicode character
520 * Finds the leftmost occurrence of the given Unicode character
521 * in a UTF-8 encoded string, while limiting the search to @len bytes.
522 * If @len is -1, allow unbounded search.
524 * Return value: %NULL if the string does not contain the character,
525 * otherwise, a pointer to the start of the leftmost occurrence of
526 * the character in the string.
529 g_utf8_strchr (const char *p,
535 gint charlen = g_unichar_to_utf8 (c, ch);
538 return g_strstr_len (p, len, ch);
544 * @p: a nul-terminated UTF-8 encoded string
545 * @len: the maximum length of @p
546 * @c: a Unicode character
548 * Find the rightmost occurrence of the given Unicode character
549 * in a UTF-8 encoded string, while limiting the search to @len bytes.
550 * If @len is -1, allow unbounded search.
552 * Return value: %NULL if the string does not contain the character,
553 * otherwise, a pointer to the start of the rightmost occurrence of the
554 * character in the string.
557 g_utf8_strrchr (const char *p,
563 gint charlen = g_unichar_to_utf8 (c, ch);
566 return g_strrstr_len (p, len, ch);
570 /* Like g_utf8_get_char, but take a maximum length
571 * and return (gunichar)-2 on incomplete trailing character;
572 * also check for malformed or overlong sequences
573 * and return (gunichar)-1 in this case.
575 static inline gunichar
576 g_utf8_get_char_extended (const gchar *p,
581 gunichar wc = (guchar) *p;
587 else if (G_UNLIKELY (wc < 0xc0))
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)
636 for (i = 1; i < len; ++i)
638 gunichar ch = ((guchar *)p)[i];
640 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
652 if (G_UNLIKELY (wc < min_code))
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, for no maximum or
662 * if @p is nul-terminated
664 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
665 * This function checks for incomplete characters, for invalid characters
666 * such as characters that are out of the range of Unicode, and for
667 * overlong encodings of valid characters.
669 * Return value: the resulting character. If @p points to a partial
670 * sequence at the end of a string that could begin a valid
671 * character (or if @max_len is zero), returns (gunichar)-2;
672 * otherwise, if @p does not point to a valid UTF-8 encoded
673 * Unicode character, returns (gunichar)-1.
676 g_utf8_get_char_validated (const gchar *p,
684 result = g_utf8_get_char_extended (p, max_len);
686 if (result & 0x80000000)
688 else if (!UNICODE_VALID (result))
695 * g_utf8_to_ucs4_fast:
696 * @str: a UTF-8 encoded string
697 * @len: the maximum length of @str to use, in bytes. If @len < 0,
698 * then the string is nul-terminated.
699 * @items_written: (allow-none): location to store the number of characters in the
702 * Convert a string from UTF-8 to a 32-bit fixed width
703 * representation as UCS-4, assuming valid UTF-8 input.
704 * This function is roughly twice as fast as g_utf8_to_ucs4()
705 * but does no error checking on the input. A trailing 0 character
706 * will be added to the string after the converted text.
708 * Return value: a pointer to a newly allocated UCS-4 string.
709 * This value must be freed with g_free().
712 g_utf8_to_ucs4_fast (const gchar *str,
714 glong *items_written)
720 g_return_val_if_fail (str != NULL, NULL);
728 p = g_utf8_next_char (p);
734 while (p < str + len && *p)
736 p = g_utf8_next_char (p);
741 result = g_new (gunichar, n_chars + 1);
744 for (i=0; i < n_chars; i++)
746 gunichar wc = (guchar)*p++;
754 gunichar mask = 0x40;
756 if (G_UNLIKELY ((wc & mask) == 0))
758 /* It's an out-of-sequence 10xxxxxxx byte.
759 * Rather than making an ugly hash of this and the next byte
760 * and overrunning the buffer, it's more useful to treat it
761 * with a replacement character */
769 wc |= (guchar)(*p++) & 0x3f;
772 while((wc & mask) != 0);
789 * @str: a UTF-8 encoded string
790 * @len: the maximum length of @str to use, in bytes. If @len < 0,
791 * then the string is nul-terminated.
792 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
793 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
794 * returned in case @str contains a trailing partial
795 * character. If an error occurs then the index of the
796 * invalid input is stored here.
797 * @items_written: (allow-none): location to store number of characters written or %NULL.
798 * The value here stored does not include the trailing 0
800 * @error: location to store the error occurring, or %NULL to ignore
801 * errors. Any of the errors in #GConvertError other than
802 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
804 * Convert a string from UTF-8 to a 32-bit fixed width
805 * representation as UCS-4. A trailing 0 character will be added to the
806 * string after the converted text.
808 * Return value: a pointer to a newly allocated UCS-4 string.
809 * This value must be freed with g_free(). If an
810 * error occurs, %NULL will be returned and
814 g_utf8_to_ucs4 (const gchar *str,
817 glong *items_written,
820 gunichar *result = NULL;
826 while ((len < 0 || str + len - in > 0) && *in)
828 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
831 if (wc == (gunichar)-2)
836 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
837 _("Partial character sequence at end of input"));
840 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
841 _("Invalid byte sequence in conversion input"));
848 in = g_utf8_next_char (in);
851 result = g_new (gunichar, n_chars + 1);
854 for (i=0; i < n_chars; i++)
856 result[i] = g_utf8_get_char (in);
857 in = g_utf8_next_char (in);
862 *items_written = n_chars;
866 *items_read = in - str;
873 * @str: a UCS-4 encoded string
874 * @len: the maximum length (number of characters) of @str to use.
875 * If @len < 0, then the string is nul-terminated.
876 * @items_read: (allow-none): location to store number of characters read, or %NULL.
877 * @items_written: (allow-none): location to store number of bytes written or %NULL.
878 * The value here stored does not include the trailing 0
880 * @error: location to store the error occurring, or %NULL to ignore
881 * errors. Any of the errors in #GConvertError other than
882 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
884 * Convert a string from a 32-bit fixed width representation as UCS-4.
885 * to UTF-8. The result will be terminated with a 0 byte.
887 * Return value: a pointer to a newly allocated UTF-8 string.
888 * This value must be freed with g_free(). If an
889 * error occurs, %NULL will be returned and
890 * @error set. In that case, @items_read will be
891 * set to the position of the first invalid input
895 g_ucs4_to_utf8 (const gunichar *str,
898 glong *items_written,
902 gchar *result = NULL;
907 for (i = 0; len < 0 || i < len ; i++)
912 if (str[i] >= 0x80000000)
914 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
915 _("Character out of range for UTF-8"));
919 result_length += UTF8_LENGTH (str[i]);
922 result = g_malloc (result_length + 1);
926 while (p < result + result_length)
927 p += g_unichar_to_utf8 (str[i++], p);
932 *items_written = p - result;
941 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
945 * @str: a UTF-16 encoded string
946 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
947 * If @len < 0, then the string is nul-terminated.
948 * @items_read: (allow-none): location to store number of words read, or %NULL.
949 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
950 * returned in case @str contains a trailing partial
951 * character. If an error occurs then the index of the
952 * invalid input is stored here.
953 * @items_written: (allow-none): location to store number of bytes written, or %NULL.
954 * The value stored here does not include the trailing
956 * @error: location to store the error occurring, or %NULL to ignore
957 * errors. Any of the errors in #GConvertError other than
958 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
960 * Convert a string from UTF-16 to UTF-8. The result will be
961 * terminated with a 0 byte.
963 * Note that the input is expected to be already in native endianness,
964 * an initial byte-order-mark character is not handled specially.
965 * g_convert() can be used to convert a byte buffer of UTF-16 data of
966 * ambiguous endianess.
968 * Further note that this function does not validate the result
969 * string; it may e.g. include embedded NUL characters. The only
970 * validation done by this function is to ensure that the input can
971 * be correctly interpreted as UTF-16, i.e. it doesn't contain
972 * things unpaired surrogates.
974 * Return value: a pointer to a newly allocated UTF-8 string.
975 * This value must be freed with g_free(). If an
976 * error occurs, %NULL will be returned and
980 g_utf16_to_utf8 (const gunichar2 *str,
983 glong *items_written,
986 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
991 gchar *result = NULL;
993 gunichar high_surrogate;
995 g_return_val_if_fail (str != NULL, NULL);
1000 while ((len < 0 || in - str < len) && *in)
1005 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1009 wc = SURROGATE_VALUE (high_surrogate, c);
1014 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1015 _("Invalid sequence in conversion input"));
1023 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1024 _("Invalid sequence in conversion input"));
1028 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1037 /********** DIFFERENT for UTF8/UCS4 **********/
1038 n_bytes += UTF8_LENGTH (wc);
1044 if (high_surrogate && !items_read)
1046 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1047 _("Partial character sequence at end of input"));
1051 /* At this point, everything is valid, and we just need to convert
1053 /********** DIFFERENT for UTF8/UCS4 **********/
1054 result = g_malloc (n_bytes + 1);
1059 while (out < result + n_bytes)
1064 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1066 wc = SURROGATE_VALUE (high_surrogate, c);
1069 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1077 /********** DIFFERENT for UTF8/UCS4 **********/
1078 out += g_unichar_to_utf8 (wc, out);
1084 /********** DIFFERENT for UTF8/UCS4 **********/
1088 /********** DIFFERENT for UTF8/UCS4 **********/
1089 *items_written = out - result;
1093 *items_read = in - str;
1100 * @str: a UTF-16 encoded string
1101 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1102 * If @len < 0, then the string is nul-terminated.
1103 * @items_read: (allow-none): location to store number of words read, or %NULL.
1104 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1105 * returned in case @str contains a trailing partial
1106 * character. If an error occurs then the index of the
1107 * invalid input is stored here.
1108 * @items_written: (allow-none): location to store number of characters written, or %NULL.
1109 * The value stored here does not include the trailing
1111 * @error: location to store the error occurring, or %NULL to ignore
1112 * errors. Any of the errors in #GConvertError other than
1113 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1115 * Convert a string from UTF-16 to UCS-4. The result will be
1118 * Return value: a pointer to a newly allocated UCS-4 string.
1119 * This value must be freed with g_free(). If an
1120 * error occurs, %NULL will be returned and
1124 g_utf16_to_ucs4 (const gunichar2 *str,
1127 glong *items_written,
1130 const gunichar2 *in;
1132 gchar *result = NULL;
1134 gunichar high_surrogate;
1136 g_return_val_if_fail (str != NULL, NULL);
1141 while ((len < 0 || in - str < len) && *in)
1145 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1153 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1154 _("Invalid sequence in conversion input"));
1162 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163 _("Invalid sequence in conversion input"));
1167 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1174 /********** DIFFERENT for UTF8/UCS4 **********/
1175 n_bytes += sizeof (gunichar);
1181 if (high_surrogate && !items_read)
1183 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1184 _("Partial character sequence at end of input"));
1188 /* At this point, everything is valid, and we just need to convert
1190 /********** DIFFERENT for UTF8/UCS4 **********/
1191 result = g_malloc (n_bytes + 4);
1196 while (out < result + n_bytes)
1201 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1203 wc = SURROGATE_VALUE (high_surrogate, c);
1206 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1214 /********** DIFFERENT for UTF8/UCS4 **********/
1215 *(gunichar *)out = wc;
1216 out += sizeof (gunichar);
1222 /********** DIFFERENT for UTF8/UCS4 **********/
1223 *(gunichar *)out = 0;
1226 /********** DIFFERENT for UTF8/UCS4 **********/
1227 *items_written = (out - result) / sizeof (gunichar);
1231 *items_read = in - str;
1233 return (gunichar *)result;
1238 * @str: a UTF-8 encoded string
1239 * @len: the maximum length (number of bytes) of @str to use.
1240 * If @len < 0, then the string is nul-terminated.
1241 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
1242 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1243 * returned in case @str contains a trailing partial
1244 * character. If an error occurs then the index of the
1245 * invalid input is stored here.
1246 * @items_written: (allow-none): location to store number of <type>gunichar2</type> written,
1248 * The value stored here does not include the trailing 0.
1249 * @error: location to store the error occurring, or %NULL to ignore
1250 * errors. Any of the errors in #GConvertError other than
1251 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1253 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1254 * added to the result after the converted text.
1256 * Return value: a pointer to a newly allocated UTF-16 string.
1257 * This value must be freed with g_free(). If an
1258 * error occurs, %NULL will be returned and
1262 g_utf8_to_utf16 (const gchar *str,
1265 glong *items_written,
1268 gunichar2 *result = NULL;
1273 g_return_val_if_fail (str != NULL, NULL);
1277 while ((len < 0 || str + len - in > 0) && *in)
1279 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1280 if (wc & 0x80000000)
1282 if (wc == (gunichar)-2)
1287 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1288 _("Partial character sequence at end of input"));
1291 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1292 _("Invalid byte sequence in conversion input"));
1299 else if (wc < 0xe000)
1301 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1302 _("Invalid sequence in conversion input"));
1306 else if (wc < 0x10000)
1308 else if (wc < 0x110000)
1312 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1313 _("Character out of range for UTF-16"));
1318 in = g_utf8_next_char (in);
1321 result = g_new (gunichar2, n16 + 1);
1324 for (i = 0; i < n16;)
1326 gunichar wc = g_utf8_get_char (in);
1334 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1335 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1338 in = g_utf8_next_char (in);
1344 *items_written = n16;
1348 *items_read = in - str;
1355 * @str: a UCS-4 encoded string
1356 * @len: the maximum length (number of characters) of @str to use.
1357 * If @len < 0, then the string is nul-terminated.
1358 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
1359 * If an error occurs then the index of the invalid input
1361 * @items_written: (allow-none): location to store number of <type>gunichar2</type>
1362 * written, or %NULL. The value stored here does not
1363 * include the trailing 0.
1364 * @error: location to store the error occurring, or %NULL to ignore
1365 * errors. Any of the errors in #GConvertError other than
1366 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1368 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1369 * added to the result after the converted text.
1371 * Return value: a pointer to a newly allocated UTF-16 string.
1372 * This value must be freed with g_free(). If an
1373 * error occurs, %NULL will be returned and
1377 g_ucs4_to_utf16 (const gunichar *str,
1380 glong *items_written,
1383 gunichar2 *result = NULL;
1389 while ((len < 0 || i < len) && str[i])
1391 gunichar wc = str[i];
1395 else if (wc < 0xe000)
1397 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1398 _("Invalid sequence in conversion input"));
1402 else if (wc < 0x10000)
1404 else if (wc < 0x110000)
1408 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1409 _("Character out of range for UTF-16"));
1417 result = g_new (gunichar2, n16 + 1);
1419 for (i = 0, j = 0; j < n16; i++)
1421 gunichar wc = str[i];
1429 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1430 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1436 *items_written = n16;
1445 #define CONTINUATION_CHAR \
1447 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1450 val |= (*(guchar *)p) & 0x3f; \
1453 static const gchar *
1454 fast_validate (const char *str)
1461 for (p = str; *p; p++)
1463 if (*(guchar *)p < 128)
1470 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1472 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1475 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1480 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1483 val = *(guchar *)p & 0x0f;
1486 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1489 val = *(guchar *)p & 0x07;
1502 if (G_UNLIKELY (val < min))
1505 if (G_UNLIKELY (!UNICODE_VALID(val)))
1519 static const gchar *
1520 fast_validate_len (const char *str,
1528 g_assert (max_len >= 0);
1530 for (p = str; ((p - str) < max_len) && *p; p++)
1532 if (*(guchar *)p < 128)
1539 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1541 if (G_UNLIKELY (max_len - (p - str) < 2))
1544 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1547 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1552 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1554 if (G_UNLIKELY (max_len - (p - str) < 3))
1558 val = *(guchar *)p & 0x0f;
1561 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1563 if (G_UNLIKELY (max_len - (p - str) < 4))
1567 val = *(guchar *)p & 0x07;
1580 if (G_UNLIKELY (val < min))
1582 if (G_UNLIKELY (!UNICODE_VALID(val)))
1598 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1599 * @max_len: max bytes to validate, or -1 to go until NUL
1600 * @end: (allow-none) (out): return location for end of valid data
1602 * Validates UTF-8 encoded text. @str is the text to validate;
1603 * if @str is nul-terminated, then @max_len can be -1, otherwise
1604 * @max_len should be the number of bytes to validate.
1605 * If @end is non-%NULL, then the end of the valid range
1606 * will be stored there (i.e. the start of the first invalid
1607 * character if some bytes were invalid, or the end of the text
1608 * being validated otherwise).
1610 * Note that g_utf8_validate() returns %FALSE if @max_len is
1611 * positive and any of the @max_len bytes are NUL.
1613 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1614 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1615 * so data read from a file or the network should be checked
1616 * with g_utf8_validate() before doing anything else with it.
1618 * Return value: %TRUE if the text was valid UTF-8
1621 g_utf8_validate (const char *str,
1629 p = fast_validate (str);
1631 p = fast_validate_len (str, max_len);
1636 if ((max_len >= 0 && p != str + max_len) ||
1637 (max_len < 0 && *p != '\0'))
1644 * g_unichar_validate:
1645 * @ch: a Unicode character
1647 * Checks whether @ch is a valid Unicode character. Some possible
1648 * integer values of @ch will not be valid. 0 is considered a valid
1649 * character, though it's normally a string terminator.
1651 * Return value: %TRUE if @ch is a valid Unicode character
1654 g_unichar_validate (gunichar ch)
1656 return UNICODE_VALID (ch);
1660 * g_utf8_strreverse:
1661 * @str: a UTF-8 encoded string
1662 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1663 * then the string is nul-terminated.
1665 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1666 * (Use g_utf8_validate() on all text before trying to use UTF-8
1667 * utility functions with it.)
1669 * This function is intended for programmatic uses of reversed strings.
1670 * It pays no attention to decomposed characters, combining marks, byte
1671 * order marks, directional indicators (LRM, LRO, etc) and similar
1672 * characters which might need special handling when reversing a string
1673 * for display purposes.
1675 * Note that unlike g_strreverse(), this function returns
1676 * newly-allocated memory, which should be freed with g_free() when
1679 * Returns: a newly-allocated string which is the reverse of @str.
1684 g_utf8_strreverse (const gchar *str,
1693 result = g_new (gchar, len + 1);
1698 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1700 for (m = r; skip; skip--)
1710 _g_utf8_make_valid (const gchar *name)
1713 const gchar *remainder, *invalid;
1714 gint remaining_bytes, valid_bytes;
1716 g_return_val_if_fail (name != NULL, NULL);
1720 remaining_bytes = strlen (name);
1722 while (remaining_bytes != 0)
1724 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1726 valid_bytes = invalid - remainder;
1729 string = g_string_sized_new (remaining_bytes);
1731 g_string_append_len (string, remainder, valid_bytes);
1732 /* append U+FFFD REPLACEMENT CHARACTER */
1733 g_string_append (string, "\357\277\275");
1735 remaining_bytes -= valid_bytes + 1;
1736 remainder = invalid + 1;
1740 return g_strdup (name);
1742 g_string_append (string, remainder);
1744 g_assert (g_utf8_validate (string->str, -1, NULL));
1746 return g_string_free (string, FALSE);