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, see <http://www.gnu.org/licenses/>.
28 #ifdef G_PLATFORM_WIN32
37 #include "gstrfuncs.h"
38 #include "gtestutils.h"
43 #define UTF8_COMPUTE(Char, Mask, Len) \
49 else if ((Char & 0xe0) == 0xc0) \
54 else if ((Char & 0xf0) == 0xe0) \
59 else if ((Char & 0xf8) == 0xf0) \
64 else if ((Char & 0xfc) == 0xf8) \
69 else if ((Char & 0xfe) == 0xfc) \
77 #define UTF8_LENGTH(Char) \
78 ((Char) < 0x80 ? 1 : \
79 ((Char) < 0x800 ? 2 : \
80 ((Char) < 0x10000 ? 3 : \
81 ((Char) < 0x200000 ? 4 : \
82 ((Char) < 0x4000000 ? 5 : 6)))))
85 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
86 (Result) = (Chars)[0] & (Mask); \
87 for ((Count) = 1; (Count) < (Len); ++(Count)) \
89 if (((Chars)[(Count)] & 0xc0) != 0x80) \
95 (Result) |= ((Chars)[(Count)] & 0x3f); \
99 * Check whether a Unicode (5.2) char is in a valid range.
101 * The first check comes from the Unicode guarantee to never encode
102 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
104 * The second check covers surrogate pairs (category Cs).
106 * @param Char the character
108 #define UNICODE_VALID(Char) \
109 ((Char) < 0x110000 && \
110 (((Char) & 0xFFFFF800) != 0xD800))
113 static const gchar utf8_skip_data[256] = {
114 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
115 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
116 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
117 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
118 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
119 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
120 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
121 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
124 const gchar * const g_utf8_skip = utf8_skip_data;
127 * g_utf8_find_prev_char:
128 * @str: pointer to the beginning of a UTF-8 encoded string
129 * @p: pointer to some position within @str
131 * Given a position @p with a UTF-8 encoded string @str, find the start
132 * of the previous UTF-8 character starting before @p. Returns %NULL if no
133 * UTF-8 characters are present in @str before @p.
135 * @p does not have to be at the beginning of a UTF-8 character. No check
136 * is made to see if the character found is actually valid other than
137 * it starts with an appropriate byte.
139 * Returns: a pointer to the found character or %NULL.
142 g_utf8_find_prev_char (const char *str,
145 for (--p; p >= str; --p)
147 if ((*p & 0xc0) != 0x80)
154 * g_utf8_find_next_char:
155 * @p: a pointer to a position within a UTF-8 encoded string
156 * @end: a pointer to the byte following the end of the string,
157 * or %NULL to indicate that the string is nul-terminated
159 * Finds the start of the next UTF-8 character in the string after @p.
161 * @p does not have to be at the beginning of a UTF-8 character. No check
162 * is made to see if the character found is actually valid other than
163 * it starts with an appropriate byte.
165 * Returns: a pointer to the found character or %NULL
168 g_utf8_find_next_char (const gchar *p,
174 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
177 for (++p; (*p & 0xc0) == 0x80; ++p)
180 return (p == end) ? NULL : (gchar *)p;
185 * @p: a pointer to a position within a UTF-8 encoded string
187 * Finds the previous UTF-8 character in the string before @p.
189 * @p does not have to be at the beginning of a UTF-8 character. No check
190 * is made to see if the character found is actually valid other than
191 * it starts with an appropriate byte. If @p might be the first
192 * character of the string, you must use g_utf8_find_prev_char() instead.
194 * Returns: a pointer to the found character
197 g_utf8_prev_char (const gchar *p)
202 if ((*p & 0xc0) != 0x80)
209 * @p: pointer to the start of a UTF-8 encoded string
210 * @max: the maximum number of bytes to examine. If @max
211 * is less than 0, then the string is assumed to be
212 * nul-terminated. If @max is 0, @p will not be examined and
213 * may be %NULL. If @max is greater than 0, up to @max
216 * Computes the length of the string in characters, not including
217 * the terminating nul character. If the @max'th byte falls in the
218 * middle of a character, the last (partial) character is not counted.
220 * Returns: the length of the string in characters
223 g_utf8_strlen (const gchar *p,
227 const gchar *start = p;
228 g_return_val_if_fail (p != NULL || max == 0, 0);
234 p = g_utf8_next_char (p);
243 p = g_utf8_next_char (p);
245 while (p - start < max && *p)
248 p = g_utf8_next_char (p);
251 /* only do the last len increment if we got a complete
252 * char (don't count partial chars)
254 if (p - start <= max)
263 * @str: a UTF-8 encoded string
264 * @start_pos: a character offset within @str
265 * @end_pos: another character offset within @str
267 * Copies a substring out of a UTF-8 encoded string.
268 * The substring will contain @end_pos - @start_pos characters.
270 * Returns: a newly allocated copy of the requested
271 * substring. Free with g_free() when no longer needed.
276 g_utf8_substring (const gchar *str,
280 gchar *start, *end, *out;
282 start = g_utf8_offset_to_pointer (str, start_pos);
283 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
285 out = g_malloc (end - start + 1);
286 memcpy (out, start, end - start);
287 out[end - start] = 0;
294 * @p: a pointer to Unicode character encoded as UTF-8
296 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
298 * If @p does not point to a valid UTF-8 encoded character, results
299 * are undefined. If you are not sure that the bytes are complete
300 * valid Unicode characters, you should use g_utf8_get_char_validated()
303 * Returns: the resulting character
306 g_utf8_get_char (const gchar *p)
308 int i, mask = 0, len;
310 unsigned char c = (unsigned char) *p;
312 UTF8_COMPUTE (c, mask, len);
315 UTF8_GET (result, p, i, mask, len);
321 * g_utf8_offset_to_pointer:
322 * @str: a UTF-8 encoded string
323 * @offset: a character offset within @str
325 * Converts from an integer character offset to a pointer to a position
328 * Since 2.10, this function allows to pass a negative @offset to
329 * step backwards. It is usually worth stepping backwards from the end
330 * instead of forwards if @offset is in the last fourth of the string,
331 * since moving forward is about 3 times faster than moving backward.
333 * Note that this function doesn't abort when reaching the end of @str.
334 * Therefore you should be sure that @offset is within string boundaries
335 * before calling that function. Call g_utf8_strlen() when unsure.
336 * This limitation exists as this function is called frequently during
337 * text rendering and therefore has to be as fast as possible.
339 * Returns: the resulting pointer
342 g_utf8_offset_to_pointer (const gchar *str,
345 const gchar *s = str;
349 s = g_utf8_next_char (s);
354 /* This nice technique for fast backwards stepping
355 * through a UTF-8 string was dubbed "stutter stepping"
356 * by its inventor, Larry Ewing.
362 while ((*s & 0xc0) == 0x80)
365 offset += g_utf8_pointer_to_offset (s, s1);
373 * g_utf8_pointer_to_offset:
374 * @str: a UTF-8 encoded string
375 * @pos: a pointer to a position within @str
377 * Converts from a pointer to position within a string to a integer
380 * Since 2.10, this function allows @pos to be before @str, and returns
381 * a negative offset in this case.
383 * Returns: the resulting character offset
386 g_utf8_pointer_to_offset (const gchar *str,
389 const gchar *s = str;
393 offset = - g_utf8_pointer_to_offset (pos, str);
397 s = g_utf8_next_char (s);
407 * @dest: buffer to fill with characters from @src
408 * @src: UTF-8 encoded string
409 * @n: character count
411 * Like the standard C strncpy() function, but copies a given number
412 * of characters instead of a given number of bytes. The @src string
413 * must be valid UTF-8 encoded text. (Use g_utf8_validate() on all
414 * text before trying to use UTF-8 utility functions with it.)
419 g_utf8_strncpy (gchar *dest,
423 const gchar *s = src;
426 s = g_utf8_next_char(s);
429 strncpy(dest, src, s - src);
438 * @c: a Unicode character code
439 * @outbuf: output buffer, must have at least 6 bytes of space.
440 * If %NULL, the length will be computed and returned
441 * and nothing will be written to @outbuf.
443 * Converts a single character to UTF-8.
445 * Returns: number of bytes written
448 g_unichar_to_utf8 (gunichar c,
451 /* If this gets modified, also update the copy in g_string_insert_unichar() */
466 else if (c < 0x10000)
471 else if (c < 0x200000)
476 else if (c < 0x4000000)
489 for (i = len - 1; i > 0; --i)
491 outbuf[i] = (c & 0x3f) | 0x80;
494 outbuf[0] = c | first;
502 * @p: a nul-terminated UTF-8 encoded string
503 * @len: the maximum length of @p
504 * @c: a Unicode character
506 * Finds the leftmost occurrence of the given Unicode character
507 * in a UTF-8 encoded string, while limiting the search to @len bytes.
508 * If @len is -1, allow unbounded search.
510 * Returns: %NULL if the string does not contain the character,
511 * otherwise, a pointer to the start of the leftmost occurrence
512 * of the character in the string.
515 g_utf8_strchr (const char *p,
521 gint charlen = g_unichar_to_utf8 (c, ch);
524 return g_strstr_len (p, len, ch);
530 * @p: a nul-terminated UTF-8 encoded string
531 * @len: the maximum length of @p
532 * @c: a Unicode character
534 * Find the rightmost occurrence of the given Unicode character
535 * in a UTF-8 encoded string, while limiting the search to @len bytes.
536 * If @len is -1, allow unbounded search.
538 * Returns: %NULL if the string does not contain the character,
539 * otherwise, a pointer to the start of the rightmost occurrence
540 * of the character in the string.
543 g_utf8_strrchr (const char *p,
549 gint charlen = g_unichar_to_utf8 (c, ch);
552 return g_strrstr_len (p, len, ch);
556 /* Like g_utf8_get_char, but take a maximum length
557 * and return (gunichar)-2 on incomplete trailing character;
558 * also check for malformed or overlong sequences
559 * and return (gunichar)-1 in this case.
561 static inline gunichar
562 g_utf8_get_char_extended (const gchar *p,
567 gunichar wc = (guchar) *p;
573 else if (G_UNLIKELY (wc < 0xc0))
612 if (G_UNLIKELY (max_len >= 0 && len > max_len))
614 for (i = 1; i < max_len; i++)
616 if ((((guchar *)p)[i] & 0xc0) != 0x80)
622 for (i = 1; i < len; ++i)
624 gunichar ch = ((guchar *)p)[i];
626 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
638 if (G_UNLIKELY (wc < min_code))
645 * g_utf8_get_char_validated:
646 * @p: a pointer to Unicode character encoded as UTF-8
647 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
648 * if @p is nul-terminated
650 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
651 * This function checks for incomplete characters, for invalid characters
652 * such as characters that are out of the range of Unicode, and for
653 * overlong encodings of valid characters.
655 * Returns: the resulting character. If @p points to a partial
656 * sequence at the end of a string that could begin a valid
657 * character (or if @max_len is zero), returns (gunichar)-2;
658 * otherwise, if @p does not point to a valid UTF-8 encoded
659 * Unicode character, returns (gunichar)-1.
662 g_utf8_get_char_validated (const gchar *p,
670 result = g_utf8_get_char_extended (p, max_len);
672 if (result & 0x80000000)
674 else if (!UNICODE_VALID (result))
681 * g_utf8_to_ucs4_fast:
682 * @str: a UTF-8 encoded string
683 * @len: the maximum length of @str to use, in bytes. If @len < 0,
684 * then the string is nul-terminated.
685 * @items_written: (allow-none): location to store the number of
686 * characters in the result, or %NULL.
688 * Convert a string from UTF-8 to a 32-bit fixed width
689 * representation as UCS-4, assuming valid UTF-8 input.
690 * This function is roughly twice as fast as g_utf8_to_ucs4()
691 * but does no error checking on the input. A trailing 0 character
692 * will be added to the string after the converted text.
694 * Returns: a pointer to a newly allocated UCS-4 string.
695 * This value must be freed with g_free().
698 g_utf8_to_ucs4_fast (const gchar *str,
700 glong *items_written)
706 g_return_val_if_fail (str != NULL, NULL);
714 p = g_utf8_next_char (p);
720 while (p < str + len && *p)
722 p = g_utf8_next_char (p);
727 result = g_new (gunichar, n_chars + 1);
730 for (i=0; i < n_chars; i++)
732 gunichar wc = (guchar)*p++;
740 gunichar mask = 0x40;
742 if (G_UNLIKELY ((wc & mask) == 0))
744 /* It's an out-of-sequence 10xxxxxxx byte.
745 * Rather than making an ugly hash of this and the next byte
746 * and overrunning the buffer, it's more useful to treat it
747 * with a replacement character
756 wc |= (guchar)(*p++) & 0x3f;
759 while((wc & mask) != 0);
775 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
777 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
779 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
780 _("Failed to allocate memory"));
786 * @str: a UTF-8 encoded string
787 * @len: the maximum length of @str to use, in bytes. If @len < 0,
788 * then the string is nul-terminated.
789 * @items_read: (allow-none): location to store number of bytes read, or %NULL.
790 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
791 * returned in case @str contains a trailing partial
792 * character. If an error occurs then the index of the
793 * invalid input is stored here.
794 * @items_written: (allow-none): location to store number of characters
795 * written or %NULL. The value here stored does not include the
796 * trailing 0 character.
797 * @error: location to store the error occurring, or %NULL to ignore
798 * errors. Any of the errors in #GConvertError other than
799 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
801 * Convert a string from UTF-8 to a 32-bit fixed width
802 * representation as UCS-4. A trailing 0 character will be added to the
803 * string after the converted text.
805 * Returns: a pointer to a newly allocated UCS-4 string.
806 * This value must be freed with g_free(). If an error occurs,
807 * %NULL will be returned and @error set.
810 g_utf8_to_ucs4 (const gchar *str,
813 glong *items_written,
816 gunichar *result = NULL;
822 while ((len < 0 || str + len - in > 0) && *in)
824 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
827 if (wc == (gunichar)-2)
832 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
833 _("Partial character sequence at end of input"));
836 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
837 _("Invalid byte sequence in conversion input"));
844 in = g_utf8_next_char (in);
847 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
852 for (i=0; i < n_chars; i++)
854 result[i] = g_utf8_get_char (in);
855 in = g_utf8_next_char (in);
860 *items_written = n_chars;
864 *items_read = in - str;
871 * @str: a UCS-4 encoded string
872 * @len: the maximum length (number of characters) of @str to use.
873 * If @len < 0, then the string is nul-terminated.
874 * @items_read: (allow-none): location to store number of characters
876 * @items_written: (allow-none): location to store number of bytes
877 * written or %NULL. The value here stored does not include the
879 * @error: location to store the error occurring, or %NULL to ignore
880 * errors. Any of the errors in #GConvertError other than
881 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
883 * Convert a string from a 32-bit fixed width representation as UCS-4.
884 * to UTF-8. The result will be terminated with a 0 byte.
886 * Returns: a pointer to a newly allocated UTF-8 string.
887 * This value must be freed with g_free(). If an error occurs,
888 * %NULL will be returned and @error set. In that case, @items_read
889 * will be set to the position of the first invalid input character.
892 g_ucs4_to_utf8 (const gunichar *str,
895 glong *items_written,
899 gchar *result = NULL;
904 for (i = 0; len < 0 || i < len ; i++)
909 if (str[i] >= 0x80000000)
911 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
912 _("Character out of range for UTF-8"));
916 result_length += UTF8_LENGTH (str[i]);
919 result = try_malloc_n (result_length + 1, 1, error);
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 #gunichar2) 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,
949 * or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
950 * returned in case @str contains a trailing partial character. If
951 * an error occurs then the index of the invalid input is stored here.
952 * @items_written: (allow-none): location to store number of bytes written,
953 * or %NULL. The value stored here does not include the trailing 0 byte.
954 * @error: location to store the error occurring, or %NULL to ignore
955 * errors. Any of the errors in #GConvertError other than
956 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
958 * Convert a string from UTF-16 to UTF-8. The result will be
959 * terminated with a 0 byte.
961 * Note that the input is expected to be already in native endianness,
962 * an initial byte-order-mark character is not handled specially.
963 * g_convert() can be used to convert a byte buffer of UTF-16 data of
964 * ambiguous endianess.
966 * Further note that this function does not validate the result
967 * string; it may e.g. include embedded NUL characters. The only
968 * validation done by this function is to ensure that the input can
969 * be correctly interpreted as UTF-16, i.e. it doesn't contain
970 * things unpaired surrogates.
972 * Returns: a pointer to a newly allocated UTF-8 string.
973 * This value must be freed with g_free(). If an error occurs,
974 * %NULL will be returned and @error set.
977 g_utf16_to_utf8 (const gunichar2 *str,
980 glong *items_written,
983 /* This function and g_utf16_to_ucs4 are almost exactly identical -
984 * The lines that differ are marked.
988 gchar *result = NULL;
990 gunichar high_surrogate;
992 g_return_val_if_fail (str != NULL, NULL);
997 while ((len < 0 || in - str < len) && *in)
1002 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1006 wc = SURROGATE_VALUE (high_surrogate, c);
1011 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1012 _("Invalid sequence in conversion input"));
1020 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1021 _("Invalid sequence in conversion input"));
1025 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1034 /********** DIFFERENT for UTF8/UCS4 **********/
1035 n_bytes += UTF8_LENGTH (wc);
1041 if (high_surrogate && !items_read)
1043 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1044 _("Partial character sequence at end of input"));
1048 /* At this point, everything is valid, and we just need to convert
1050 /********** DIFFERENT for UTF8/UCS4 **********/
1051 result = try_malloc_n (n_bytes + 1, 1, error);
1058 while (out < result + n_bytes)
1063 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1065 wc = SURROGATE_VALUE (high_surrogate, c);
1068 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1076 /********** DIFFERENT for UTF8/UCS4 **********/
1077 out += g_unichar_to_utf8 (wc, out);
1083 /********** DIFFERENT for UTF8/UCS4 **********/
1087 /********** DIFFERENT for UTF8/UCS4 **********/
1088 *items_written = out - result;
1092 *items_read = in - str;
1099 * @str: a UTF-16 encoded string
1100 * @len: the maximum length (number of #gunichar2) of @str to use.
1101 * If @len < 0, then the string is nul-terminated.
1102 * @items_read: (allow-none): location to store number of words read,
1103 * or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1104 * returned in case @str contains a trailing partial character. If
1105 * an error occurs then the index of the invalid input is stored here.
1106 * @items_written: (allow-none): location to store number of characters
1107 * written, or %NULL. The value stored here does not include the trailing
1109 * @error: location to store the error occurring, or %NULL to ignore
1110 * errors. Any of the errors in #GConvertError other than
1111 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1113 * Convert a string from UTF-16 to UCS-4. The result will be
1116 * Returns: a pointer to a newly allocated UCS-4 string.
1117 * This value must be freed with g_free(). If an error occurs,
1118 * %NULL will be returned and @error set.
1121 g_utf16_to_ucs4 (const gunichar2 *str,
1124 glong *items_written,
1127 const gunichar2 *in;
1129 gchar *result = NULL;
1131 gunichar high_surrogate;
1133 g_return_val_if_fail (str != NULL, NULL);
1138 while ((len < 0 || in - str < len) && *in)
1142 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1150 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1151 _("Invalid sequence in conversion input"));
1159 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1160 _("Invalid sequence in conversion input"));
1164 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1171 /********** DIFFERENT for UTF8/UCS4 **********/
1172 n_bytes += sizeof (gunichar);
1178 if (high_surrogate && !items_read)
1180 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1181 _("Partial character sequence at end of input"));
1185 /* At this point, everything is valid, and we just need to convert
1187 /********** DIFFERENT for UTF8/UCS4 **********/
1188 result = try_malloc_n (n_bytes + 4, 1, error);
1195 while (out < result + n_bytes)
1200 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1202 wc = SURROGATE_VALUE (high_surrogate, c);
1205 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1213 /********** DIFFERENT for UTF8/UCS4 **********/
1214 *(gunichar *)out = wc;
1215 out += sizeof (gunichar);
1221 /********** DIFFERENT for UTF8/UCS4 **********/
1222 *(gunichar *)out = 0;
1225 /********** DIFFERENT for UTF8/UCS4 **********/
1226 *items_written = (out - result) / sizeof (gunichar);
1230 *items_read = in - str;
1232 return (gunichar *)result;
1237 * @str: a UTF-8 encoded string
1238 * @len: the maximum length (number of bytes) of @str to use.
1239 * If @len < 0, then the string is nul-terminated.
1240 * @items_read: (allow-none): location to store number of bytes read,
1241 * or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1242 * returned in case @str contains a trailing partial character. If
1243 * an error occurs then the index of the invalid input is stored here.
1244 * @items_written: (allow-none): location to store number of #gunichar2
1245 * written, or %NULL. The value stored here does not include the
1247 * @error: location to store the error occurring, or %NULL to ignore
1248 * errors. Any of the errors in #GConvertError other than
1249 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1251 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1252 * added to the result after the converted text.
1254 * Returns: a pointer to a newly allocated UTF-16 string.
1255 * This value must be freed with g_free(). If an error occurs,
1256 * %NULL will be returned and @error set.
1259 g_utf8_to_utf16 (const gchar *str,
1262 glong *items_written,
1265 gunichar2 *result = NULL;
1270 g_return_val_if_fail (str != NULL, NULL);
1274 while ((len < 0 || str + len - in > 0) && *in)
1276 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1277 if (wc & 0x80000000)
1279 if (wc == (gunichar)-2)
1284 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1285 _("Partial character sequence at end of input"));
1288 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1289 _("Invalid byte sequence in conversion input"));
1296 else if (wc < 0xe000)
1298 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1299 _("Invalid sequence in conversion input"));
1303 else if (wc < 0x10000)
1305 else if (wc < 0x110000)
1309 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1310 _("Character out of range for UTF-16"));
1315 in = g_utf8_next_char (in);
1318 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1323 for (i = 0; i < n16;)
1325 gunichar wc = g_utf8_get_char (in);
1333 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1334 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1337 in = g_utf8_next_char (in);
1343 *items_written = n16;
1347 *items_read = in - str;
1354 * @str: a UCS-4 encoded string
1355 * @len: the maximum length (number of characters) of @str to use.
1356 * If @len < 0, then the string is nul-terminated.
1357 * @items_read: (allow-none): location to store number of bytes read,
1358 * or %NULL. If an error occurs then the index of the invalid input
1360 * @items_written: (allow-none): location to store number of #gunichar2
1361 * written, or %NULL. The value stored here does not include the
1363 * @error: location to store the error occurring, or %NULL to ignore
1364 * errors. Any of the errors in #GConvertError other than
1365 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1367 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1368 * added to the result after the converted text.
1370 * Returns: a pointer to a newly allocated UTF-16 string.
1371 * This value must be freed with g_free(). If an error occurs,
1372 * %NULL will be returned and @error set.
1375 g_ucs4_to_utf16 (const gunichar *str,
1378 glong *items_written,
1381 gunichar2 *result = NULL;
1387 while ((len < 0 || i < len) && str[i])
1389 gunichar wc = str[i];
1393 else if (wc < 0xe000)
1395 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1396 _("Invalid sequence in conversion input"));
1400 else if (wc < 0x10000)
1402 else if (wc < 0x110000)
1406 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1407 _("Character out of range for UTF-16"));
1415 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
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) (transfer none): 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 require valid UTF-8 as input; so data read from a file
1615 * or the network should be checked with g_utf8_validate() before
1616 * doing anything else with it.
1618 * Returns: %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 * Returns: %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);