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.
32 #ifdef G_PLATFORM_WIN32
39 #include "libcharset/libcharset.h"
44 #define UTF8_COMPUTE(Char, Mask, Len) \
50 else if ((Char & 0xe0) == 0xc0) \
55 else if ((Char & 0xf0) == 0xe0) \
60 else if ((Char & 0xf8) == 0xf0) \
65 else if ((Char & 0xfc) == 0xf8) \
70 else if ((Char & 0xfe) == 0xfc) \
78 #define UTF8_LENGTH(Char) \
79 ((Char) < 0x80 ? 1 : \
80 ((Char) < 0x800 ? 2 : \
81 ((Char) < 0x10000 ? 3 : \
82 ((Char) < 0x200000 ? 4 : \
83 ((Char) < 0x4000000 ? 5 : 6)))))
86 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
87 (Result) = (Chars)[0] & (Mask); \
88 for ((Count) = 1; (Count) < (Len); ++(Count)) \
90 if (((Chars)[(Count)] & 0xc0) != 0x80) \
96 (Result) |= ((Chars)[(Count)] & 0x3f); \
99 #define UNICODE_VALID(Char) \
100 ((Char) < 0x110000 && \
101 (((Char) & 0xFFFFF800) != 0xD800) && \
102 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
103 ((Char) & 0xFFFE) != 0xFFFE)
106 static const gchar utf8_skip_data[256] = {
107 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,
108 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,
109 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,
110 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,
111 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,
112 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,
113 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,
114 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
117 const gchar * const g_utf8_skip = utf8_skip_data;
120 * g_utf8_find_prev_char:
121 * @str: pointer to the beginning of a UTF-8 encoded string
122 * @p: pointer to some position within @str
124 * Given a position @p with a UTF-8 encoded string @str, find the start
125 * of the previous UTF-8 character starting before @p. Returns %NULL if no
126 * UTF-8 characters are present in @str before @p.
128 * @p does not have to be at the beginning of a UTF-8 character. No check
129 * is made to see if the character found is actually valid other than
130 * it starts with an appropriate byte.
132 * Return value: a pointer to the found character or %NULL.
135 g_utf8_find_prev_char (const char *str,
138 for (--p; p >= str; --p)
140 if ((*p & 0xc0) != 0x80)
147 * g_utf8_find_next_char:
148 * @p: a pointer to a position within a UTF-8 encoded string
149 * @end: a pointer to the byte following the end of the string,
150 * or %NULL to indicate that the string is nul-terminated.
152 * Finds the start of the next UTF-8 character in the string after @p.
154 * @p does not have to be at the beginning of a UTF-8 character. No check
155 * is made to see if the character found is actually valid other than
156 * it starts with an appropriate byte.
158 * Return value: a pointer to the found character or %NULL
161 g_utf8_find_next_char (const gchar *p,
167 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
170 for (++p; (*p & 0xc0) == 0x80; ++p)
173 return (p == end) ? NULL : (gchar *)p;
178 * @p: a pointer to a position within a UTF-8 encoded string
180 * Finds the previous UTF-8 character in the string before @p.
182 * @p does not have to be at the beginning of a UTF-8 character. No check
183 * is made to see if the character found is actually valid other than
184 * it starts with an appropriate byte. If @p might be the first
185 * character of the string, you must use g_utf8_find_prev_char() instead.
187 * Return value: a pointer to the found character.
190 g_utf8_prev_char (const gchar *p)
195 if ((*p & 0xc0) != 0x80)
202 * @p: pointer to the start of a UTF-8 encoded string.
203 * @max: the maximum number of bytes to examine. If @max
204 * is less than 0, then the string is assumed to be
205 * nul-terminated. If @max is 0, @p will not be examined and
208 * Returns the length of the string in characters.
210 * Return value: the length of the string in characters
213 g_utf8_strlen (const gchar *p,
217 const gchar *start = p;
218 g_return_val_if_fail (p != NULL || max == 0, 0);
224 p = g_utf8_next_char (p);
233 p = g_utf8_next_char (p);
235 while (p - start < max && *p)
238 p = g_utf8_next_char (p);
241 /* only do the last len increment if we got a complete
242 * char (don't count partial chars)
244 if (p - start <= max)
253 * @p: a pointer to Unicode character encoded as UTF-8
255 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
256 * If @p does not point to a valid UTF-8 encoded character, results are
257 * undefined. If you are not sure that the bytes are complete
258 * valid Unicode characters, you should use g_utf8_get_char_validated()
261 * Return value: the resulting character
264 g_utf8_get_char (const gchar *p)
266 int i, mask = 0, len;
268 unsigned char c = (unsigned char) *p;
270 UTF8_COMPUTE (c, mask, len);
273 UTF8_GET (result, p, i, mask, len);
279 * g_utf8_offset_to_pointer:
280 * @str: a UTF-8 encoded string
281 * @offset: a character offset within @str
283 * Converts from an integer character offset to a pointer to a position
286 * Since 2.10, this function allows to pass a negative @offset to
287 * step backwards. It is usually worth stepping backwards from the end
288 * instead of forwards if @offset is in the last fourth of the string,
289 * since moving forward is about 3 times faster than moving backward.
291 * Return value: the resulting pointer
294 g_utf8_offset_to_pointer (const gchar *str,
297 const gchar *s = str;
301 s = g_utf8_next_char (s);
306 /* This nice technique for fast backwards stepping
307 * through a UTF-8 string was dubbed "stutter stepping"
308 * by its inventor, Larry Ewing.
314 while ((*s & 0xc0) == 0x80)
317 offset += g_utf8_pointer_to_offset (s, s1);
325 * g_utf8_pointer_to_offset:
326 * @str: a UTF-8 encoded string
327 * @pos: a pointer to a position within @str
329 * Converts from a pointer to position within a string to a integer
332 * Since 2.10, this function allows @pos to be before @str, and returns
333 * a negative offset in this case.
335 * Return value: the resulting character offset
338 g_utf8_pointer_to_offset (const gchar *str,
341 const gchar *s = str;
345 offset = - g_utf8_pointer_to_offset (pos, str);
349 s = g_utf8_next_char (s);
359 * @dest: buffer to fill with characters from @src
360 * @src: UTF-8 encoded string
361 * @n: character count
363 * Like the standard C strncpy() function, but
364 * copies a given number of characters instead of a given number of
365 * bytes. The @src string must be valid UTF-8 encoded text.
366 * (Use g_utf8_validate() on all text before trying to use UTF-8
367 * utility functions with it.)
369 * Return value: @dest
372 g_utf8_strncpy (gchar *dest,
376 const gchar *s = src;
379 s = g_utf8_next_char(s);
382 strncpy(dest, src, s - src);
387 G_LOCK_DEFINE_STATIC (aliases);
390 get_alias_hash (void)
392 static GHashTable *alias_hash = NULL;
399 alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
401 aliases = _g_locale_get_charset_aliases ();
402 while (*aliases != '\0')
404 const char *canonical;
406 const char **alias_array;
410 aliases += strlen (aliases) + 1;
412 aliases += strlen (aliases) + 1;
414 alias_array = g_hash_table_lookup (alias_hash, canonical);
417 while (alias_array[count])
421 alias_array = g_renew (const char *, alias_array, count + 2);
422 alias_array[count] = alias;
423 alias_array[count + 1] = NULL;
425 g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
434 /* As an abuse of the alias table, the following routines gets
435 * the charsets that are aliases for the canonical name.
437 G_GNUC_INTERNAL const char **
438 _g_charset_get_aliases (const char *canonical_name)
440 GHashTable *alias_hash = get_alias_hash ();
442 return g_hash_table_lookup (alias_hash, canonical_name);
446 g_utf8_get_charset_internal (const char *raw_data,
449 const char *charset = getenv("CHARSET");
451 if (charset && *charset)
455 if (charset && strstr (charset, "UTF-8"))
461 /* The libcharset code tries to be thread-safe without
462 * a lock, but has a memory leak and a missing memory
463 * barrier, so we lock for it
466 charset = _g_locale_charset_unalias (raw_data);
469 if (charset && *charset)
473 if (charset && strstr (charset, "UTF-8"))
479 /* Assume this for compatibility at present. */
485 typedef struct _GCharsetCache GCharsetCache;
487 struct _GCharsetCache {
494 charset_cache_free (gpointer data)
496 GCharsetCache *cache = data;
498 g_free (cache->charset);
504 * @charset: return location for character set name
506 * Obtains the character set for the <link linkend="setlocale">current
507 * locale</link>; you might use this character set as an argument to
508 * g_convert(), to convert from the current locale's encoding to some
509 * other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8()
510 * are nice shortcuts, though.)
512 * On Windows the character set returned by this function is the
513 * so-called system default ANSI code-page. That is the character set
514 * used by the "narrow" versions of C library and Win32 functions that
515 * handle file names. It might be different from the character set
516 * used by the C library's current locale.
518 * The return value is %TRUE if the locale's encoding is UTF-8, in that
519 * case you can perhaps avoid calling g_convert().
521 * The string returned in @charset is not allocated, and should not be
524 * Return value: %TRUE if the returned charset is UTF-8
527 g_get_charset (G_CONST_RETURN char **charset)
529 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
530 GCharsetCache *cache = g_static_private_get (&cache_private);
535 cache = g_new0 (GCharsetCache, 1);
536 g_static_private_set (&cache_private, cache, charset_cache_free);
539 raw = _g_locale_charset_raw ();
541 if (!(cache->raw && strcmp (cache->raw, raw) == 0))
543 const gchar *new_charset;
546 g_free (cache->charset);
547 cache->raw = g_strdup (raw);
548 cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
549 cache->charset = g_strdup (new_charset);
553 *charset = cache->charset;
555 return cache->is_utf8;
562 * @c: a Unicode character code
563 * @outbuf: output buffer, must have at least 6 bytes of space.
564 * If %NULL, the length will be computed and returned
565 * and nothing will be written to @outbuf.
567 * Converts a single character to UTF-8.
569 * Return value: number of bytes written
572 g_unichar_to_utf8 (gunichar c,
575 /* If this gets modified, also update the copy in g_string_insert_unichar() */
590 else if (c < 0x10000)
595 else if (c < 0x200000)
600 else if (c < 0x4000000)
613 for (i = len - 1; i > 0; --i)
615 outbuf[i] = (c & 0x3f) | 0x80;
618 outbuf[0] = c | first;
626 * @p: a nul-terminated UTF-8 encoded string
627 * @len: the maximum length of @p
628 * @c: a Unicode character
630 * Finds the leftmost occurrence of the given Unicode character
631 * in a UTF-8 encoded string, while limiting the search to @len bytes.
632 * If @len is -1, allow unbounded search.
634 * Return value: %NULL if the string does not contain the character,
635 * otherwise, a pointer to the start of the leftmost occurrence of
636 * the character in the string.
639 g_utf8_strchr (const char *p,
645 gint charlen = g_unichar_to_utf8 (c, ch);
648 return g_strstr_len (p, len, ch);
654 * @p: a nul-terminated UTF-8 encoded string
655 * @len: the maximum length of @p
656 * @c: a Unicode character
658 * Find the rightmost occurrence of the given Unicode character
659 * in a UTF-8 encoded string, while limiting the search to @len bytes.
660 * If @len is -1, allow unbounded search.
662 * Return value: %NULL if the string does not contain the character,
663 * otherwise, a pointer to the start of the rightmost occurrence of the
664 * character in the string.
667 g_utf8_strrchr (const char *p,
673 gint charlen = g_unichar_to_utf8 (c, ch);
676 return g_strrstr_len (p, len, ch);
680 /* Like g_utf8_get_char, but take a maximum length
681 * and return (gunichar)-2 on incomplete trailing character
683 static inline gunichar
684 g_utf8_get_char_extended (const gchar *p,
688 gunichar wc = (guchar) *p;
728 if (max_len >= 0 && len > max_len)
730 for (i = 1; i < max_len; i++)
732 if ((((guchar *)p)[i] & 0xc0) != 0x80)
738 for (i = 1; i < len; ++i)
740 gunichar ch = ((guchar *)p)[i];
742 if ((ch & 0xc0) != 0x80)
754 if (UTF8_LENGTH(wc) != len)
761 * g_utf8_get_char_validated:
762 * @p: a pointer to Unicode character encoded as UTF-8
763 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
764 * if @p is nul-terminated
766 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
767 * This function checks for incomplete characters, for invalid characters
768 * such as characters that are out of the range of Unicode, and for
769 * overlong encodings of valid characters.
771 * Return value: the resulting character. If @p points to a partial
772 * sequence at the end of a string that could begin a valid
773 * character (or if @max_len is zero), returns (gunichar)-2;
774 * otherwise, if @p does not point to a valid UTF-8 encoded
775 * Unicode character, returns (gunichar)-1.
778 g_utf8_get_char_validated (const gchar *p,
786 result = g_utf8_get_char_extended (p, max_len);
788 if (result & 0x80000000)
790 else if (!UNICODE_VALID (result))
797 * g_utf8_to_ucs4_fast:
798 * @str: a UTF-8 encoded string
799 * @len: the maximum length of @str to use, in bytes. If @len < 0,
800 * then the string is nul-terminated.
801 * @items_written: location to store the number of characters in the
804 * Convert a string from UTF-8 to a 32-bit fixed width
805 * representation as UCS-4, assuming valid UTF-8 input.
806 * This function is roughly twice as fast as g_utf8_to_ucs4()
807 * but does no error checking on the input.
809 * Return value: a pointer to a newly allocated UCS-4 string.
810 * This value must be freed with g_free().
813 g_utf8_to_ucs4_fast (const gchar *str,
815 glong *items_written)
822 g_return_val_if_fail (str != NULL, NULL);
830 p = g_utf8_next_char (p);
836 while (p < str + len && *p)
838 p = g_utf8_next_char (p);
843 result = g_new (gunichar, n_chars + 1);
846 for (i=0; i < n_chars; i++)
848 gunichar wc = ((unsigned char *)p)[0];
883 for (j = 1; j < charlen; j++)
886 wc |= ((unsigned char *)p)[j] & 0x3f;
903 * @str: a UTF-8 encoded string
904 * @len: the maximum length of @str to use, in bytes. If @len < 0,
905 * then the string is nul-terminated.
906 * @items_read: location to store number of bytes read, or %NULL.
907 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
908 * returned in case @str contains a trailing partial
909 * character. If an error occurs then the index of the
910 * invalid input is stored here.
911 * @items_written: location to store number of characters written or %NULL.
912 * The value here stored does not include the trailing 0
914 * @error: location to store the error occuring, or %NULL to ignore
915 * errors. Any of the errors in #GConvertError other than
916 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
918 * Convert a string from UTF-8 to a 32-bit fixed width
919 * representation as UCS-4. A trailing 0 will be added to the
920 * string after the converted text.
922 * Return value: a pointer to a newly allocated UCS-4 string.
923 * This value must be freed with g_free(). If an
924 * error occurs, %NULL will be returned and
928 g_utf8_to_ucs4 (const gchar *str,
931 glong *items_written,
934 gunichar *result = NULL;
940 while ((len < 0 || str + len - in > 0) && *in)
942 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
945 if (wc == (gunichar)-2)
950 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
951 _("Partial character sequence at end of input"));
954 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
955 _("Invalid byte sequence in conversion input"));
962 in = g_utf8_next_char (in);
965 result = g_new (gunichar, n_chars + 1);
968 for (i=0; i < n_chars; i++)
970 result[i] = g_utf8_get_char (in);
971 in = g_utf8_next_char (in);
976 *items_written = n_chars;
980 *items_read = in - str;
987 * @str: a UCS-4 encoded string
988 * @len: the maximum length (number of characters) of @str to use.
989 * If @len < 0, then the string is nul-terminated.
990 * @items_read: location to store number of characters read, or %NULL.
991 * @items_written: location to store number of bytes written or %NULL.
992 * The value here stored does not include the trailing 0
994 * @error: location to store the error occuring, or %NULL to ignore
995 * errors. Any of the errors in #GConvertError other than
996 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
998 * Convert a string from a 32-bit fixed width representation as UCS-4.
999 * to UTF-8. The result will be terminated with a 0 byte.
1001 * Return value: a pointer to a newly allocated UTF-8 string.
1002 * This value must be freed with g_free(). If an
1003 * error occurs, %NULL will be returned and
1004 * @error set. In that case, @items_read will be
1005 * set to the position of the first invalid input
1009 g_ucs4_to_utf8 (const gunichar *str,
1012 glong *items_written,
1016 gchar *result = NULL;
1021 for (i = 0; len < 0 || i < len ; i++)
1026 if (str[i] >= 0x80000000)
1028 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1029 _("Character out of range for UTF-8"));
1033 result_length += UTF8_LENGTH (str[i]);
1036 result = g_malloc (result_length + 1);
1040 while (p < result + result_length)
1041 p += g_unichar_to_utf8 (str[i++], p);
1046 *items_written = p - result;
1055 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1059 * @str: a UTF-16 encoded string
1060 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1061 * If @len < 0, then the string is nul-terminated.
1062 * @items_read: location to store number of words read, or %NULL.
1063 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1064 * returned in case @str contains a trailing partial
1065 * character. If an error occurs then the index of the
1066 * invalid input is stored here.
1067 * @items_written: location to store number of bytes written, or %NULL.
1068 * The value stored here does not include the trailing
1070 * @error: location to store the error occuring, or %NULL to ignore
1071 * errors. Any of the errors in #GConvertError other than
1072 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1074 * Convert a string from UTF-16 to UTF-8. The result will be
1075 * terminated with a 0 byte.
1077 * Note that the input is expected to be already in native endianness,
1078 * an initial byte-order-mark character is not handled specially.
1079 * g_convert() can be used to convert a byte buffer of UTF-16 data of
1080 * ambiguous endianess.
1082 * Return value: a pointer to a newly allocated UTF-8 string.
1083 * This value must be freed with g_free(). If an
1084 * error occurs, %NULL will be returned and
1088 g_utf16_to_utf8 (const gunichar2 *str,
1091 glong *items_written,
1094 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1097 const gunichar2 *in;
1099 gchar *result = NULL;
1101 gunichar high_surrogate;
1103 g_return_val_if_fail (str != NULL, NULL);
1108 while ((len < 0 || in - str < len) && *in)
1113 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1117 wc = SURROGATE_VALUE (high_surrogate, c);
1122 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1123 _("Invalid sequence in conversion input"));
1131 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1132 _("Invalid sequence in conversion input"));
1136 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1145 /********** DIFFERENT for UTF8/UCS4 **********/
1146 n_bytes += UTF8_LENGTH (wc);
1152 if (high_surrogate && !items_read)
1154 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1155 _("Partial character sequence at end of input"));
1159 /* At this point, everything is valid, and we just need to convert
1161 /********** DIFFERENT for UTF8/UCS4 **********/
1162 result = g_malloc (n_bytes + 1);
1167 while (out < result + n_bytes)
1172 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1174 wc = SURROGATE_VALUE (high_surrogate, c);
1177 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1185 /********** DIFFERENT for UTF8/UCS4 **********/
1186 out += g_unichar_to_utf8 (wc, out);
1192 /********** DIFFERENT for UTF8/UCS4 **********/
1196 /********** DIFFERENT for UTF8/UCS4 **********/
1197 *items_written = out - result;
1201 *items_read = in - str;
1208 * @str: a UTF-16 encoded string
1209 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1210 * If @len < 0, then the string is nul-terminated.
1211 * @items_read: location to store number of words read, or %NULL.
1212 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1213 * returned in case @str contains a trailing partial
1214 * character. If an error occurs then the index of the
1215 * invalid input is stored here.
1216 * @items_written: location to store number of characters written, or %NULL.
1217 * The value stored here does not include the trailing
1219 * @error: location to store the error occuring, or %NULL to ignore
1220 * errors. Any of the errors in #GConvertError other than
1221 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1223 * Convert a string from UTF-16 to UCS-4. The result will be
1226 * Return value: a pointer to a newly allocated UCS-4 string.
1227 * This value must be freed with g_free(). If an
1228 * error occurs, %NULL will be returned and
1232 g_utf16_to_ucs4 (const gunichar2 *str,
1235 glong *items_written,
1238 const gunichar2 *in;
1240 gchar *result = NULL;
1242 gunichar high_surrogate;
1244 g_return_val_if_fail (str != NULL, NULL);
1249 while ((len < 0 || in - str < len) && *in)
1254 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1258 wc = SURROGATE_VALUE (high_surrogate, c);
1263 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1264 _("Invalid sequence in conversion input"));
1272 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1273 _("Invalid sequence in conversion input"));
1277 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1286 /********** DIFFERENT for UTF8/UCS4 **********/
1287 n_bytes += sizeof (gunichar);
1293 if (high_surrogate && !items_read)
1295 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1296 _("Partial character sequence at end of input"));
1300 /* At this point, everything is valid, and we just need to convert
1302 /********** DIFFERENT for UTF8/UCS4 **********/
1303 result = g_malloc (n_bytes + 4);
1308 while (out < result + n_bytes)
1313 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1315 wc = SURROGATE_VALUE (high_surrogate, c);
1318 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1326 /********** DIFFERENT for UTF8/UCS4 **********/
1327 *(gunichar *)out = wc;
1328 out += sizeof (gunichar);
1334 /********** DIFFERENT for UTF8/UCS4 **********/
1335 *(gunichar *)out = 0;
1338 /********** DIFFERENT for UTF8/UCS4 **********/
1339 *items_written = (out - result) / sizeof (gunichar);
1343 *items_read = in - str;
1345 return (gunichar *)result;
1350 * @str: a UTF-8 encoded string
1351 * @len: the maximum length (number of characters) of @str to use.
1352 * If @len < 0, then the string is nul-terminated.
1353 * @items_read: location to store number of bytes read, or %NULL.
1354 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1355 * returned in case @str contains a trailing partial
1356 * character. If an error occurs then the index of the
1357 * invalid input is stored here.
1358 * @items_written: location to store number of <type>gunichar2</type> written,
1360 * The value stored here does not include the trailing 0.
1361 * @error: location to store the error occuring, or %NULL to ignore
1362 * errors. Any of the errors in #GConvertError other than
1363 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1365 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1366 * added to the result after the converted text.
1368 * Return value: a pointer to a newly allocated UTF-16 string.
1369 * This value must be freed with g_free(). If an
1370 * error occurs, %NULL will be returned and
1374 g_utf8_to_utf16 (const gchar *str,
1377 glong *items_written,
1380 gunichar2 *result = NULL;
1385 g_return_val_if_fail (str != NULL, NULL);
1389 while ((len < 0 || str + len - in > 0) && *in)
1391 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1392 if (wc & 0x80000000)
1394 if (wc == (gunichar)-2)
1399 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1400 _("Partial character sequence at end of input"));
1403 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1404 _("Invalid byte sequence in conversion input"));
1411 else if (wc < 0xe000)
1413 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1414 _("Invalid sequence in conversion input"));
1418 else if (wc < 0x10000)
1420 else if (wc < 0x110000)
1424 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1425 _("Character out of range for UTF-16"));
1430 in = g_utf8_next_char (in);
1433 result = g_new (gunichar2, n16 + 1);
1436 for (i = 0; i < n16;)
1438 gunichar wc = g_utf8_get_char (in);
1446 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1447 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1450 in = g_utf8_next_char (in);
1456 *items_written = n16;
1460 *items_read = in - str;
1467 * @str: a UCS-4 encoded string
1468 * @len: the maximum length (number of characters) of @str to use.
1469 * If @len < 0, then the string is nul-terminated.
1470 * @items_read: location to store number of bytes read, or %NULL.
1471 * If an error occurs then the index of the invalid input
1473 * @items_written: location to store number of <type>gunichar2</type>
1474 * written, or %NULL. The value stored here does not
1475 * include the trailing 0.
1476 * @error: location to store the error occuring, or %NULL to ignore
1477 * errors. Any of the errors in #GConvertError other than
1478 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1480 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1481 * added to the result after the converted text.
1483 * Return value: a pointer to a newly allocated UTF-16 string.
1484 * This value must be freed with g_free(). If an
1485 * error occurs, %NULL will be returned and
1489 g_ucs4_to_utf16 (const gunichar *str,
1492 glong *items_written,
1495 gunichar2 *result = NULL;
1501 while ((len < 0 || i < len) && str[i])
1503 gunichar wc = str[i];
1507 else if (wc < 0xe000)
1509 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1510 _("Invalid sequence in conversion input"));
1514 else if (wc < 0x10000)
1516 else if (wc < 0x110000)
1520 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1521 _("Character out of range for UTF-16"));
1529 result = g_new (gunichar2, n16 + 1);
1531 for (i = 0, j = 0; j < n16; i++)
1533 gunichar wc = str[i];
1541 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1542 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1548 *items_written = n16;
1557 #define CONTINUATION_CHAR \
1559 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1562 val |= (*(guchar *)p) & 0x3f; \
1565 static const gchar *
1566 fast_validate (const char *str)
1573 for (p = str; *p; p++)
1575 if (*(guchar *)p < 128)
1582 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1584 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1587 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1592 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1595 val = *(guchar *)p & 0x0f;
1598 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1601 val = *(guchar *)p & 0x07;
1614 if (G_UNLIKELY (val < min))
1617 if (G_UNLIKELY (!UNICODE_VALID(val)))
1631 static const gchar *
1632 fast_validate_len (const char *str,
1640 g_assert (max_len >= 0);
1642 for (p = str; ((p - str) < max_len) && *p; p++)
1644 if (*(guchar *)p < 128)
1651 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1653 if (G_UNLIKELY (max_len - (p - str) < 2))
1656 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1659 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1664 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1666 if (G_UNLIKELY (max_len - (p - str) < 3))
1670 val = *(guchar *)p & 0x0f;
1673 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1675 if (G_UNLIKELY (max_len - (p - str) < 4))
1679 val = *(guchar *)p & 0x07;
1692 if (G_UNLIKELY (val < min))
1694 if (G_UNLIKELY (!UNICODE_VALID(val)))
1710 * @str: a pointer to character data
1711 * @max_len: max bytes to validate, or -1 to go until NUL
1712 * @end: return location for end of valid data
1714 * Validates UTF-8 encoded text. @str is the text to validate;
1715 * if @str is nul-terminated, then @max_len can be -1, otherwise
1716 * @max_len should be the number of bytes to validate.
1717 * If @end is non-%NULL, then the end of the valid range
1718 * will be stored there (i.e. the start of the first invalid
1719 * character if some bytes were invalid, or the end of the text
1720 * being validated otherwise).
1722 * Note that g_utf8_validate() returns %FALSE if @max_len is
1723 * positive and NUL is met before @max_len bytes have been read.
1725 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1726 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1727 * so data read from a file or the network should be checked
1728 * with g_utf8_validate() before doing anything else with it.
1730 * Return value: %TRUE if the text was valid UTF-8
1733 g_utf8_validate (const char *str,
1741 p = fast_validate (str);
1743 p = fast_validate_len (str, max_len);
1748 if ((max_len >= 0 && p != str + max_len) ||
1749 (max_len < 0 && *p != '\0'))
1756 * g_unichar_validate:
1757 * @ch: a Unicode character
1759 * Checks whether @ch is a valid Unicode character. Some possible
1760 * integer values of @ch will not be valid. 0 is considered a valid
1761 * character, though it's normally a string terminator.
1763 * Return value: %TRUE if @ch is a valid Unicode character
1766 g_unichar_validate (gunichar ch)
1768 return UNICODE_VALID (ch);
1772 * g_utf8_strreverse:
1773 * @str: a UTF-8 encoded string
1774 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1775 * then the string is nul-terminated.
1777 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1778 * (Use g_utf8_validate() on all text before trying to use UTF-8
1779 * utility functions with it.)
1781 * This function is intended for programmatic uses of reversed strings.
1782 * It pays no attention to decomposed characters, combining marks, byte
1783 * order marks, directional indicators (LRM, LRO, etc) and similar
1784 * characters which might need special handling when reversing a string
1785 * for display purposes.
1787 * Note that unlike g_strreverse(), this function returns
1788 * newly-allocated memory, which should be freed with g_free() when
1791 * Returns: a newly-allocated string which is the reverse of @str.
1796 g_utf8_strreverse (const gchar *str,
1805 result = g_new (gchar, len + 1);
1810 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1812 for (m = r; skip; skip--)
1822 _g_utf8_make_valid (const gchar *name)
1825 const gchar *remainder, *invalid;
1826 gint remaining_bytes, valid_bytes;
1830 remaining_bytes = strlen (name);
1832 while (remaining_bytes != 0)
1834 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1836 valid_bytes = invalid - remainder;
1839 string = g_string_sized_new (remaining_bytes);
1841 g_string_append_len (string, remainder, valid_bytes);
1842 /* append U+FFFD REPLACEMENT CHARACTER */
1843 g_string_append (string, "\357\277\275");
1845 remaining_bytes -= valid_bytes + 1;
1846 remainder = invalid + 1;
1850 return g_strdup (name);
1852 g_string_append (string, remainder);
1854 g_assert (g_utf8_validate (string->str, -1, NULL));
1856 return g_string_free (string, FALSE);
1860 #define __G_UTF8_C__
1861 #include "galiasdef.c"