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); \
100 * Check whether a Unicode (5.2) char is in a valid range.
102 * The first check comes from the Unicode guarantee to never encode
103 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
105 * The second check covers surrogate pairs (category Cs).
107 * The last two checks cover "Noncharacter": defined as:
108 * "A code point that is permanently reserved for
109 * internal use, and that should never be interchanged. In
110 * Unicode 3.1, these consist of the values U+nFFFE and U+nFFFF
111 * (where n is from 0 to 10_16) and the values U+FDD0..U+FDEF."
113 * @param Char the character
115 #define UNICODE_VALID(Char) \
116 ((Char) < 0x110000 && \
117 (((Char) & 0xFFFFF800) != 0xD800) && \
118 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
119 ((Char) & 0xFFFE) != 0xFFFE)
122 static const gchar utf8_skip_data[256] = {
123 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,
124 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
125 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
126 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
127 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
128 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
129 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,
130 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
133 const gchar * const g_utf8_skip = utf8_skip_data;
136 * g_utf8_find_prev_char:
137 * @str: pointer to the beginning of a UTF-8 encoded string
138 * @p: pointer to some position within @str
140 * Given a position @p with a UTF-8 encoded string @str, find the start
141 * of the previous UTF-8 character starting before @p. Returns %NULL if no
142 * UTF-8 characters are present in @str before @p.
144 * @p does not have to be at the beginning of a UTF-8 character. No check
145 * is made to see if the character found is actually valid other than
146 * it starts with an appropriate byte.
148 * Return value: a pointer to the found character or %NULL.
151 g_utf8_find_prev_char (const char *str,
154 for (--p; p >= str; --p)
156 if ((*p & 0xc0) != 0x80)
163 * g_utf8_find_next_char:
164 * @p: a pointer to a position within a UTF-8 encoded string
165 * @end: a pointer to the byte following the end of the string,
166 * or %NULL to indicate that the string is nul-terminated.
168 * Finds the start of the next UTF-8 character in the string after @p.
170 * @p does not have to be at the beginning of a UTF-8 character. No check
171 * is made to see if the character found is actually valid other than
172 * it starts with an appropriate byte.
174 * Return value: a pointer to the found character or %NULL
177 g_utf8_find_next_char (const gchar *p,
183 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
186 for (++p; (*p & 0xc0) == 0x80; ++p)
189 return (p == end) ? NULL : (gchar *)p;
194 * @p: a pointer to a position within a UTF-8 encoded string
196 * Finds the previous UTF-8 character in the string before @p.
198 * @p does not have to be at the beginning of a UTF-8 character. No check
199 * is made to see if the character found is actually valid other than
200 * it starts with an appropriate byte. If @p might be the first
201 * character of the string, you must use g_utf8_find_prev_char() instead.
203 * Return value: a pointer to the found character.
206 g_utf8_prev_char (const gchar *p)
211 if ((*p & 0xc0) != 0x80)
218 * @p: pointer to the start of a UTF-8 encoded string.
219 * @max: the maximum number of bytes to examine. If @max
220 * is less than 0, then the string is assumed to be
221 * nul-terminated. If @max is 0, @p will not be examined and
224 * Returns the length of the string in characters.
226 * Return value: the length of the string in characters
229 g_utf8_strlen (const gchar *p,
233 const gchar *start = p;
234 g_return_val_if_fail (p != NULL || max == 0, 0);
240 p = g_utf8_next_char (p);
249 p = g_utf8_next_char (p);
251 while (p - start < max && *p)
254 p = g_utf8_next_char (p);
257 /* only do the last len increment if we got a complete
258 * char (don't count partial chars)
260 if (p - start <= max)
269 * @p: a pointer to Unicode character encoded as UTF-8
271 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
272 * If @p does not point to a valid UTF-8 encoded character, results are
273 * undefined. If you are not sure that the bytes are complete
274 * valid Unicode characters, you should use g_utf8_get_char_validated()
277 * Return value: the resulting character
280 g_utf8_get_char (const gchar *p)
282 int i, mask = 0, len;
284 unsigned char c = (unsigned char) *p;
286 UTF8_COMPUTE (c, mask, len);
289 UTF8_GET (result, p, i, mask, len);
295 * g_utf8_offset_to_pointer:
296 * @str: a UTF-8 encoded string
297 * @offset: a character offset within @str
299 * Converts from an integer character offset to a pointer to a position
302 * Since 2.10, this function allows to pass a negative @offset to
303 * step backwards. It is usually worth stepping backwards from the end
304 * instead of forwards if @offset is in the last fourth of the string,
305 * since moving forward is about 3 times faster than moving backward.
308 * This function doesn't abort when reaching the end of @str. Therefore
309 * you should be sure that @offset is within string boundaries before
310 * calling that function. Call g_utf8_strlen() when unsure.
312 * This limitation exists as this function is called frequently during
313 * text rendering and therefore has to be as fast as possible.
316 * Return value: the resulting pointer
319 g_utf8_offset_to_pointer (const gchar *str,
322 const gchar *s = str;
326 s = g_utf8_next_char (s);
331 /* This nice technique for fast backwards stepping
332 * through a UTF-8 string was dubbed "stutter stepping"
333 * by its inventor, Larry Ewing.
339 while ((*s & 0xc0) == 0x80)
342 offset += g_utf8_pointer_to_offset (s, s1);
350 * g_utf8_pointer_to_offset:
351 * @str: a UTF-8 encoded string
352 * @pos: a pointer to a position within @str
354 * Converts from a pointer to position within a string to a integer
357 * Since 2.10, this function allows @pos to be before @str, and returns
358 * a negative offset in this case.
360 * Return value: the resulting character offset
363 g_utf8_pointer_to_offset (const gchar *str,
366 const gchar *s = str;
370 offset = - g_utf8_pointer_to_offset (pos, str);
374 s = g_utf8_next_char (s);
384 * @dest: buffer to fill with characters from @src
385 * @src: UTF-8 encoded string
386 * @n: character count
388 * Like the standard C strncpy() function, but
389 * copies a given number of characters instead of a given number of
390 * bytes. The @src string must be valid UTF-8 encoded text.
391 * (Use g_utf8_validate() on all text before trying to use UTF-8
392 * utility functions with it.)
394 * Return value: @dest
397 g_utf8_strncpy (gchar *dest,
401 const gchar *s = src;
404 s = g_utf8_next_char(s);
407 strncpy(dest, src, s - src);
412 G_LOCK_DEFINE_STATIC (aliases);
415 get_alias_hash (void)
417 static GHashTable *alias_hash = NULL;
424 alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
426 aliases = _g_locale_get_charset_aliases ();
427 while (*aliases != '\0')
429 const char *canonical;
431 const char **alias_array;
435 aliases += strlen (aliases) + 1;
437 aliases += strlen (aliases) + 1;
439 alias_array = g_hash_table_lookup (alias_hash, canonical);
442 while (alias_array[count])
446 alias_array = g_renew (const char *, alias_array, count + 2);
447 alias_array[count] = alias;
448 alias_array[count + 1] = NULL;
450 g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
459 /* As an abuse of the alias table, the following routines gets
460 * the charsets that are aliases for the canonical name.
462 G_GNUC_INTERNAL const char **
463 _g_charset_get_aliases (const char *canonical_name)
465 GHashTable *alias_hash = get_alias_hash ();
467 return g_hash_table_lookup (alias_hash, canonical_name);
471 g_utf8_get_charset_internal (const char *raw_data,
474 const char *charset = getenv("CHARSET");
476 if (charset && *charset)
480 if (charset && strstr (charset, "UTF-8"))
486 /* The libcharset code tries to be thread-safe without
487 * a lock, but has a memory leak and a missing memory
488 * barrier, so we lock for it
491 charset = _g_locale_charset_unalias (raw_data);
494 if (charset && *charset)
498 if (charset && strstr (charset, "UTF-8"))
504 /* Assume this for compatibility at present. */
510 typedef struct _GCharsetCache GCharsetCache;
512 struct _GCharsetCache {
519 charset_cache_free (gpointer data)
521 GCharsetCache *cache = data;
523 g_free (cache->charset);
529 * @charset: return location for character set name
531 * Obtains the character set for the <link linkend="setlocale">current
532 * locale</link>; you might use this character set as an argument to
533 * g_convert(), to convert from the current locale's encoding to some
534 * other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8()
535 * are nice shortcuts, though.)
537 * On Windows the character set returned by this function is the
538 * so-called system default ANSI code-page. That is the character set
539 * used by the "narrow" versions of C library and Win32 functions that
540 * handle file names. It might be different from the character set
541 * used by the C library's current locale.
543 * The return value is %TRUE if the locale's encoding is UTF-8, in that
544 * case you can perhaps avoid calling g_convert().
546 * The string returned in @charset is not allocated, and should not be
549 * Return value: %TRUE if the returned charset is UTF-8
552 g_get_charset (G_CONST_RETURN char **charset)
554 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
555 GCharsetCache *cache = g_static_private_get (&cache_private);
560 cache = g_new0 (GCharsetCache, 1);
561 g_static_private_set (&cache_private, cache, charset_cache_free);
564 raw = _g_locale_charset_raw ();
566 if (!(cache->raw && strcmp (cache->raw, raw) == 0))
568 const gchar *new_charset;
571 g_free (cache->charset);
572 cache->raw = g_strdup (raw);
573 cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
574 cache->charset = g_strdup (new_charset);
578 *charset = cache->charset;
580 return cache->is_utf8;
587 * @c: a Unicode character code
588 * @outbuf: output buffer, must have at least 6 bytes of space.
589 * If %NULL, the length will be computed and returned
590 * and nothing will be written to @outbuf.
592 * Converts a single character to UTF-8.
594 * Return value: number of bytes written
597 g_unichar_to_utf8 (gunichar c,
600 /* If this gets modified, also update the copy in g_string_insert_unichar() */
615 else if (c < 0x10000)
620 else if (c < 0x200000)
625 else if (c < 0x4000000)
638 for (i = len - 1; i > 0; --i)
640 outbuf[i] = (c & 0x3f) | 0x80;
643 outbuf[0] = c | first;
651 * @p: a nul-terminated UTF-8 encoded string
652 * @len: the maximum length of @p
653 * @c: a Unicode character
655 * Finds the leftmost occurrence of the given Unicode character
656 * in a UTF-8 encoded string, while limiting the search to @len bytes.
657 * If @len is -1, allow unbounded search.
659 * Return value: %NULL if the string does not contain the character,
660 * otherwise, a pointer to the start of the leftmost occurrence of
661 * the character in the string.
664 g_utf8_strchr (const char *p,
670 gint charlen = g_unichar_to_utf8 (c, ch);
673 return g_strstr_len (p, len, ch);
679 * @p: a nul-terminated UTF-8 encoded string
680 * @len: the maximum length of @p
681 * @c: a Unicode character
683 * Find the rightmost occurrence of the given Unicode character
684 * in a UTF-8 encoded string, while limiting the search to @len bytes.
685 * If @len is -1, allow unbounded search.
687 * Return value: %NULL if the string does not contain the character,
688 * otherwise, a pointer to the start of the rightmost occurrence of the
689 * character in the string.
692 g_utf8_strrchr (const char *p,
698 gint charlen = g_unichar_to_utf8 (c, ch);
701 return g_strrstr_len (p, len, ch);
705 /* Like g_utf8_get_char, but take a maximum length
706 * and return (gunichar)-2 on incomplete trailing character
708 static inline gunichar
709 g_utf8_get_char_extended (const gchar *p,
713 gunichar wc = (guchar) *p;
753 if (max_len >= 0 && len > max_len)
755 for (i = 1; i < max_len; i++)
757 if ((((guchar *)p)[i] & 0xc0) != 0x80)
763 for (i = 1; i < len; ++i)
765 gunichar ch = ((guchar *)p)[i];
767 if ((ch & 0xc0) != 0x80)
779 if (UTF8_LENGTH(wc) != len)
786 * g_utf8_get_char_validated:
787 * @p: a pointer to Unicode character encoded as UTF-8
788 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
789 * if @p is nul-terminated
791 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
792 * This function checks for incomplete characters, for invalid characters
793 * such as characters that are out of the range of Unicode, and for
794 * overlong encodings of valid characters.
796 * Return value: the resulting character. If @p points to a partial
797 * sequence at the end of a string that could begin a valid
798 * character (or if @max_len is zero), returns (gunichar)-2;
799 * otherwise, if @p does not point to a valid UTF-8 encoded
800 * Unicode character, returns (gunichar)-1.
803 g_utf8_get_char_validated (const gchar *p,
811 result = g_utf8_get_char_extended (p, max_len);
813 if (result & 0x80000000)
815 else if (!UNICODE_VALID (result))
822 * g_utf8_to_ucs4_fast:
823 * @str: a UTF-8 encoded string
824 * @len: the maximum length of @str to use, in bytes. If @len < 0,
825 * then the string is nul-terminated.
826 * @items_written: location to store the number of characters in the
829 * Convert a string from UTF-8 to a 32-bit fixed width
830 * representation as UCS-4, assuming valid UTF-8 input.
831 * This function is roughly twice as fast as g_utf8_to_ucs4()
832 * but does no error checking on the input.
834 * Return value: a pointer to a newly allocated UCS-4 string.
835 * This value must be freed with g_free().
838 g_utf8_to_ucs4_fast (const gchar *str,
840 glong *items_written)
847 g_return_val_if_fail (str != NULL, NULL);
855 p = g_utf8_next_char (p);
861 while (p < str + len && *p)
863 p = g_utf8_next_char (p);
868 result = g_new (gunichar, n_chars + 1);
871 for (i=0; i < n_chars; i++)
873 gunichar wc = ((unsigned char *)p)[0];
908 for (j = 1; j < charlen; j++)
911 wc |= ((unsigned char *)p)[j] & 0x3f;
928 * @str: a UTF-8 encoded string
929 * @len: the maximum length of @str to use, in bytes. If @len < 0,
930 * then the string is nul-terminated.
931 * @items_read: location to store number of bytes read, or %NULL.
932 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
933 * returned in case @str contains a trailing partial
934 * character. If an error occurs then the index of the
935 * invalid input is stored here.
936 * @items_written: location to store number of characters written or %NULL.
937 * The value here stored does not include the trailing 0
939 * @error: location to store the error occuring, or %NULL to ignore
940 * errors. Any of the errors in #GConvertError other than
941 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
943 * Convert a string from UTF-8 to a 32-bit fixed width
944 * representation as UCS-4. A trailing 0 will be added to the
945 * string after the converted text.
947 * Return value: a pointer to a newly allocated UCS-4 string.
948 * This value must be freed with g_free(). If an
949 * error occurs, %NULL will be returned and
953 g_utf8_to_ucs4 (const gchar *str,
956 glong *items_written,
959 gunichar *result = NULL;
965 while ((len < 0 || str + len - in > 0) && *in)
967 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
970 if (wc == (gunichar)-2)
975 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
976 _("Partial character sequence at end of input"));
979 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
980 _("Invalid byte sequence in conversion input"));
987 in = g_utf8_next_char (in);
990 result = g_new (gunichar, n_chars + 1);
993 for (i=0; i < n_chars; i++)
995 result[i] = g_utf8_get_char (in);
996 in = g_utf8_next_char (in);
1001 *items_written = n_chars;
1005 *items_read = in - str;
1012 * @str: a UCS-4 encoded string
1013 * @len: the maximum length (number of characters) of @str to use.
1014 * If @len < 0, then the string is nul-terminated.
1015 * @items_read: location to store number of characters read, or %NULL.
1016 * @items_written: location to store number of bytes written or %NULL.
1017 * The value here stored does not include the trailing 0
1019 * @error: location to store the error occuring, or %NULL to ignore
1020 * errors. Any of the errors in #GConvertError other than
1021 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1023 * Convert a string from a 32-bit fixed width representation as UCS-4.
1024 * to UTF-8. The result will be terminated with a 0 byte.
1026 * Return value: a pointer to a newly allocated UTF-8 string.
1027 * This value must be freed with g_free(). If an
1028 * error occurs, %NULL will be returned and
1029 * @error set. In that case, @items_read will be
1030 * set to the position of the first invalid input
1034 g_ucs4_to_utf8 (const gunichar *str,
1037 glong *items_written,
1041 gchar *result = NULL;
1046 for (i = 0; len < 0 || i < len ; i++)
1051 if (str[i] >= 0x80000000)
1053 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1054 _("Character out of range for UTF-8"));
1058 result_length += UTF8_LENGTH (str[i]);
1061 result = g_malloc (result_length + 1);
1065 while (p < result + result_length)
1066 p += g_unichar_to_utf8 (str[i++], p);
1071 *items_written = p - result;
1080 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1084 * @str: a UTF-16 encoded string
1085 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1086 * If @len < 0, then the string is nul-terminated.
1087 * @items_read: location to store number of words read, or %NULL.
1088 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1089 * returned in case @str contains a trailing partial
1090 * character. If an error occurs then the index of the
1091 * invalid input is stored here.
1092 * @items_written: location to store number of bytes written, or %NULL.
1093 * The value stored here does not include the trailing
1095 * @error: location to store the error occuring, or %NULL to ignore
1096 * errors. Any of the errors in #GConvertError other than
1097 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1099 * Convert a string from UTF-16 to UTF-8. The result will be
1100 * terminated with a 0 byte.
1102 * Note that the input is expected to be already in native endianness,
1103 * an initial byte-order-mark character is not handled specially.
1104 * g_convert() can be used to convert a byte buffer of UTF-16 data of
1105 * ambiguous endianess.
1107 * Further note that this function does not validate the result
1108 * string; it may e.g. include embedded NUL characters. The only
1109 * validation done by this function is to ensure that the input can
1110 * be correctly interpreted as UTF-16, i.e. it doesn't contain
1111 * things unpaired surrogates.
1113 * Return value: a pointer to a newly allocated UTF-8 string.
1114 * This value must be freed with g_free(). If an
1115 * error occurs, %NULL will be returned and
1119 g_utf16_to_utf8 (const gunichar2 *str,
1122 glong *items_written,
1125 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1128 const gunichar2 *in;
1130 gchar *result = NULL;
1132 gunichar high_surrogate;
1134 g_return_val_if_fail (str != NULL, NULL);
1139 while ((len < 0 || in - str < len) && *in)
1144 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1148 wc = SURROGATE_VALUE (high_surrogate, c);
1153 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1154 _("Invalid sequence in conversion input"));
1162 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163 _("Invalid sequence in conversion input"));
1167 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1176 /********** DIFFERENT for UTF8/UCS4 **********/
1177 n_bytes += UTF8_LENGTH (wc);
1183 if (high_surrogate && !items_read)
1185 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1186 _("Partial character sequence at end of input"));
1190 /* At this point, everything is valid, and we just need to convert
1192 /********** DIFFERENT for UTF8/UCS4 **********/
1193 result = g_malloc (n_bytes + 1);
1198 while (out < result + n_bytes)
1203 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1205 wc = SURROGATE_VALUE (high_surrogate, c);
1208 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1216 /********** DIFFERENT for UTF8/UCS4 **********/
1217 out += g_unichar_to_utf8 (wc, out);
1223 /********** DIFFERENT for UTF8/UCS4 **********/
1227 /********** DIFFERENT for UTF8/UCS4 **********/
1228 *items_written = out - result;
1232 *items_read = in - str;
1239 * @str: a UTF-16 encoded string
1240 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1241 * If @len < 0, then the string is nul-terminated.
1242 * @items_read: location to store number of words read, or %NULL.
1243 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1244 * returned in case @str contains a trailing partial
1245 * character. If an error occurs then the index of the
1246 * invalid input is stored here.
1247 * @items_written: location to store number of characters written, or %NULL.
1248 * The value stored here does not include the trailing
1250 * @error: location to store the error occuring, or %NULL to ignore
1251 * errors. Any of the errors in #GConvertError other than
1252 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1254 * Convert a string from UTF-16 to UCS-4. The result will be
1257 * Return value: a pointer to a newly allocated UCS-4 string.
1258 * This value must be freed with g_free(). If an
1259 * error occurs, %NULL will be returned and
1263 g_utf16_to_ucs4 (const gunichar2 *str,
1266 glong *items_written,
1269 const gunichar2 *in;
1271 gchar *result = NULL;
1273 gunichar high_surrogate;
1275 g_return_val_if_fail (str != NULL, NULL);
1280 while ((len < 0 || in - str < len) && *in)
1285 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1289 wc = SURROGATE_VALUE (high_surrogate, c);
1294 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1295 _("Invalid sequence in conversion input"));
1303 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1304 _("Invalid sequence in conversion input"));
1308 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1317 /********** DIFFERENT for UTF8/UCS4 **********/
1318 n_bytes += sizeof (gunichar);
1324 if (high_surrogate && !items_read)
1326 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1327 _("Partial character sequence at end of input"));
1331 /* At this point, everything is valid, and we just need to convert
1333 /********** DIFFERENT for UTF8/UCS4 **********/
1334 result = g_malloc (n_bytes + 4);
1339 while (out < result + n_bytes)
1344 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1346 wc = SURROGATE_VALUE (high_surrogate, c);
1349 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1357 /********** DIFFERENT for UTF8/UCS4 **********/
1358 *(gunichar *)out = wc;
1359 out += sizeof (gunichar);
1365 /********** DIFFERENT for UTF8/UCS4 **********/
1366 *(gunichar *)out = 0;
1369 /********** DIFFERENT for UTF8/UCS4 **********/
1370 *items_written = (out - result) / sizeof (gunichar);
1374 *items_read = in - str;
1376 return (gunichar *)result;
1381 * @str: a UTF-8 encoded string
1382 * @len: the maximum length (number of bytes) of @str to use.
1383 * If @len < 0, then the string is nul-terminated.
1384 * @items_read: location to store number of bytes read, or %NULL.
1385 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1386 * returned in case @str contains a trailing partial
1387 * character. If an error occurs then the index of the
1388 * invalid input is stored here.
1389 * @items_written: location to store number of <type>gunichar2</type> written,
1391 * The value stored here does not include the trailing 0.
1392 * @error: location to store the error occuring, or %NULL to ignore
1393 * errors. Any of the errors in #GConvertError other than
1394 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1396 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1397 * added to the result after the converted text.
1399 * Return value: a pointer to a newly allocated UTF-16 string.
1400 * This value must be freed with g_free(). If an
1401 * error occurs, %NULL will be returned and
1405 g_utf8_to_utf16 (const gchar *str,
1408 glong *items_written,
1411 gunichar2 *result = NULL;
1416 g_return_val_if_fail (str != NULL, NULL);
1420 while ((len < 0 || str + len - in > 0) && *in)
1422 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1423 if (wc & 0x80000000)
1425 if (wc == (gunichar)-2)
1430 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1431 _("Partial character sequence at end of input"));
1434 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1435 _("Invalid byte sequence in conversion input"));
1442 else if (wc < 0xe000)
1444 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1445 _("Invalid sequence in conversion input"));
1449 else if (wc < 0x10000)
1451 else if (wc < 0x110000)
1455 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1456 _("Character out of range for UTF-16"));
1461 in = g_utf8_next_char (in);
1464 result = g_new (gunichar2, n16 + 1);
1467 for (i = 0; i < n16;)
1469 gunichar wc = g_utf8_get_char (in);
1477 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1478 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1481 in = g_utf8_next_char (in);
1487 *items_written = n16;
1491 *items_read = in - str;
1498 * @str: a UCS-4 encoded string
1499 * @len: the maximum length (number of characters) of @str to use.
1500 * If @len < 0, then the string is nul-terminated.
1501 * @items_read: location to store number of bytes read, or %NULL.
1502 * If an error occurs then the index of the invalid input
1504 * @items_written: location to store number of <type>gunichar2</type>
1505 * written, or %NULL. The value stored here does not
1506 * include the trailing 0.
1507 * @error: location to store the error occuring, or %NULL to ignore
1508 * errors. Any of the errors in #GConvertError other than
1509 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1511 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1512 * added to the result after the converted text.
1514 * Return value: a pointer to a newly allocated UTF-16 string.
1515 * This value must be freed with g_free(). If an
1516 * error occurs, %NULL will be returned and
1520 g_ucs4_to_utf16 (const gunichar *str,
1523 glong *items_written,
1526 gunichar2 *result = NULL;
1532 while ((len < 0 || i < len) && str[i])
1534 gunichar wc = str[i];
1538 else if (wc < 0xe000)
1540 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1541 _("Invalid sequence in conversion input"));
1545 else if (wc < 0x10000)
1547 else if (wc < 0x110000)
1551 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1552 _("Character out of range for UTF-16"));
1560 result = g_new (gunichar2, n16 + 1);
1562 for (i = 0, j = 0; j < n16; i++)
1564 gunichar wc = str[i];
1572 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1573 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1579 *items_written = n16;
1588 #define CONTINUATION_CHAR \
1590 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1593 val |= (*(guchar *)p) & 0x3f; \
1596 static const gchar *
1597 fast_validate (const char *str)
1604 for (p = str; *p; p++)
1606 if (*(guchar *)p < 128)
1613 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1615 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1618 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1623 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1626 val = *(guchar *)p & 0x0f;
1629 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1632 val = *(guchar *)p & 0x07;
1645 if (G_UNLIKELY (val < min))
1648 if (G_UNLIKELY (!UNICODE_VALID(val)))
1662 static const gchar *
1663 fast_validate_len (const char *str,
1671 g_assert (max_len >= 0);
1673 for (p = str; ((p - str) < max_len) && *p; p++)
1675 if (*(guchar *)p < 128)
1682 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1684 if (G_UNLIKELY (max_len - (p - str) < 2))
1687 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1690 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1695 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1697 if (G_UNLIKELY (max_len - (p - str) < 3))
1701 val = *(guchar *)p & 0x0f;
1704 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1706 if (G_UNLIKELY (max_len - (p - str) < 4))
1710 val = *(guchar *)p & 0x07;
1723 if (G_UNLIKELY (val < min))
1725 if (G_UNLIKELY (!UNICODE_VALID(val)))
1741 * @str: a pointer to character data
1742 * @max_len: max bytes to validate, or -1 to go until NUL
1743 * @end: return location for end of valid data
1745 * Validates UTF-8 encoded text. @str is the text to validate;
1746 * if @str is nul-terminated, then @max_len can be -1, otherwise
1747 * @max_len should be the number of bytes to validate.
1748 * If @end is non-%NULL, then the end of the valid range
1749 * will be stored there (i.e. the start of the first invalid
1750 * character if some bytes were invalid, or the end of the text
1751 * being validated otherwise).
1753 * Note that g_utf8_validate() returns %FALSE if @max_len is
1754 * positive and NUL is met before @max_len bytes have been read.
1756 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1757 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1758 * so data read from a file or the network should be checked
1759 * with g_utf8_validate() before doing anything else with it.
1761 * Return value: %TRUE if the text was valid UTF-8
1764 g_utf8_validate (const char *str,
1772 p = fast_validate (str);
1774 p = fast_validate_len (str, max_len);
1779 if ((max_len >= 0 && p != str + max_len) ||
1780 (max_len < 0 && *p != '\0'))
1787 * g_unichar_validate:
1788 * @ch: a Unicode character
1790 * Checks whether @ch is a valid Unicode character. Some possible
1791 * integer values of @ch will not be valid. 0 is considered a valid
1792 * character, though it's normally a string terminator.
1794 * Return value: %TRUE if @ch is a valid Unicode character
1797 g_unichar_validate (gunichar ch)
1799 return UNICODE_VALID (ch);
1803 * g_utf8_strreverse:
1804 * @str: a UTF-8 encoded string
1805 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1806 * then the string is nul-terminated.
1808 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1809 * (Use g_utf8_validate() on all text before trying to use UTF-8
1810 * utility functions with it.)
1812 * This function is intended for programmatic uses of reversed strings.
1813 * It pays no attention to decomposed characters, combining marks, byte
1814 * order marks, directional indicators (LRM, LRO, etc) and similar
1815 * characters which might need special handling when reversing a string
1816 * for display purposes.
1818 * Note that unlike g_strreverse(), this function returns
1819 * newly-allocated memory, which should be freed with g_free() when
1822 * Returns: a newly-allocated string which is the reverse of @str.
1827 g_utf8_strreverse (const gchar *str,
1836 result = g_new (gchar, len + 1);
1841 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1843 for (m = r; skip; skip--)
1853 _g_utf8_make_valid (const gchar *name)
1856 const gchar *remainder, *invalid;
1857 gint remaining_bytes, valid_bytes;
1859 g_return_val_if_fail (name != NULL, NULL);
1863 remaining_bytes = strlen (name);
1865 while (remaining_bytes != 0)
1867 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1869 valid_bytes = invalid - remainder;
1872 string = g_string_sized_new (remaining_bytes);
1874 g_string_append_len (string, remainder, valid_bytes);
1875 /* append U+FFFD REPLACEMENT CHARACTER */
1876 g_string_append (string, "\357\277\275");
1878 remaining_bytes -= valid_bytes + 1;
1879 remainder = invalid + 1;
1883 return g_strdup (name);
1885 g_string_append (string, remainder);
1887 g_assert (g_utf8_validate (string->str, -1, NULL));
1889 return g_string_free (string, FALSE);
1893 #define __G_UTF8_C__
1894 #include "galiasdef.c"