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.
292 * This function doesn't abort when reaching the end of @str. Therefore
293 * you should be sure that @offset is within string boundaries before
294 * calling that function. Call g_utf8_strlen() when unsure.
296 * This limitation exists as this function is called frequently during
297 * text rendering and therefore has to be as fast as possible.
300 * Return value: the resulting pointer
303 g_utf8_offset_to_pointer (const gchar *str,
306 const gchar *s = str;
310 s = g_utf8_next_char (s);
315 /* This nice technique for fast backwards stepping
316 * through a UTF-8 string was dubbed "stutter stepping"
317 * by its inventor, Larry Ewing.
323 while ((*s & 0xc0) == 0x80)
326 offset += g_utf8_pointer_to_offset (s, s1);
334 * g_utf8_pointer_to_offset:
335 * @str: a UTF-8 encoded string
336 * @pos: a pointer to a position within @str
338 * Converts from a pointer to position within a string to a integer
341 * Since 2.10, this function allows @pos to be before @str, and returns
342 * a negative offset in this case.
344 * Return value: the resulting character offset
347 g_utf8_pointer_to_offset (const gchar *str,
350 const gchar *s = str;
354 offset = - g_utf8_pointer_to_offset (pos, str);
358 s = g_utf8_next_char (s);
368 * @dest: buffer to fill with characters from @src
369 * @src: UTF-8 encoded string
370 * @n: character count
372 * Like the standard C strncpy() function, but
373 * copies a given number of characters instead of a given number of
374 * bytes. The @src string must be valid UTF-8 encoded text.
375 * (Use g_utf8_validate() on all text before trying to use UTF-8
376 * utility functions with it.)
378 * Return value: @dest
381 g_utf8_strncpy (gchar *dest,
385 const gchar *s = src;
388 s = g_utf8_next_char(s);
391 strncpy(dest, src, s - src);
396 G_LOCK_DEFINE_STATIC (aliases);
399 get_alias_hash (void)
401 static GHashTable *alias_hash = NULL;
408 alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
410 aliases = _g_locale_get_charset_aliases ();
411 while (*aliases != '\0')
413 const char *canonical;
415 const char **alias_array;
419 aliases += strlen (aliases) + 1;
421 aliases += strlen (aliases) + 1;
423 alias_array = g_hash_table_lookup (alias_hash, canonical);
426 while (alias_array[count])
430 alias_array = g_renew (const char *, alias_array, count + 2);
431 alias_array[count] = alias;
432 alias_array[count + 1] = NULL;
434 g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
443 /* As an abuse of the alias table, the following routines gets
444 * the charsets that are aliases for the canonical name.
446 G_GNUC_INTERNAL const char **
447 _g_charset_get_aliases (const char *canonical_name)
449 GHashTable *alias_hash = get_alias_hash ();
451 return g_hash_table_lookup (alias_hash, canonical_name);
455 g_utf8_get_charset_internal (const char *raw_data,
458 const char *charset = getenv("CHARSET");
460 if (charset && *charset)
464 if (charset && strstr (charset, "UTF-8"))
470 /* The libcharset code tries to be thread-safe without
471 * a lock, but has a memory leak and a missing memory
472 * barrier, so we lock for it
475 charset = _g_locale_charset_unalias (raw_data);
478 if (charset && *charset)
482 if (charset && strstr (charset, "UTF-8"))
488 /* Assume this for compatibility at present. */
494 typedef struct _GCharsetCache GCharsetCache;
496 struct _GCharsetCache {
503 charset_cache_free (gpointer data)
505 GCharsetCache *cache = data;
507 g_free (cache->charset);
513 * @charset: return location for character set name
515 * Obtains the character set for the <link linkend="setlocale">current
516 * locale</link>; you might use this character set as an argument to
517 * g_convert(), to convert from the current locale's encoding to some
518 * other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8()
519 * are nice shortcuts, though.)
521 * On Windows the character set returned by this function is the
522 * so-called system default ANSI code-page. That is the character set
523 * used by the "narrow" versions of C library and Win32 functions that
524 * handle file names. It might be different from the character set
525 * used by the C library's current locale.
527 * The return value is %TRUE if the locale's encoding is UTF-8, in that
528 * case you can perhaps avoid calling g_convert().
530 * The string returned in @charset is not allocated, and should not be
533 * Return value: %TRUE if the returned charset is UTF-8
536 g_get_charset (G_CONST_RETURN char **charset)
538 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
539 GCharsetCache *cache = g_static_private_get (&cache_private);
544 cache = g_new0 (GCharsetCache, 1);
545 g_static_private_set (&cache_private, cache, charset_cache_free);
548 raw = _g_locale_charset_raw ();
550 if (!(cache->raw && strcmp (cache->raw, raw) == 0))
552 const gchar *new_charset;
555 g_free (cache->charset);
556 cache->raw = g_strdup (raw);
557 cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
558 cache->charset = g_strdup (new_charset);
562 *charset = cache->charset;
564 return cache->is_utf8;
571 * @c: a Unicode character code
572 * @outbuf: output buffer, must have at least 6 bytes of space.
573 * If %NULL, the length will be computed and returned
574 * and nothing will be written to @outbuf.
576 * Converts a single character to UTF-8.
578 * Return value: number of bytes written
581 g_unichar_to_utf8 (gunichar c,
584 /* If this gets modified, also update the copy in g_string_insert_unichar() */
599 else if (c < 0x10000)
604 else if (c < 0x200000)
609 else if (c < 0x4000000)
622 for (i = len - 1; i > 0; --i)
624 outbuf[i] = (c & 0x3f) | 0x80;
627 outbuf[0] = c | first;
635 * @p: a nul-terminated UTF-8 encoded string
636 * @len: the maximum length of @p
637 * @c: a Unicode character
639 * Finds the leftmost occurrence of the given Unicode character
640 * in a UTF-8 encoded string, while limiting the search to @len bytes.
641 * If @len is -1, allow unbounded search.
643 * Return value: %NULL if the string does not contain the character,
644 * otherwise, a pointer to the start of the leftmost occurrence of
645 * the character in the string.
648 g_utf8_strchr (const char *p,
654 gint charlen = g_unichar_to_utf8 (c, ch);
657 return g_strstr_len (p, len, ch);
663 * @p: a nul-terminated UTF-8 encoded string
664 * @len: the maximum length of @p
665 * @c: a Unicode character
667 * Find the rightmost occurrence of the given Unicode character
668 * in a UTF-8 encoded string, while limiting the search to @len bytes.
669 * If @len is -1, allow unbounded search.
671 * Return value: %NULL if the string does not contain the character,
672 * otherwise, a pointer to the start of the rightmost occurrence of the
673 * character in the string.
676 g_utf8_strrchr (const char *p,
682 gint charlen = g_unichar_to_utf8 (c, ch);
685 return g_strrstr_len (p, len, ch);
689 /* Like g_utf8_get_char, but take a maximum length
690 * and return (gunichar)-2 on incomplete trailing character
692 static inline gunichar
693 g_utf8_get_char_extended (const gchar *p,
697 gunichar wc = (guchar) *p;
737 if (max_len >= 0 && len > max_len)
739 for (i = 1; i < max_len; i++)
741 if ((((guchar *)p)[i] & 0xc0) != 0x80)
747 for (i = 1; i < len; ++i)
749 gunichar ch = ((guchar *)p)[i];
751 if ((ch & 0xc0) != 0x80)
763 if (UTF8_LENGTH(wc) != len)
770 * g_utf8_get_char_validated:
771 * @p: a pointer to Unicode character encoded as UTF-8
772 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
773 * if @p is nul-terminated
775 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
776 * This function checks for incomplete characters, for invalid characters
777 * such as characters that are out of the range of Unicode, and for
778 * overlong encodings of valid characters.
780 * Return value: the resulting character. If @p points to a partial
781 * sequence at the end of a string that could begin a valid
782 * character (or if @max_len is zero), returns (gunichar)-2;
783 * otherwise, if @p does not point to a valid UTF-8 encoded
784 * Unicode character, returns (gunichar)-1.
787 g_utf8_get_char_validated (const gchar *p,
795 result = g_utf8_get_char_extended (p, max_len);
797 if (result & 0x80000000)
799 else if (!UNICODE_VALID (result))
806 * g_utf8_to_ucs4_fast:
807 * @str: a UTF-8 encoded string
808 * @len: the maximum length of @str to use, in bytes. If @len < 0,
809 * then the string is nul-terminated.
810 * @items_written: location to store the number of characters in the
813 * Convert a string from UTF-8 to a 32-bit fixed width
814 * representation as UCS-4, assuming valid UTF-8 input.
815 * This function is roughly twice as fast as g_utf8_to_ucs4()
816 * but does no error checking on the input.
818 * Return value: a pointer to a newly allocated UCS-4 string.
819 * This value must be freed with g_free().
822 g_utf8_to_ucs4_fast (const gchar *str,
824 glong *items_written)
831 g_return_val_if_fail (str != NULL, NULL);
839 p = g_utf8_next_char (p);
845 while (p < str + len && *p)
847 p = g_utf8_next_char (p);
852 result = g_new (gunichar, n_chars + 1);
855 for (i=0; i < n_chars; i++)
857 gunichar wc = ((unsigned char *)p)[0];
892 for (j = 1; j < charlen; j++)
895 wc |= ((unsigned char *)p)[j] & 0x3f;
912 * @str: a UTF-8 encoded string
913 * @len: the maximum length of @str to use, in bytes. If @len < 0,
914 * then the string is nul-terminated.
915 * @items_read: location to store number of bytes read, or %NULL.
916 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
917 * returned in case @str contains a trailing partial
918 * character. If an error occurs then the index of the
919 * invalid input is stored here.
920 * @items_written: location to store number of characters written or %NULL.
921 * The value here stored does not include the trailing 0
923 * @error: location to store the error occuring, or %NULL to ignore
924 * errors. Any of the errors in #GConvertError other than
925 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
927 * Convert a string from UTF-8 to a 32-bit fixed width
928 * representation as UCS-4. A trailing 0 will be added to the
929 * string after the converted text.
931 * Return value: a pointer to a newly allocated UCS-4 string.
932 * This value must be freed with g_free(). If an
933 * error occurs, %NULL will be returned and
937 g_utf8_to_ucs4 (const gchar *str,
940 glong *items_written,
943 gunichar *result = NULL;
949 while ((len < 0 || str + len - in > 0) && *in)
951 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
954 if (wc == (gunichar)-2)
959 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
960 _("Partial character sequence at end of input"));
963 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
964 _("Invalid byte sequence in conversion input"));
971 in = g_utf8_next_char (in);
974 result = g_new (gunichar, n_chars + 1);
977 for (i=0; i < n_chars; i++)
979 result[i] = g_utf8_get_char (in);
980 in = g_utf8_next_char (in);
985 *items_written = n_chars;
989 *items_read = in - str;
996 * @str: a UCS-4 encoded string
997 * @len: the maximum length (number of characters) of @str to use.
998 * If @len < 0, then the string is nul-terminated.
999 * @items_read: location to store number of characters read, or %NULL.
1000 * @items_written: location to store number of bytes written or %NULL.
1001 * The value here stored does not include the trailing 0
1003 * @error: location to store the error occuring, or %NULL to ignore
1004 * errors. Any of the errors in #GConvertError other than
1005 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1007 * Convert a string from a 32-bit fixed width representation as UCS-4.
1008 * to UTF-8. The result will be terminated with a 0 byte.
1010 * Return value: a pointer to a newly allocated UTF-8 string.
1011 * This value must be freed with g_free(). If an
1012 * error occurs, %NULL will be returned and
1013 * @error set. In that case, @items_read will be
1014 * set to the position of the first invalid input
1018 g_ucs4_to_utf8 (const gunichar *str,
1021 glong *items_written,
1025 gchar *result = NULL;
1030 for (i = 0; len < 0 || i < len ; i++)
1035 if (str[i] >= 0x80000000)
1037 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1038 _("Character out of range for UTF-8"));
1042 result_length += UTF8_LENGTH (str[i]);
1045 result = g_malloc (result_length + 1);
1049 while (p < result + result_length)
1050 p += g_unichar_to_utf8 (str[i++], p);
1055 *items_written = p - result;
1064 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1068 * @str: a UTF-16 encoded string
1069 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1070 * If @len < 0, then the string is nul-terminated.
1071 * @items_read: location to store number of words read, or %NULL.
1072 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1073 * returned in case @str contains a trailing partial
1074 * character. If an error occurs then the index of the
1075 * invalid input is stored here.
1076 * @items_written: location to store number of bytes written, or %NULL.
1077 * The value stored here does not include the trailing
1079 * @error: location to store the error occuring, or %NULL to ignore
1080 * errors. Any of the errors in #GConvertError other than
1081 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1083 * Convert a string from UTF-16 to UTF-8. The result will be
1084 * terminated with a 0 byte.
1086 * Note that the input is expected to be already in native endianness,
1087 * an initial byte-order-mark character is not handled specially.
1088 * g_convert() can be used to convert a byte buffer of UTF-16 data of
1089 * ambiguous endianess.
1091 * Further note that this function does not validate the result
1092 * string; it may e.g. include embedded NUL characters. The only
1093 * validation done by this function is to ensure that the input can
1094 * be correctly interpreted as UTF-16, i.e. it doesn't contain
1095 * things unpaired surrogates.
1097 * Return value: a pointer to a newly allocated UTF-8 string.
1098 * This value must be freed with g_free(). If an
1099 * error occurs, %NULL will be returned and
1103 g_utf16_to_utf8 (const gunichar2 *str,
1106 glong *items_written,
1109 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1112 const gunichar2 *in;
1114 gchar *result = NULL;
1116 gunichar high_surrogate;
1118 g_return_val_if_fail (str != NULL, NULL);
1123 while ((len < 0 || in - str < len) && *in)
1128 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1132 wc = SURROGATE_VALUE (high_surrogate, c);
1137 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1138 _("Invalid sequence in conversion input"));
1146 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1147 _("Invalid sequence in conversion input"));
1151 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1160 /********** DIFFERENT for UTF8/UCS4 **********/
1161 n_bytes += UTF8_LENGTH (wc);
1167 if (high_surrogate && !items_read)
1169 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1170 _("Partial character sequence at end of input"));
1174 /* At this point, everything is valid, and we just need to convert
1176 /********** DIFFERENT for UTF8/UCS4 **********/
1177 result = g_malloc (n_bytes + 1);
1182 while (out < result + n_bytes)
1187 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1189 wc = SURROGATE_VALUE (high_surrogate, c);
1192 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1200 /********** DIFFERENT for UTF8/UCS4 **********/
1201 out += g_unichar_to_utf8 (wc, out);
1207 /********** DIFFERENT for UTF8/UCS4 **********/
1211 /********** DIFFERENT for UTF8/UCS4 **********/
1212 *items_written = out - result;
1216 *items_read = in - str;
1223 * @str: a UTF-16 encoded string
1224 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1225 * If @len < 0, then the string is nul-terminated.
1226 * @items_read: location to store number of words read, or %NULL.
1227 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1228 * returned in case @str contains a trailing partial
1229 * character. If an error occurs then the index of the
1230 * invalid input is stored here.
1231 * @items_written: location to store number of characters written, or %NULL.
1232 * The value stored here does not include the trailing
1234 * @error: location to store the error occuring, or %NULL to ignore
1235 * errors. Any of the errors in #GConvertError other than
1236 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1238 * Convert a string from UTF-16 to UCS-4. The result will be
1241 * Return value: a pointer to a newly allocated UCS-4 string.
1242 * This value must be freed with g_free(). If an
1243 * error occurs, %NULL will be returned and
1247 g_utf16_to_ucs4 (const gunichar2 *str,
1250 glong *items_written,
1253 const gunichar2 *in;
1255 gchar *result = NULL;
1257 gunichar high_surrogate;
1259 g_return_val_if_fail (str != NULL, NULL);
1264 while ((len < 0 || in - str < len) && *in)
1269 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1273 wc = SURROGATE_VALUE (high_surrogate, c);
1278 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1279 _("Invalid sequence in conversion input"));
1287 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1288 _("Invalid sequence in conversion input"));
1292 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1301 /********** DIFFERENT for UTF8/UCS4 **********/
1302 n_bytes += sizeof (gunichar);
1308 if (high_surrogate && !items_read)
1310 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1311 _("Partial character sequence at end of input"));
1315 /* At this point, everything is valid, and we just need to convert
1317 /********** DIFFERENT for UTF8/UCS4 **********/
1318 result = g_malloc (n_bytes + 4);
1323 while (out < result + n_bytes)
1328 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1330 wc = SURROGATE_VALUE (high_surrogate, c);
1333 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1341 /********** DIFFERENT for UTF8/UCS4 **********/
1342 *(gunichar *)out = wc;
1343 out += sizeof (gunichar);
1349 /********** DIFFERENT for UTF8/UCS4 **********/
1350 *(gunichar *)out = 0;
1353 /********** DIFFERENT for UTF8/UCS4 **********/
1354 *items_written = (out - result) / sizeof (gunichar);
1358 *items_read = in - str;
1360 return (gunichar *)result;
1365 * @str: a UTF-8 encoded string
1366 * @len: the maximum length (number of bytes) of @str to use.
1367 * If @len < 0, then the string is nul-terminated.
1368 * @items_read: location to store number of bytes read, or %NULL.
1369 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1370 * returned in case @str contains a trailing partial
1371 * character. If an error occurs then the index of the
1372 * invalid input is stored here.
1373 * @items_written: location to store number of <type>gunichar2</type> written,
1375 * The value stored here does not include the trailing 0.
1376 * @error: location to store the error occuring, or %NULL to ignore
1377 * errors. Any of the errors in #GConvertError other than
1378 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1380 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1381 * added to the result after the converted text.
1383 * Return value: a pointer to a newly allocated UTF-16 string.
1384 * This value must be freed with g_free(). If an
1385 * error occurs, %NULL will be returned and
1389 g_utf8_to_utf16 (const gchar *str,
1392 glong *items_written,
1395 gunichar2 *result = NULL;
1400 g_return_val_if_fail (str != NULL, NULL);
1404 while ((len < 0 || str + len - in > 0) && *in)
1406 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1407 if (wc & 0x80000000)
1409 if (wc == (gunichar)-2)
1414 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1415 _("Partial character sequence at end of input"));
1418 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1419 _("Invalid byte sequence in conversion input"));
1426 else if (wc < 0xe000)
1428 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1429 _("Invalid sequence in conversion input"));
1433 else if (wc < 0x10000)
1435 else if (wc < 0x110000)
1439 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1440 _("Character out of range for UTF-16"));
1445 in = g_utf8_next_char (in);
1448 result = g_new (gunichar2, n16 + 1);
1451 for (i = 0; i < n16;)
1453 gunichar wc = g_utf8_get_char (in);
1461 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1462 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1465 in = g_utf8_next_char (in);
1471 *items_written = n16;
1475 *items_read = in - str;
1482 * @str: a UCS-4 encoded string
1483 * @len: the maximum length (number of characters) of @str to use.
1484 * If @len < 0, then the string is nul-terminated.
1485 * @items_read: location to store number of bytes read, or %NULL.
1486 * If an error occurs then the index of the invalid input
1488 * @items_written: location to store number of <type>gunichar2</type>
1489 * written, or %NULL. The value stored here does not
1490 * include the trailing 0.
1491 * @error: location to store the error occuring, or %NULL to ignore
1492 * errors. Any of the errors in #GConvertError other than
1493 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1495 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1496 * added to the result after the converted text.
1498 * Return value: a pointer to a newly allocated UTF-16 string.
1499 * This value must be freed with g_free(). If an
1500 * error occurs, %NULL will be returned and
1504 g_ucs4_to_utf16 (const gunichar *str,
1507 glong *items_written,
1510 gunichar2 *result = NULL;
1516 while ((len < 0 || i < len) && str[i])
1518 gunichar wc = str[i];
1522 else if (wc < 0xe000)
1524 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1525 _("Invalid sequence in conversion input"));
1529 else if (wc < 0x10000)
1531 else if (wc < 0x110000)
1535 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1536 _("Character out of range for UTF-16"));
1544 result = g_new (gunichar2, n16 + 1);
1546 for (i = 0, j = 0; j < n16; i++)
1548 gunichar wc = str[i];
1556 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1557 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1563 *items_written = n16;
1572 #define CONTINUATION_CHAR \
1574 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1577 val |= (*(guchar *)p) & 0x3f; \
1580 static const gchar *
1581 fast_validate (const char *str)
1588 for (p = str; *p; p++)
1590 if (*(guchar *)p < 128)
1597 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1599 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1602 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1607 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1610 val = *(guchar *)p & 0x0f;
1613 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1616 val = *(guchar *)p & 0x07;
1629 if (G_UNLIKELY (val < min))
1632 if (G_UNLIKELY (!UNICODE_VALID(val)))
1646 static const gchar *
1647 fast_validate_len (const char *str,
1655 g_assert (max_len >= 0);
1657 for (p = str; ((p - str) < max_len) && *p; p++)
1659 if (*(guchar *)p < 128)
1666 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1668 if (G_UNLIKELY (max_len - (p - str) < 2))
1671 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1674 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1679 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1681 if (G_UNLIKELY (max_len - (p - str) < 3))
1685 val = *(guchar *)p & 0x0f;
1688 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1690 if (G_UNLIKELY (max_len - (p - str) < 4))
1694 val = *(guchar *)p & 0x07;
1707 if (G_UNLIKELY (val < min))
1709 if (G_UNLIKELY (!UNICODE_VALID(val)))
1725 * @str: a pointer to character data
1726 * @max_len: max bytes to validate, or -1 to go until NUL
1727 * @end: return location for end of valid data
1729 * Validates UTF-8 encoded text. @str is the text to validate;
1730 * if @str is nul-terminated, then @max_len can be -1, otherwise
1731 * @max_len should be the number of bytes to validate.
1732 * If @end is non-%NULL, then the end of the valid range
1733 * will be stored there (i.e. the start of the first invalid
1734 * character if some bytes were invalid, or the end of the text
1735 * being validated otherwise).
1737 * Note that g_utf8_validate() returns %FALSE if @max_len is
1738 * positive and NUL is met before @max_len bytes have been read.
1740 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1741 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1742 * so data read from a file or the network should be checked
1743 * with g_utf8_validate() before doing anything else with it.
1745 * Return value: %TRUE if the text was valid UTF-8
1748 g_utf8_validate (const char *str,
1756 p = fast_validate (str);
1758 p = fast_validate_len (str, max_len);
1763 if ((max_len >= 0 && p != str + max_len) ||
1764 (max_len < 0 && *p != '\0'))
1771 * g_unichar_validate:
1772 * @ch: a Unicode character
1774 * Checks whether @ch is a valid Unicode character. Some possible
1775 * integer values of @ch will not be valid. 0 is considered a valid
1776 * character, though it's normally a string terminator.
1778 * Return value: %TRUE if @ch is a valid Unicode character
1781 g_unichar_validate (gunichar ch)
1783 return UNICODE_VALID (ch);
1787 * g_utf8_strreverse:
1788 * @str: a UTF-8 encoded string
1789 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1790 * then the string is nul-terminated.
1792 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1793 * (Use g_utf8_validate() on all text before trying to use UTF-8
1794 * utility functions with it.)
1796 * This function is intended for programmatic uses of reversed strings.
1797 * It pays no attention to decomposed characters, combining marks, byte
1798 * order marks, directional indicators (LRM, LRO, etc) and similar
1799 * characters which might need special handling when reversing a string
1800 * for display purposes.
1802 * Note that unlike g_strreverse(), this function returns
1803 * newly-allocated memory, which should be freed with g_free() when
1806 * Returns: a newly-allocated string which is the reverse of @str.
1811 g_utf8_strreverse (const gchar *str,
1820 result = g_new (gchar, len + 1);
1825 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1827 for (m = r; skip; skip--)
1837 _g_utf8_make_valid (const gchar *name)
1840 const gchar *remainder, *invalid;
1841 gint remaining_bytes, valid_bytes;
1843 g_return_val_if_fail (name != NULL, NULL);
1847 remaining_bytes = strlen (name);
1849 while (remaining_bytes != 0)
1851 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1853 valid_bytes = invalid - remainder;
1856 string = g_string_sized_new (remaining_bytes);
1858 g_string_append_len (string, remainder, valid_bytes);
1859 /* append U+FFFD REPLACEMENT CHARACTER */
1860 g_string_append (string, "\357\277\275");
1862 remaining_bytes -= valid_bytes + 1;
1863 remainder = invalid + 1;
1867 return g_strdup (name);
1869 g_string_append (string, remainder);
1871 g_assert (g_utf8_validate (string->str, -1, NULL));
1873 return g_string_free (string, FALSE);
1877 #define __G_UTF8_C__
1878 #include "galiasdef.c"