1 /* gutf8.c - Operations on UTF-8 strings.
3 * Copyright (C) 1999 Tom Tromey
4 * Copyright (C) 2000 Red Hat, Inc.
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
30 #ifdef G_PLATFORM_WIN32
39 #include "gstrfuncs.h"
40 #include "gtestutils.h"
45 #define UTF8_COMPUTE(Char, Mask, Len) \
51 else if ((Char & 0xe0) == 0xc0) \
56 else if ((Char & 0xf0) == 0xe0) \
61 else if ((Char & 0xf8) == 0xf0) \
66 else if ((Char & 0xfc) == 0xf8) \
71 else if ((Char & 0xfe) == 0xfc) \
79 #define UTF8_LENGTH(Char) \
80 ((Char) < 0x80 ? 1 : \
81 ((Char) < 0x800 ? 2 : \
82 ((Char) < 0x10000 ? 3 : \
83 ((Char) < 0x200000 ? 4 : \
84 ((Char) < 0x4000000 ? 5 : 6)))))
87 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
88 (Result) = (Chars)[0] & (Mask); \
89 for ((Count) = 1; (Count) < (Len); ++(Count)) \
91 if (((Chars)[(Count)] & 0xc0) != 0x80) \
97 (Result) |= ((Chars)[(Count)] & 0x3f); \
101 * Check whether a Unicode (5.2) char is in a valid range.
103 * The first check comes from the Unicode guarantee to never encode
104 * a point above 0x0010ffff, since UTF-16 couldn't represent it.
106 * The second check covers surrogate pairs (category Cs).
108 * @param Char the character
110 #define UNICODE_VALID(Char) \
111 ((Char) < 0x110000 && \
112 (((Char) & 0xFFFFF800) != 0xD800))
115 static const gchar utf8_skip_data[256] = {
116 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
117 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
118 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
119 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
120 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
121 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
122 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
123 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
126 const gchar * const g_utf8_skip = utf8_skip_data;
129 * g_utf8_find_prev_char:
130 * @str: pointer to the beginning of a UTF-8 encoded string
131 * @p: pointer to some position within @str
133 * Given a position @p with a UTF-8 encoded string @str, find the start
134 * of the previous UTF-8 character starting before @p. Returns %NULL if no
135 * UTF-8 characters are present in @str before @p.
137 * @p does not have to be at the beginning of a UTF-8 character. No check
138 * is made to see if the character found is actually valid other than
139 * it starts with an appropriate byte.
141 * Returns: (transfer none) (nullable): a pointer to the found character or %NULL.
144 g_utf8_find_prev_char (const gchar *str,
150 if ((*p & 0xc0) != 0x80)
157 * g_utf8_find_next_char:
158 * @p: a pointer to a position within a UTF-8 encoded string
159 * @end: (nullable): a pointer to the byte following the end of the string,
160 * or %NULL to indicate that the string is nul-terminated
162 * Finds the start of the next UTF-8 character in the string after @p.
164 * @p does not have to be at the beginning of a UTF-8 character. No check
165 * is made to see if the character found is actually valid other than
166 * it starts with an appropriate byte.
168 * If @end is %NULL, the return value will never be %NULL: if the end of the
169 * string is reached, a pointer to the terminating nul byte is returned. If
170 * @end is non-%NULL, the return value will be %NULL if the end of the string
173 * Returns: (transfer none) (nullable): a pointer to the found character or %NULL if @end is
177 g_utf8_find_next_char (const gchar *p,
182 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
184 return (p >= end) ? NULL : (gchar *)p;
188 for (++p; (*p & 0xc0) == 0x80; ++p)
196 * @p: a pointer to a position within a UTF-8 encoded string
198 * Finds the previous UTF-8 character in the string before @p.
200 * @p does not have to be at the beginning of a UTF-8 character. No check
201 * is made to see if the character found is actually valid other than
202 * it starts with an appropriate byte. If @p might be the first
203 * character of the string, you must use g_utf8_find_prev_char() instead.
205 * Returns: (transfer none) (not nullable): a pointer to the found character
208 g_utf8_prev_char (const gchar *p)
213 if ((*p & 0xc0) != 0x80)
220 * @p: pointer to the start of a UTF-8 encoded string
221 * @max: the maximum number of bytes to examine. If @max
222 * is less than 0, then the string is assumed to be
223 * nul-terminated. If @max is 0, @p will not be examined and
224 * may be %NULL. If @max is greater than 0, up to @max
227 * Computes the length of the string in characters, not including
228 * the terminating nul character. If the @max'th byte falls in the
229 * middle of a character, the last (partial) character is not counted.
231 * Returns: the length of the string in characters
234 g_utf8_strlen (const gchar *p,
238 const gchar *start = p;
239 g_return_val_if_fail (p != NULL || max == 0, 0);
245 p = g_utf8_next_char (p);
254 p = g_utf8_next_char (p);
256 while (p - start < max && *p)
259 p = g_utf8_next_char (p);
262 /* only do the last len increment if we got a complete
263 * char (don't count partial chars)
265 if (p - start <= max)
274 * @str: a UTF-8 encoded string
275 * @start_pos: a character offset within @str
276 * @end_pos: another character offset within @str,
277 * or `-1` to indicate the end of the string
279 * Copies a substring out of a UTF-8 encoded string.
280 * The substring will contain @end_pos - @start_pos characters.
282 * Since GLib 2.72, `-1` can be passed to @end_pos to indicate the
285 * Returns: (transfer full): a newly allocated copy of the requested
286 * substring. Free with g_free() when no longer needed.
291 g_utf8_substring (const gchar *str,
295 gchar *start, *end, *out;
297 g_return_val_if_fail (end_pos >= start_pos || end_pos == -1, NULL);
299 start = g_utf8_offset_to_pointer (str, start_pos);
303 glong length = g_utf8_strlen (start, -1);
304 end = g_utf8_offset_to_pointer (start, length);
308 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
311 out = g_malloc (end - start + 1);
312 memcpy (out, start, end - start);
313 out[end - start] = 0;
320 * @p: a pointer to Unicode character encoded as UTF-8
322 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
324 * If @p does not point to a valid UTF-8 encoded character, results
325 * are undefined. If you are not sure that the bytes are complete
326 * valid Unicode characters, you should use g_utf8_get_char_validated()
329 * Returns: the resulting character
332 g_utf8_get_char (const gchar *p)
334 int i, mask = 0, len;
336 unsigned char c = (unsigned char) *p;
338 UTF8_COMPUTE (c, mask, len);
341 UTF8_GET (result, p, i, mask, len);
347 * g_utf8_offset_to_pointer:
348 * @str: a UTF-8 encoded string
349 * @offset: a character offset within @str
351 * Converts from an integer character offset to a pointer to a position
354 * Since 2.10, this function allows to pass a negative @offset to
355 * step backwards. It is usually worth stepping backwards from the end
356 * instead of forwards if @offset is in the last fourth of the string,
357 * since moving forward is about 3 times faster than moving backward.
359 * Note that this function doesn't abort when reaching the end of @str.
360 * Therefore you should be sure that @offset is within string boundaries
361 * before calling that function. Call g_utf8_strlen() when unsure.
362 * This limitation exists as this function is called frequently during
363 * text rendering and therefore has to be as fast as possible.
365 * Returns: (transfer none): the resulting pointer
368 g_utf8_offset_to_pointer (const gchar *str,
371 const gchar *s = str;
375 s = g_utf8_next_char (s);
380 /* This nice technique for fast backwards stepping
381 * through a UTF-8 string was dubbed "stutter stepping"
382 * by its inventor, Larry Ewing.
388 while ((*s & 0xc0) == 0x80)
391 offset += g_utf8_pointer_to_offset (s, s1);
399 * g_utf8_pointer_to_offset:
400 * @str: a UTF-8 encoded string
401 * @pos: a pointer to a position within @str
403 * Converts from a pointer to position within a string to an integer
406 * Since 2.10, this function allows @pos to be before @str, and returns
407 * a negative offset in this case.
409 * Returns: the resulting character offset
412 g_utf8_pointer_to_offset (const gchar *str,
415 const gchar *s = str;
419 offset = - g_utf8_pointer_to_offset (pos, str);
423 s = g_utf8_next_char (s);
433 * @dest: (transfer none): buffer to fill with characters from @src
434 * @src: UTF-8 encoded string
435 * @n: character count
437 * Like the standard C strncpy() function, but copies a given number
438 * of characters instead of a given number of bytes. The @src string
439 * must be valid UTF-8 encoded text. (Use g_utf8_validate() on all
440 * text before trying to use UTF-8 utility functions with it.)
442 * Note you must ensure @dest is at least 4 * @n + 1 to fit the
443 * largest possible UTF-8 characters
445 * Returns: (transfer none): @dest
448 g_utf8_strncpy (gchar *dest,
452 const gchar *s = src;
455 s = g_utf8_next_char(s);
458 strncpy(dest, src, s - src);
464 * g_utf8_truncate_middle:
465 * @string: (transfer none): a nul-terminated UTF-8 encoded string
466 * @truncate_length: the new size of @string, in characters, including the ellipsis character
468 * Cuts off the middle of the string, preserving half of @truncate_length
469 * characters at the beginning and half at the end.
471 * If @string is already short enough, this returns a copy of @string.
472 * If @truncate_length is `0`, an empty string is returned.
474 * Returns: (transfer full): a newly-allocated copy of @string ellipsized in the middle
479 g_utf8_truncate_middle (const gchar *string,
480 gsize truncate_length)
482 const gchar *ellipsis = "…";
483 const gsize ellipsis_bytes = strlen (ellipsis);
486 gsize left_substring_length;
487 gchar *left_substring_end;
488 gchar *right_substring_begin;
489 gchar *right_substring_end;
494 g_return_val_if_fail (string != NULL, NULL);
496 length = g_utf8_strlen (string, -1);
497 /* Current string already smaller than requested length */
498 if (length <= truncate_length)
499 return g_strdup (string);
500 if (truncate_length == 0)
501 return g_strdup ("");
503 /* Find substrings to keep, ignore ellipsis character for that */
504 truncate_length -= 1;
506 left_substring_length = truncate_length / 2;
508 left_substring_end = g_utf8_offset_to_pointer (string, left_substring_length);
509 right_substring_begin = g_utf8_offset_to_pointer (left_substring_end,
510 length - truncate_length);
511 right_substring_end = g_utf8_offset_to_pointer (right_substring_begin,
512 truncate_length - left_substring_length);
514 g_assert (*right_substring_end == '\0');
516 left_bytes = left_substring_end - string;
517 right_bytes = right_substring_end - right_substring_begin;
519 result = g_malloc (left_bytes + ellipsis_bytes + right_bytes + 1);
521 strncpy (result, string, left_bytes);
522 memcpy (result + left_bytes, ellipsis, ellipsis_bytes);
523 strncpy (result + left_bytes + ellipsis_bytes, right_substring_begin, right_bytes);
524 result[left_bytes + ellipsis_bytes + right_bytes] = '\0';
533 * @c: a Unicode character code
534 * @outbuf: (out caller-allocates) (optional): output buffer, must have at
535 * least 6 bytes of space. If %NULL, the length will be computed and
536 * returned and nothing will be written to @outbuf.
538 * Converts a single character to UTF-8.
540 * Returns: number of bytes written
543 g_unichar_to_utf8 (gunichar c,
546 /* If this gets modified, also update the copy in g_string_insert_unichar() */
561 else if (c < 0x10000)
566 else if (c < 0x200000)
571 else if (c < 0x4000000)
584 for (i = len - 1; i > 0; --i)
586 outbuf[i] = (c & 0x3f) | 0x80;
589 outbuf[0] = c | first;
597 * @p: a nul-terminated UTF-8 encoded string
598 * @len: the maximum length of @p
599 * @c: a Unicode character
601 * Finds the leftmost occurrence of the given Unicode character
602 * in a UTF-8 encoded string, while limiting the search to @len bytes.
603 * If @len is -1, allow unbounded search.
605 * Returns: (transfer none) (nullable): %NULL if the string does not contain the character,
606 * otherwise, a pointer to the start of the leftmost occurrence
607 * of the character in the string.
610 g_utf8_strchr (const char *p,
616 gint charlen = g_unichar_to_utf8 (c, ch);
619 return g_strstr_len (p, len, ch);
625 * @p: a nul-terminated UTF-8 encoded string
626 * @len: the maximum length of @p
627 * @c: a Unicode character
629 * Find the rightmost occurrence of the given Unicode character
630 * in a UTF-8 encoded string, while limiting the search to @len bytes.
631 * If @len is -1, allow unbounded search.
633 * Returns: (transfer none) (nullable): %NULL if the string does not contain the character,
634 * otherwise, a pointer to the start of the rightmost occurrence
635 * of the character in the string.
638 g_utf8_strrchr (const char *p,
644 gint charlen = g_unichar_to_utf8 (c, ch);
647 return g_strrstr_len (p, len, ch);
651 /* Like g_utf8_get_char, but take a maximum length
652 * and return (gunichar)-2 on incomplete trailing character;
653 * also check for malformed or overlong sequences
654 * and return (gunichar)-1 in this case.
656 static inline gunichar
657 g_utf8_get_char_extended (const gchar *p,
662 gunichar wc = (guchar) *p;
663 const gunichar partial_sequence = (gunichar) -2;
664 const gunichar malformed_sequence = (gunichar) -1;
670 else if (G_UNLIKELY (wc < 0xc0))
672 return malformed_sequence;
706 return malformed_sequence;
709 if (G_UNLIKELY (max_len >= 0 && len > (gsize) max_len))
711 for (i = 1; i < (gsize) max_len; i++)
713 if ((((guchar *)p)[i] & 0xc0) != 0x80)
714 return malformed_sequence;
716 return partial_sequence;
719 for (i = 1; i < len; ++i)
721 gunichar ch = ((guchar *)p)[i];
723 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
726 return malformed_sequence;
728 return partial_sequence;
735 if (G_UNLIKELY (wc < min_code))
736 return malformed_sequence;
742 * g_utf8_get_char_validated:
743 * @p: a pointer to Unicode character encoded as UTF-8
744 * @max_len: the maximum number of bytes to read, or -1 if @p is nul-terminated
746 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
747 * This function checks for incomplete characters, for invalid characters
748 * such as characters that are out of the range of Unicode, and for
749 * overlong encodings of valid characters.
751 * Note that g_utf8_get_char_validated() returns (gunichar)-2 if
752 * @max_len is positive and any of the bytes in the first UTF-8 character
755 * Returns: the resulting character. If @p points to a partial
756 * sequence at the end of a string that could begin a valid
757 * character (or if @max_len is zero), returns (gunichar)-2;
758 * otherwise, if @p does not point to a valid UTF-8 encoded
759 * Unicode character, returns (gunichar)-1.
762 g_utf8_get_char_validated (const gchar *p,
770 result = g_utf8_get_char_extended (p, max_len);
772 /* Disallow codepoint U+0000 as it’s a nul byte,
773 * and all string handling in GLib is nul-terminated */
774 if (result == 0 && max_len > 0)
775 return (gunichar) -2;
777 if (result & 0x80000000)
779 else if (!UNICODE_VALID (result))
785 #define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
788 * g_utf8_to_ucs4_fast:
789 * @str: a UTF-8 encoded string
790 * @len: the maximum length of @str to use, in bytes. If @len < 0,
791 * then the string is nul-terminated.
792 * @items_written: (out) (optional): location to store the
793 * number of characters in the result, or %NULL.
795 * Convert a string from UTF-8 to a 32-bit fixed width
796 * representation as UCS-4, assuming valid UTF-8 input.
797 * This function is roughly twice as fast as g_utf8_to_ucs4()
798 * but does no error checking on the input. A trailing 0 character
799 * will be added to the string after the converted text.
801 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
802 * This value must be freed with g_free().
805 g_utf8_to_ucs4_fast (const gchar *str,
807 glong *items_written)
813 g_return_val_if_fail (str != NULL, NULL);
821 p = g_utf8_next_char (p);
827 while (p < str + len && *p)
829 p = g_utf8_next_char (p);
834 result = g_new (gunichar, n_chars + 1);
837 for (i=0; i < n_chars; i++)
839 guchar first = (guchar)*p++;
844 /* We really hope first < 0x80, but we don't want to test an
845 * extra branch for invalid input, which this function
846 * does not care about. Handling unexpected continuation bytes
847 * here will do the least damage. */
852 gunichar c1 = CONT_BYTE_FAST(p);
855 wc = ((first & 0x1f) << 6) | c1;
859 gunichar c2 = CONT_BYTE_FAST(p);
862 wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
866 gunichar c3 = CONT_BYTE_FAST(p);
867 wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
868 if (G_UNLIKELY (first >= 0xf8))
870 /* This can't be valid UTF-8, but g_utf8_next_char()
871 * and company allow out-of-range sequences */
872 gunichar mask = 1 << 20;
873 while ((wc & mask) != 0)
876 wc |= CONT_BYTE_FAST(p);
895 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
897 gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
899 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
900 _("Failed to allocate memory"));
906 * @str: a UTF-8 encoded string
907 * @len: the maximum length of @str to use, in bytes. If @len < 0,
908 * then the string is nul-terminated.
909 * @items_read: (out) (optional): location to store number of
910 * bytes read, or %NULL.
911 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
912 * returned in case @str contains a trailing partial
913 * character. If an error occurs then the index of the
914 * invalid input is stored here.
915 * @items_written: (out) (optional): location to store number
916 * of characters written or %NULL. The value here stored does not include
917 * the trailing 0 character.
918 * @error: location to store the error occurring, or %NULL to ignore
919 * errors. Any of the errors in #GConvertError other than
920 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
922 * Convert a string from UTF-8 to a 32-bit fixed width
923 * representation as UCS-4. A trailing 0 character will be added to the
924 * string after the converted text.
926 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
927 * This value must be freed with g_free(). If an error occurs,
928 * %NULL will be returned and @error set.
931 g_utf8_to_ucs4 (const gchar *str,
934 glong *items_written,
937 gunichar *result = NULL;
943 while ((len < 0 || str + len - in > 0) && *in)
945 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
948 if (wc == (gunichar)-2)
953 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
954 _("Partial character sequence at end of input"));
957 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
958 _("Invalid byte sequence in conversion input"));
965 in = g_utf8_next_char (in);
968 result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
973 for (i=0; i < n_chars; i++)
975 result[i] = g_utf8_get_char (in);
976 in = g_utf8_next_char (in);
981 *items_written = n_chars;
985 *items_read = in - str;
992 * @str: (array length=len) (element-type gunichar): a UCS-4 encoded string
993 * @len: the maximum length (number of characters) of @str to use.
994 * If @len < 0, then the string is nul-terminated.
995 * @items_read: (out) (optional): location to store number of
996 * characters read, or %NULL.
997 * @items_written: (out) (optional): location to store number
998 * of bytes written or %NULL. The value here stored does not include the
1000 * @error: location to store the error occurring, or %NULL to ignore
1001 * errors. Any of the errors in #GConvertError other than
1002 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1004 * Convert a string from a 32-bit fixed width representation as UCS-4.
1005 * to UTF-8. The result will be terminated with a 0 byte.
1007 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
1008 * This value must be freed with g_free(). If an error occurs,
1009 * %NULL will be returned and @error set. In that case, @items_read
1010 * will be set to the position of the first invalid input character.
1013 g_ucs4_to_utf8 (const gunichar *str,
1016 glong *items_written,
1020 gchar *result = NULL;
1025 for (i = 0; len < 0 || i < len ; i++)
1030 if (str[i] >= 0x80000000)
1032 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1033 _("Character out of range for UTF-8"));
1037 result_length += UTF8_LENGTH (str[i]);
1040 result = try_malloc_n (result_length + 1, 1, error);
1047 while (p < result + result_length)
1048 p += g_unichar_to_utf8 (str[i++], p);
1053 *items_written = p - result;
1062 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1066 * @str: (array length=len) (element-type guint16): a UTF-16 encoded string
1067 * @len: the maximum length (number of #gunichar2) of @str to use.
1068 * If @len < 0, then the string is nul-terminated.
1069 * @items_read: (out) (optional): location to store number of
1070 * words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1071 * be returned in case @str contains a trailing partial character. If
1072 * an error occurs then the index of the invalid input is stored here.
1073 * It’s guaranteed to be non-negative.
1074 * @items_written: (out) (optional): location to store number
1075 * of bytes written, or %NULL. The value stored here does not include the
1076 * trailing 0 byte. It’s guaranteed to be non-negative.
1077 * @error: location to store the error occurring, or %NULL to ignore
1078 * errors. Any of the errors in #GConvertError other than
1079 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1081 * Convert a string from UTF-16 to UTF-8. The result will be
1082 * terminated with a 0 byte.
1084 * Note that the input is expected to be already in native endianness,
1085 * an initial byte-order-mark character is not handled specially.
1086 * g_convert() can be used to convert a byte buffer of UTF-16 data of
1087 * ambiguous endianness.
1089 * Further note that this function does not validate the result
1090 * string; it may e.g. include embedded NUL characters. The only
1091 * validation done by this function is to ensure that the input can
1092 * be correctly interpreted as UTF-16, i.e. it doesn't contain
1093 * unpaired surrogates or partial character sequences.
1095 * Returns: (transfer full): a pointer to a newly allocated UTF-8 string.
1096 * This value must be freed with g_free(). If an error occurs,
1097 * %NULL will be returned and @error set.
1100 g_utf16_to_utf8 (const gunichar2 *str,
1103 glong *items_written,
1106 /* This function and g_utf16_to_ucs4 are almost exactly identical -
1107 * The lines that differ are marked.
1109 const gunichar2 *in;
1111 gchar *result = NULL;
1113 gunichar high_surrogate;
1115 g_return_val_if_fail (str != NULL, NULL);
1120 while ((len < 0 || in - str < len) && *in)
1125 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1129 wc = SURROGATE_VALUE (high_surrogate, c);
1134 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1135 _("Invalid sequence in conversion input"));
1143 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1144 _("Invalid sequence in conversion input"));
1148 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1157 /********** DIFFERENT for UTF8/UCS4 **********/
1158 n_bytes += UTF8_LENGTH (wc);
1164 if (high_surrogate && !items_read)
1166 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1167 _("Partial character sequence at end of input"));
1171 /* At this point, everything is valid, and we just need to convert
1173 /********** DIFFERENT for UTF8/UCS4 **********/
1174 result = try_malloc_n (n_bytes + 1, 1, error);
1181 while (out < result + n_bytes)
1186 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1188 wc = SURROGATE_VALUE (high_surrogate, c);
1191 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1199 /********** DIFFERENT for UTF8/UCS4 **********/
1200 out += g_unichar_to_utf8 (wc, out);
1206 /********** DIFFERENT for UTF8/UCS4 **********/
1210 /********** DIFFERENT for UTF8/UCS4 **********/
1211 *items_written = out - result;
1215 *items_read = in - str;
1222 * @str: (array length=len) (element-type guint16): a UTF-16 encoded string
1223 * @len: the maximum length (number of #gunichar2) of @str to use.
1224 * If @len < 0, then the string is nul-terminated.
1225 * @items_read: (out) (optional): location to store number of
1226 * words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1227 * be returned in case @str contains a trailing partial character. If
1228 * an error occurs then the index of the invalid input is stored here.
1229 * @items_written: (out) (optional): location to store number
1230 * of characters written, or %NULL. The value stored here does not include
1231 * the trailing 0 character.
1232 * @error: location to store the error occurring, or %NULL to ignore
1233 * errors. Any of the errors in #GConvertError other than
1234 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1236 * Convert a string from UTF-16 to UCS-4. The result will be
1239 * Returns: (transfer full): a pointer to a newly allocated UCS-4 string.
1240 * This value must be freed with g_free(). If an error occurs,
1241 * %NULL will be returned and @error set.
1244 g_utf16_to_ucs4 (const gunichar2 *str,
1247 glong *items_written,
1250 const gunichar2 *in;
1252 gchar *result = NULL;
1254 gunichar high_surrogate;
1256 g_return_val_if_fail (str != NULL, NULL);
1261 while ((len < 0 || in - str < len) && *in)
1265 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1273 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1274 _("Invalid sequence in conversion input"));
1282 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1283 _("Invalid sequence in conversion input"));
1287 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1294 /********** DIFFERENT for UTF8/UCS4 **********/
1295 n_bytes += sizeof (gunichar);
1301 if (high_surrogate && !items_read)
1303 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1304 _("Partial character sequence at end of input"));
1308 /* At this point, everything is valid, and we just need to convert
1310 /********** DIFFERENT for UTF8/UCS4 **********/
1311 result = try_malloc_n (n_bytes + 4, 1, error);
1318 while (out < result + n_bytes)
1323 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1325 wc = SURROGATE_VALUE (high_surrogate, c);
1328 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1336 /********** DIFFERENT for UTF8/UCS4 **********/
1337 *(gunichar *)out = wc;
1338 out += sizeof (gunichar);
1344 /********** DIFFERENT for UTF8/UCS4 **********/
1345 *(gunichar *)out = 0;
1348 /********** DIFFERENT for UTF8/UCS4 **********/
1349 *items_written = (out - result) / sizeof (gunichar);
1353 *items_read = in - str;
1355 return (gunichar *)result;
1360 * @str: a UTF-8 encoded string
1361 * @len: the maximum length (number of bytes) of @str to use.
1362 * If @len < 0, then the string is nul-terminated.
1363 * @items_read: (out) (optional): location to store number of
1364 * bytes read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1365 * be returned in case @str contains a trailing partial character. If
1366 * an error occurs then the index of the invalid input is stored here.
1367 * @items_written: (out) (optional): location to store number
1368 * of #gunichar2 written, or %NULL. The value stored here does not include
1370 * @error: location to store the error occurring, or %NULL to ignore
1371 * errors. Any of the errors in #GConvertError other than
1372 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1374 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1375 * added to the result after the converted text.
1377 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1378 * This value must be freed with g_free(). If an error occurs,
1379 * %NULL will be returned and @error set.
1382 g_utf8_to_utf16 (const gchar *str,
1385 glong *items_written,
1388 gunichar2 *result = NULL;
1393 g_return_val_if_fail (str != NULL, NULL);
1397 while ((len < 0 || str + len - in > 0) && *in)
1399 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1400 if (wc & 0x80000000)
1402 if (wc == (gunichar)-2)
1407 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1408 _("Partial character sequence at end of input"));
1411 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1412 _("Invalid byte sequence in conversion input"));
1419 else if (wc < 0xe000)
1421 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1422 _("Invalid sequence in conversion input"));
1426 else if (wc < 0x10000)
1428 else if (wc < 0x110000)
1432 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1433 _("Character out of range for UTF-16"));
1438 in = g_utf8_next_char (in);
1441 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1446 for (i = 0; i < n16;)
1448 gunichar wc = g_utf8_get_char (in);
1456 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1457 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1460 in = g_utf8_next_char (in);
1466 *items_written = n16;
1470 *items_read = in - str;
1477 * @str: (array length=len) (element-type gunichar): a UCS-4 encoded string
1478 * @len: the maximum length (number of characters) of @str to use.
1479 * If @len < 0, then the string is nul-terminated.
1480 * @items_read: (out) (optional): location to store number of
1481 * bytes read, or %NULL. If an error occurs then the index of the invalid
1482 * input is stored here.
1483 * @items_written: (out) (optional): location to store number
1484 * of #gunichar2 written, or %NULL. The value stored here does not include
1486 * @error: location to store the error occurring, or %NULL to ignore
1487 * errors. Any of the errors in #GConvertError other than
1488 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1490 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1491 * added to the result after the converted text.
1493 * Returns: (transfer full): a pointer to a newly allocated UTF-16 string.
1494 * This value must be freed with g_free(). If an error occurs,
1495 * %NULL will be returned and @error set.
1498 g_ucs4_to_utf16 (const gunichar *str,
1501 glong *items_written,
1504 gunichar2 *result = NULL;
1510 while ((len < 0 || i < len) && str[i])
1512 gunichar wc = str[i];
1516 else if (wc < 0xe000)
1518 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1519 _("Invalid sequence in conversion input"));
1523 else if (wc < 0x10000)
1525 else if (wc < 0x110000)
1529 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1530 _("Character out of range for UTF-16"));
1538 result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1542 for (i = 0, j = 0; j < n16; i++)
1544 gunichar wc = str[i];
1552 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1553 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1559 *items_written = n16;
1568 #define VALIDATE_BYTE(mask, expect) \
1570 if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1574 /* see IETF RFC 3629 Section 4 */
1576 static const gchar *
1577 fast_validate (const char *str)
1582 for (p = str; *p; p++)
1584 if (*(guchar *)p < 128)
1591 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1593 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1598 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1600 switch (*(guchar *)p++ & 0x0f)
1603 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1606 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1609 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1612 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1614 switch (*(guchar *)p++ & 0x07)
1617 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1618 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1622 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1625 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1628 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1635 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1647 static const gchar *
1648 fast_validate_len (const char *str,
1654 g_assert (max_len >= 0);
1656 for (p = str; ((p - str) < max_len) && *p; p++)
1658 if (*(guchar *)p < 128)
1665 if (*(guchar *)p < 0xe0) /* 110xxxxx */
1667 if (G_UNLIKELY (max_len - (p - str) < 2))
1670 if (G_UNLIKELY (*(guchar *)p < 0xc2))
1675 if (*(guchar *)p < 0xf0) /* 1110xxxx */
1677 if (G_UNLIKELY (max_len - (p - str) < 3))
1680 switch (*(guchar *)p++ & 0x0f)
1683 VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1686 VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1689 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1692 else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1694 if (G_UNLIKELY (max_len - (p - str) < 4))
1697 switch (*(guchar *)p++ & 0x07)
1700 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1701 if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1705 VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1708 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1711 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1718 VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1732 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1733 * @max_len: max bytes to validate, or -1 to go until NUL
1734 * @end: (out) (optional) (transfer none): return location for end of valid data
1736 * Validates UTF-8 encoded text. @str is the text to validate;
1737 * if @str is nul-terminated, then @max_len can be -1, otherwise
1738 * @max_len should be the number of bytes to validate.
1739 * If @end is non-%NULL, then the end of the valid range
1740 * will be stored there (i.e. the start of the first invalid
1741 * character if some bytes were invalid, or the end of the text
1742 * being validated otherwise).
1744 * Note that g_utf8_validate() returns %FALSE if @max_len is
1745 * positive and any of the @max_len bytes are nul.
1747 * Returns %TRUE if all of @str was valid. Many GLib and GTK
1748 * routines require valid UTF-8 as input; so data read from a file
1749 * or the network should be checked with g_utf8_validate() before
1750 * doing anything else with it.
1752 * Returns: %TRUE if the text was valid UTF-8
1755 g_utf8_validate (const char *str,
1763 return g_utf8_validate_len (str, max_len, end);
1765 p = fast_validate (str);
1777 * g_utf8_validate_len:
1778 * @str: (array length=max_len) (element-type guint8): a pointer to character data
1779 * @max_len: max bytes to validate
1780 * @end: (out) (optional) (transfer none): return location for end of valid data
1782 * Validates UTF-8 encoded text.
1784 * As with g_utf8_validate(), but @max_len must be set, and hence this function
1785 * will always return %FALSE if any of the bytes of @str are nul.
1787 * Returns: %TRUE if the text was valid UTF-8
1791 g_utf8_validate_len (const char *str,
1798 p = fast_validate_len (str, max_len);
1803 if (p != str + max_len)
1810 * g_unichar_validate:
1811 * @ch: a Unicode character
1813 * Checks whether @ch is a valid Unicode character. Some possible
1814 * integer values of @ch will not be valid. 0 is considered a valid
1815 * character, though it's normally a string terminator.
1817 * Returns: %TRUE if @ch is a valid Unicode character
1820 g_unichar_validate (gunichar ch)
1822 return UNICODE_VALID (ch);
1826 * g_utf8_strreverse:
1827 * @str: a UTF-8 encoded string
1828 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1829 * then the string is nul-terminated.
1831 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1832 * (Use g_utf8_validate() on all text before trying to use UTF-8
1833 * utility functions with it.)
1835 * This function is intended for programmatic uses of reversed strings.
1836 * It pays no attention to decomposed characters, combining marks, byte
1837 * order marks, directional indicators (LRM, LRO, etc) and similar
1838 * characters which might need special handling when reversing a string
1839 * for display purposes.
1841 * Note that unlike g_strreverse(), this function returns
1842 * newly-allocated memory, which should be freed with g_free() when
1845 * Returns: (transfer full): a newly-allocated string which is the reverse of @str
1850 g_utf8_strreverse (const gchar *str,
1859 result = g_new (gchar, len + 1);
1864 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1866 g_assert (r >= result);
1867 for (m = r; skip; skip--)
1876 * g_utf8_make_valid:
1877 * @str: string to coerce into UTF-8
1878 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1879 * then the string is nul-terminated.
1881 * If the provided string is valid UTF-8, return a copy of it. If not,
1882 * return a copy in which bytes that could not be interpreted as valid Unicode
1883 * are replaced with the Unicode replacement character (U+FFFD).
1885 * For example, this is an appropriate function to use if you have received
1886 * a string that was incorrectly declared to be UTF-8, and you need a valid
1887 * UTF-8 version of it that can be logged or displayed to the user, with the
1888 * assumption that it is close enough to ASCII or UTF-8 to be mostly
1891 * Returns: (transfer full): a valid UTF-8 string whose content resembles @str
1896 g_utf8_make_valid (const gchar *str,
1900 const gchar *remainder, *invalid;
1901 gsize remaining_bytes, valid_bytes;
1903 g_return_val_if_fail (str != NULL, NULL);
1910 remaining_bytes = len;
1912 while (remaining_bytes != 0)
1914 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1916 valid_bytes = invalid - remainder;
1919 string = g_string_sized_new (remaining_bytes);
1921 g_string_append_len (string, remainder, valid_bytes);
1922 /* append U+FFFD REPLACEMENT CHARACTER */
1923 g_string_append (string, "\357\277\275");
1925 remaining_bytes -= valid_bytes + 1;
1926 remainder = invalid + 1;
1930 return g_strndup (str, len);
1932 g_string_append_len (string, remainder, remaining_bytes);
1933 g_string_append_c (string, '\0');
1935 g_assert (g_utf8_validate (string->str, -1, NULL));
1937 return g_string_free (string, FALSE);