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 * @param Char the character
110 #define UNICODE_VALID(Char) \
111 ((Char) < 0x110000 && \
112 (((Char) & 0xFFFFF800) != 0xD800))
115 static const gchar utf8_skip_data[256] = {
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 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,
122 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,
123 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
126 const gchar * const g_utf8_skip = utf8_skip_data;
129 * g_utf8_find_prev_char:
130 * @str: pointer to the beginning of a UTF-8 encoded string
131 * @p: pointer to some position within @str
133 * Given a position @p with a UTF-8 encoded string @str, find the start
134 * of the previous UTF-8 character starting before @p. Returns %NULL if no
135 * UTF-8 characters are present in @str before @p.
137 * @p does not have to be at the beginning of a UTF-8 character. No check
138 * is made to see if the character found is actually valid other than
139 * it starts with an appropriate byte.
141 * Return value: a pointer to the found character or %NULL.
144 g_utf8_find_prev_char (const char *str,
147 for (--p; p >= str; --p)
149 if ((*p & 0xc0) != 0x80)
156 * g_utf8_find_next_char:
157 * @p: a pointer to a position within a UTF-8 encoded string
158 * @end: a pointer to the byte following the end of the string,
159 * or %NULL to indicate that the string is nul-terminated.
161 * Finds the start of the next UTF-8 character in the string after @p.
163 * @p does not have to be at the beginning of a UTF-8 character. No check
164 * is made to see if the character found is actually valid other than
165 * it starts with an appropriate byte.
167 * Return value: a pointer to the found character or %NULL
170 g_utf8_find_next_char (const gchar *p,
176 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
179 for (++p; (*p & 0xc0) == 0x80; ++p)
182 return (p == end) ? NULL : (gchar *)p;
187 * @p: a pointer to a position within a UTF-8 encoded string
189 * Finds the previous UTF-8 character in the string before @p.
191 * @p does not have to be at the beginning of a UTF-8 character. No check
192 * is made to see if the character found is actually valid other than
193 * it starts with an appropriate byte. If @p might be the first
194 * character of the string, you must use g_utf8_find_prev_char() instead.
196 * Return value: a pointer to the found character.
199 g_utf8_prev_char (const gchar *p)
204 if ((*p & 0xc0) != 0x80)
211 * @p: pointer to the start of a UTF-8 encoded string
212 * @max: the maximum number of bytes to examine. If @max
213 * is less than 0, then the string is assumed to be
214 * nul-terminated. If @max is 0, @p will not be examined and
215 * may be %NULL. If @max is greater than 0, up to @max
218 * Computes the length of the string in characters, not including
219 * the terminating nul character. If the @max'th byte falls in the
220 * middle of a character, the last (partial) character is not counted.
222 * Return value: the length of the string in characters
225 g_utf8_strlen (const gchar *p,
229 const gchar *start = p;
230 g_return_val_if_fail (p != NULL || max == 0, 0);
236 p = g_utf8_next_char (p);
245 p = g_utf8_next_char (p);
247 while (p - start < max && *p)
250 p = g_utf8_next_char (p);
253 /* only do the last len increment if we got a complete
254 * char (don't count partial chars)
256 if (p - start <= max)
265 * @str: a UTF-8 encoded string
266 * @start_pos: a character offset within @str
267 * @end_pos: another character offset within @str
269 * Copies a substring out of a UTF-8 encoded string.
270 * The substring will contain @end_pos - @start_pos
273 * Returns: a newly allocated copy of the requested
274 * substring. Free with g_free() when no longer needed.
279 g_utf8_substring (const gchar *str,
283 gchar *start, *end, *out;
285 start = g_utf8_offset_to_pointer (str, start_pos);
286 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
288 out = g_malloc (end - start + 1);
289 memcpy (out, start, end - start);
290 out[end - start] = 0;
297 * @p: a pointer to Unicode character encoded as UTF-8
299 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
300 * If @p does not point to a valid UTF-8 encoded character, results are
301 * undefined. If you are not sure that the bytes are complete
302 * valid Unicode characters, you should use g_utf8_get_char_validated()
305 * Return value: the resulting character
308 g_utf8_get_char (const gchar *p)
310 int i, mask = 0, len;
312 unsigned char c = (unsigned char) *p;
314 UTF8_COMPUTE (c, mask, len);
317 UTF8_GET (result, p, i, mask, len);
323 * g_utf8_offset_to_pointer:
324 * @str: a UTF-8 encoded string
325 * @offset: a character offset within @str
327 * Converts from an integer character offset to a pointer to a position
330 * Since 2.10, this function allows to pass a negative @offset to
331 * step backwards. It is usually worth stepping backwards from the end
332 * instead of forwards if @offset is in the last fourth of the string,
333 * since moving forward is about 3 times faster than moving backward.
336 * This function doesn't abort when reaching the end of @str. Therefore
337 * you should be sure that @offset is within string boundaries before
338 * calling that function. Call g_utf8_strlen() when unsure.
340 * This limitation exists as this function is called frequently during
341 * text rendering and therefore has to be as fast as possible.
344 * Return value: the resulting pointer
347 g_utf8_offset_to_pointer (const gchar *str,
350 const gchar *s = str;
354 s = g_utf8_next_char (s);
359 /* This nice technique for fast backwards stepping
360 * through a UTF-8 string was dubbed "stutter stepping"
361 * by its inventor, Larry Ewing.
367 while ((*s & 0xc0) == 0x80)
370 offset += g_utf8_pointer_to_offset (s, s1);
378 * g_utf8_pointer_to_offset:
379 * @str: a UTF-8 encoded string
380 * @pos: a pointer to a position within @str
382 * Converts from a pointer to position within a string to a integer
385 * Since 2.10, this function allows @pos to be before @str, and returns
386 * a negative offset in this case.
388 * Return value: the resulting character offset
391 g_utf8_pointer_to_offset (const gchar *str,
394 const gchar *s = str;
398 offset = - g_utf8_pointer_to_offset (pos, str);
402 s = g_utf8_next_char (s);
412 * @dest: buffer to fill with characters from @src
413 * @src: UTF-8 encoded string
414 * @n: character count
416 * Like the standard C strncpy() function, but
417 * copies a given number of characters instead of a given number of
418 * bytes. The @src string must be valid UTF-8 encoded text.
419 * (Use g_utf8_validate() on all text before trying to use UTF-8
420 * utility functions with it.)
422 * Return value: @dest
425 g_utf8_strncpy (gchar *dest,
429 const gchar *s = src;
432 s = g_utf8_next_char(s);
435 strncpy(dest, src, s - src);
444 * @c: a Unicode character code
445 * @outbuf: output buffer, must have at least 6 bytes of space.
446 * If %NULL, the length will be computed and returned
447 * and nothing will be written to @outbuf.
449 * Converts a single character to UTF-8.
451 * Return value: number of bytes written
454 g_unichar_to_utf8 (gunichar c,
457 /* If this gets modified, also update the copy in g_string_insert_unichar() */
472 else if (c < 0x10000)
477 else if (c < 0x200000)
482 else if (c < 0x4000000)
495 for (i = len - 1; i > 0; --i)
497 outbuf[i] = (c & 0x3f) | 0x80;
500 outbuf[0] = c | first;
508 * @p: a nul-terminated UTF-8 encoded string
509 * @len: the maximum length of @p
510 * @c: a Unicode character
512 * Finds the leftmost occurrence of the given Unicode character
513 * in a UTF-8 encoded string, while limiting the search to @len bytes.
514 * If @len is -1, allow unbounded search.
516 * Return value: %NULL if the string does not contain the character,
517 * otherwise, a pointer to the start of the leftmost occurrence of
518 * the character in the string.
521 g_utf8_strchr (const char *p,
527 gint charlen = g_unichar_to_utf8 (c, ch);
530 return g_strstr_len (p, len, ch);
536 * @p: a nul-terminated UTF-8 encoded string
537 * @len: the maximum length of @p
538 * @c: a Unicode character
540 * Find the rightmost occurrence of the given Unicode character
541 * in a UTF-8 encoded string, while limiting the search to @len bytes.
542 * If @len is -1, allow unbounded search.
544 * Return value: %NULL if the string does not contain the character,
545 * otherwise, a pointer to the start of the rightmost occurrence of the
546 * character in the string.
549 g_utf8_strrchr (const char *p,
555 gint charlen = g_unichar_to_utf8 (c, ch);
558 return g_strrstr_len (p, len, ch);
562 /* Like g_utf8_get_char, but take a maximum length
563 * and return (gunichar)-2 on incomplete trailing character;
564 * also check for malformed or overlong sequences
565 * and return (gunichar)-1 in this case.
567 static inline gunichar
568 g_utf8_get_char_extended (const gchar *p,
573 gunichar wc = (guchar) *p;
579 else if (G_UNLIKELY (wc < 0xc0))
618 if (G_UNLIKELY (max_len >= 0 && len > max_len))
620 for (i = 1; i < max_len; i++)
622 if ((((guchar *)p)[i] & 0xc0) != 0x80)
628 for (i = 1; i < len; ++i)
630 gunichar ch = ((guchar *)p)[i];
632 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
644 if (G_UNLIKELY (wc < min_code))
651 * g_utf8_get_char_validated:
652 * @p: a pointer to Unicode character encoded as UTF-8
653 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
654 * if @p is nul-terminated
656 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
657 * This function checks for incomplete characters, for invalid characters
658 * such as characters that are out of the range of Unicode, and for
659 * overlong encodings of valid characters.
661 * Return value: the resulting character. If @p points to a partial
662 * sequence at the end of a string that could begin a valid
663 * character (or if @max_len is zero), returns (gunichar)-2;
664 * otherwise, if @p does not point to a valid UTF-8 encoded
665 * Unicode character, returns (gunichar)-1.
668 g_utf8_get_char_validated (const gchar *p,
676 result = g_utf8_get_char_extended (p, max_len);
678 if (result & 0x80000000)
680 else if (!UNICODE_VALID (result))
687 * g_utf8_to_ucs4_fast:
688 * @str: a UTF-8 encoded string
689 * @len: the maximum length of @str to use, in bytes. If @len < 0,
690 * then the string is nul-terminated.
691 * @items_written: (allow-none): location to store the number of characters in the
694 * Convert a string from UTF-8 to a 32-bit fixed width
695 * representation as UCS-4, assuming valid UTF-8 input.
696 * This function is roughly twice as fast as g_utf8_to_ucs4()
697 * but does no error checking on the input. A trailing 0 character
698 * will be added to the string after the converted text.
700 * Return value: a pointer to a newly allocated UCS-4 string.
701 * This value must be freed with g_free().
704 g_utf8_to_ucs4_fast (const gchar *str,
706 glong *items_written)
712 g_return_val_if_fail (str != NULL, NULL);
720 p = g_utf8_next_char (p);
726 while (p < str + len && *p)
728 p = g_utf8_next_char (p);
733 result = g_new (gunichar, n_chars + 1);
736 for (i=0; i < n_chars; i++)
738 gunichar wc = (guchar)*p++;
746 gunichar mask = 0x40;
748 if (G_UNLIKELY ((wc & mask) == 0))
750 /* It's an out-of-sequence 10xxxxxxx byte.
751 * Rather than making an ugly hash of this and the next byte
752 * and overrunning the buffer, it's more useful to treat it
753 * with a replacement character */
761 wc |= (guchar)(*p++) & 0x3f;
764 while((wc & mask) != 0);
780 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
782 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
784 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
785 _("Failed to allocate memory"));
791 * @str: a UTF-8 encoded string
792 * @len: the maximum length of @str to use, in bytes. If @len < 0,
793 * then the string is nul-terminated.
794 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
795 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
796 * returned in case @str contains a trailing partial
797 * character. If an error occurs then the index of the
798 * invalid input is stored here.
799 * @items_written: (allow-none): location to store number of characters written or %NULL.
800 * The value here stored does not include the trailing 0
802 * @error: location to store the error occurring, or %NULL to ignore
803 * errors. Any of the errors in #GConvertError other than
804 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
806 * Convert a string from UTF-8 to a 32-bit fixed width
807 * representation as UCS-4. A trailing 0 character will be added to the
808 * string after the converted text.
810 * Return value: a pointer to a newly allocated UCS-4 string.
811 * This value must be freed with g_free(). If an
812 * error occurs, %NULL will be returned and
816 g_utf8_to_ucs4 (const gchar *str,
819 glong *items_written,
822 gunichar *result = NULL;
828 while ((len < 0 || str + len - in > 0) && *in)
830 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
833 if (wc == (gunichar)-2)
838 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
839 _("Partial character sequence at end of input"));
842 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
843 _("Invalid byte sequence in conversion input"));
850 in = g_utf8_next_char (in);
853 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
858 for (i=0; i < n_chars; i++)
860 result[i] = g_utf8_get_char (in);
861 in = g_utf8_next_char (in);
866 *items_written = n_chars;
870 *items_read = in - str;
877 * @str: a UCS-4 encoded string
878 * @len: the maximum length (number of characters) of @str to use.
879 * If @len < 0, then the string is nul-terminated.
880 * @items_read: (allow-none): location to store number of characters read, or %NULL.
881 * @items_written: (allow-none): location to store number of bytes written or %NULL.
882 * The value here stored does not include the trailing 0
884 * @error: location to store the error occurring, or %NULL to ignore
885 * errors. Any of the errors in #GConvertError other than
886 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
888 * Convert a string from a 32-bit fixed width representation as UCS-4.
889 * to UTF-8. The result will be terminated with a 0 byte.
891 * Return value: a pointer to a newly allocated UTF-8 string.
892 * This value must be freed with g_free(). If an
893 * error occurs, %NULL will be returned and
894 * @error set. In that case, @items_read will be
895 * set to the position of the first invalid input
899 g_ucs4_to_utf8 (const gunichar *str,
902 glong *items_written,
906 gchar *result = NULL;
911 for (i = 0; len < 0 || i < len ; i++)
916 if (str[i] >= 0x80000000)
918 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
919 _("Character out of range for UTF-8"));
923 result_length += UTF8_LENGTH (str[i]);
926 result = try_malloc_n (result_length + 1, 1, error);
933 while (p < result + result_length)
934 p += g_unichar_to_utf8 (str[i++], p);
939 *items_written = p - result;
948 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
952 * @str: a UTF-16 encoded string
953 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
954 * If @len < 0, then the string is nul-terminated.
955 * @items_read: (allow-none): location to store number of words read, or %NULL.
956 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
957 * returned in case @str contains a trailing partial
958 * character. If an error occurs then the index of the
959 * invalid input is stored here.
960 * @items_written: (allow-none): location to store number of bytes written, or %NULL.
961 * The value stored here does not include the trailing
963 * @error: location to store the error occurring, or %NULL to ignore
964 * errors. Any of the errors in #GConvertError other than
965 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
967 * Convert a string from UTF-16 to UTF-8. The result will be
968 * terminated with a 0 byte.
970 * Note that the input is expected to be already in native endianness,
971 * an initial byte-order-mark character is not handled specially.
972 * g_convert() can be used to convert a byte buffer of UTF-16 data of
973 * ambiguous endianess.
975 * Further note that this function does not validate the result
976 * string; it may e.g. include embedded NUL characters. The only
977 * validation done by this function is to ensure that the input can
978 * be correctly interpreted as UTF-16, i.e. it doesn't contain
979 * things unpaired surrogates.
981 * Return value: a pointer to a newly allocated UTF-8 string.
982 * This value must be freed with g_free(). If an
983 * error occurs, %NULL will be returned and
987 g_utf16_to_utf8 (const gunichar2 *str,
990 glong *items_written,
993 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
998 gchar *result = NULL;
1000 gunichar high_surrogate;
1002 g_return_val_if_fail (str != NULL, NULL);
1007 while ((len < 0 || in - str < len) && *in)
1012 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1016 wc = SURROGATE_VALUE (high_surrogate, c);
1021 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1022 _("Invalid sequence in conversion input"));
1030 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1031 _("Invalid sequence in conversion input"));
1035 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1044 /********** DIFFERENT for UTF8/UCS4 **********/
1045 n_bytes += UTF8_LENGTH (wc);
1051 if (high_surrogate && !items_read)
1053 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1054 _("Partial character sequence at end of input"));
1058 /* At this point, everything is valid, and we just need to convert
1060 /********** DIFFERENT for UTF8/UCS4 **********/
1061 result = try_malloc_n (n_bytes + 1, 1, error);
1068 while (out < result + n_bytes)
1073 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1075 wc = SURROGATE_VALUE (high_surrogate, c);
1078 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1086 /********** DIFFERENT for UTF8/UCS4 **********/
1087 out += g_unichar_to_utf8 (wc, out);
1093 /********** DIFFERENT for UTF8/UCS4 **********/
1097 /********** DIFFERENT for UTF8/UCS4 **********/
1098 *items_written = out - result;
1102 *items_read = in - str;
1109 * @str: a UTF-16 encoded string
1110 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1111 * If @len < 0, then the string is nul-terminated.
1112 * @items_read: (allow-none): location to store number of words read, or %NULL.
1113 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1114 * returned in case @str contains a trailing partial
1115 * character. If an error occurs then the index of the
1116 * invalid input is stored here.
1117 * @items_written: (allow-none): location to store number of characters written, or %NULL.
1118 * The value stored here does not include the trailing
1120 * @error: location to store the error occurring, or %NULL to ignore
1121 * errors. Any of the errors in #GConvertError other than
1122 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1124 * Convert a string from UTF-16 to UCS-4. The result will be
1127 * Return value: a pointer to a newly allocated UCS-4 string.
1128 * This value must be freed with g_free(). If an
1129 * error occurs, %NULL will be returned and
1133 g_utf16_to_ucs4 (const gunichar2 *str,
1136 glong *items_written,
1139 const gunichar2 *in;
1141 gchar *result = NULL;
1143 gunichar high_surrogate;
1145 g_return_val_if_fail (str != NULL, NULL);
1150 while ((len < 0 || in - str < len) && *in)
1154 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1162 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163 _("Invalid sequence in conversion input"));
1171 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1172 _("Invalid sequence in conversion input"));
1176 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1183 /********** DIFFERENT for UTF8/UCS4 **********/
1184 n_bytes += sizeof (gunichar);
1190 if (high_surrogate && !items_read)
1192 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1193 _("Partial character sequence at end of input"));
1197 /* At this point, everything is valid, and we just need to convert
1199 /********** DIFFERENT for UTF8/UCS4 **********/
1200 result = try_malloc_n (n_bytes + 4, 1, error);
1207 while (out < result + n_bytes)
1212 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1214 wc = SURROGATE_VALUE (high_surrogate, c);
1217 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1225 /********** DIFFERENT for UTF8/UCS4 **********/
1226 *(gunichar *)out = wc;
1227 out += sizeof (gunichar);
1233 /********** DIFFERENT for UTF8/UCS4 **********/
1234 *(gunichar *)out = 0;
1237 /********** DIFFERENT for UTF8/UCS4 **********/
1238 *items_written = (out - result) / sizeof (gunichar);
1242 *items_read = in - str;
1244 return (gunichar *)result;
1249 * @str: a UTF-8 encoded string
1250 * @len: the maximum length (number of bytes) of @str to use.
1251 * If @len < 0, then the string is nul-terminated.
1252 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
1253 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1254 * returned in case @str contains a trailing partial
1255 * character. If an error occurs then the index of the
1256 * invalid input is stored here.
1257 * @items_written: (allow-none): location to store number of <type>gunichar2</type> written,
1259 * The value stored here does not include the trailing 0.
1260 * @error: location to store the error occurring, or %NULL to ignore
1261 * errors. Any of the errors in #GConvertError other than
1262 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1264 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1265 * added to the result after the converted text.
1267 * Return value: a pointer to a newly allocated UTF-16 string.
1268 * This value must be freed with g_free(). If an
1269 * error occurs, %NULL will be returned and
1273 g_utf8_to_utf16 (const gchar *str,
1276 glong *items_written,
1279 gunichar2 *result = NULL;
1284 g_return_val_if_fail (str != NULL, NULL);
1288 while ((len < 0 || str + len - in > 0) && *in)
1290 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1291 if (wc & 0x80000000)
1293 if (wc == (gunichar)-2)
1298 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1299 _("Partial character sequence at end of input"));
1302 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1303 _("Invalid byte sequence in conversion input"));
1310 else if (wc < 0xe000)
1312 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1313 _("Invalid sequence in conversion input"));
1317 else if (wc < 0x10000)
1319 else if (wc < 0x110000)
1323 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1324 _("Character out of range for UTF-16"));
1329 in = g_utf8_next_char (in);
1332 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1337 for (i = 0; i < n16;)
1339 gunichar wc = g_utf8_get_char (in);
1347 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1348 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1351 in = g_utf8_next_char (in);
1357 *items_written = n16;
1361 *items_read = in - str;
1368 * @str: a UCS-4 encoded string
1369 * @len: the maximum length (number of characters) of @str to use.
1370 * If @len < 0, then the string is nul-terminated.
1371 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
1372 * If an error occurs then the index of the invalid input
1374 * @items_written: (allow-none): location to store number of <type>gunichar2</type>
1375 * written, or %NULL. The value stored here does not
1376 * include the trailing 0.
1377 * @error: location to store the error occurring, or %NULL to ignore
1378 * errors. Any of the errors in #GConvertError other than
1379 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1381 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1382 * added to the result after the converted text.
1384 * Return value: a pointer to a newly allocated UTF-16 string.
1385 * This value must be freed with g_free(). If an
1386 * error occurs, %NULL will be returned and
1390 g_ucs4_to_utf16 (const gunichar *str,
1393 glong *items_written,
1396 gunichar2 *result = NULL;
1402 while ((len < 0 || i < len) && str[i])
1404 gunichar wc = str[i];
1408 else if (wc < 0xe000)
1410 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1411 _("Invalid sequence in conversion input"));
1415 else if (wc < 0x10000)
1417 else if (wc < 0x110000)
1421 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1422 _("Character out of range for UTF-16"));
1430 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1434 for (i = 0, j = 0; j < n16; i++)
1436 gunichar wc = str[i];
1444 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1445 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1451 *items_written = n16;
1460 #define CONTINUATION_CHAR \
1462 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1465 val |= (*(guchar *)p) & 0x3f; \
1468 static const gchar *
1469 fast_validate (const char *str)
1476 for (p = str; *p; p++)
1478 if (*(guchar *)p < 128)
1485 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1487 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1490 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1495 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1498 val = *(guchar *)p & 0x0f;
1501 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1504 val = *(guchar *)p & 0x07;
1517 if (G_UNLIKELY (val < min))
1520 if (G_UNLIKELY (!UNICODE_VALID(val)))
1534 static const gchar *
1535 fast_validate_len (const char *str,
1543 g_assert (max_len >= 0);
1545 for (p = str; ((p - str) < max_len) && *p; p++)
1547 if (*(guchar *)p < 128)
1554 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1556 if (G_UNLIKELY (max_len - (p - str) < 2))
1559 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1562 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1567 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1569 if (G_UNLIKELY (max_len - (p - str) < 3))
1573 val = *(guchar *)p & 0x0f;
1576 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1578 if (G_UNLIKELY (max_len - (p - str) < 4))
1582 val = *(guchar *)p & 0x07;
1595 if (G_UNLIKELY (val < min))
1597 if (G_UNLIKELY (!UNICODE_VALID(val)))
1613 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1614 * @max_len: max bytes to validate, or -1 to go until NUL
1615 * @end: (allow-none) (out) (transfer none): return location for end of valid data
1617 * Validates UTF-8 encoded text. @str is the text to validate;
1618 * if @str is nul-terminated, then @max_len can be -1, otherwise
1619 * @max_len should be the number of bytes to validate.
1620 * If @end is non-%NULL, then the end of the valid range
1621 * will be stored there (i.e. the start of the first invalid
1622 * character if some bytes were invalid, or the end of the text
1623 * being validated otherwise).
1625 * Note that g_utf8_validate() returns %FALSE if @max_len is
1626 * positive and any of the @max_len bytes are NUL.
1628 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1629 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1630 * so data read from a file or the network should be checked
1631 * with g_utf8_validate() before doing anything else with it.
1633 * Return value: %TRUE if the text was valid UTF-8
1636 g_utf8_validate (const char *str,
1644 p = fast_validate (str);
1646 p = fast_validate_len (str, max_len);
1651 if ((max_len >= 0 && p != str + max_len) ||
1652 (max_len < 0 && *p != '\0'))
1659 * g_unichar_validate:
1660 * @ch: a Unicode character
1662 * Checks whether @ch is a valid Unicode character. Some possible
1663 * integer values of @ch will not be valid. 0 is considered a valid
1664 * character, though it's normally a string terminator.
1666 * Return value: %TRUE if @ch is a valid Unicode character
1669 g_unichar_validate (gunichar ch)
1671 return UNICODE_VALID (ch);
1675 * g_utf8_strreverse:
1676 * @str: a UTF-8 encoded string
1677 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1678 * then the string is nul-terminated.
1680 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1681 * (Use g_utf8_validate() on all text before trying to use UTF-8
1682 * utility functions with it.)
1684 * This function is intended for programmatic uses of reversed strings.
1685 * It pays no attention to decomposed characters, combining marks, byte
1686 * order marks, directional indicators (LRM, LRO, etc) and similar
1687 * characters which might need special handling when reversing a string
1688 * for display purposes.
1690 * Note that unlike g_strreverse(), this function returns
1691 * newly-allocated memory, which should be freed with g_free() when
1694 * Returns: a newly-allocated string which is the reverse of @str.
1699 g_utf8_strreverse (const gchar *str,
1708 result = g_new (gchar, len + 1);
1713 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1715 for (m = r; skip; skip--)
1725 _g_utf8_make_valid (const gchar *name)
1728 const gchar *remainder, *invalid;
1729 gint remaining_bytes, valid_bytes;
1731 g_return_val_if_fail (name != NULL, NULL);
1735 remaining_bytes = strlen (name);
1737 while (remaining_bytes != 0)
1739 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1741 valid_bytes = invalid - remainder;
1744 string = g_string_sized_new (remaining_bytes);
1746 g_string_append_len (string, remainder, valid_bytes);
1747 /* append U+FFFD REPLACEMENT CHARACTER */
1748 g_string_append (string, "\357\277\275");
1750 remaining_bytes -= valid_bytes + 1;
1751 remainder = invalid + 1;
1755 return g_strdup (name);
1757 g_string_append (string, remainder);
1759 g_assert (g_utf8_validate (string->str, -1, NULL));
1761 return g_string_free (string, FALSE);