docs: Fix GNetworkAddress typo
[glib.git] / glib / gutf8.c
blobe1e0003dd94f514dc2d57c77c9e5503206885a26
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.
22 #include "config.h"
24 #include <stdlib.h>
25 #ifdef HAVE_CODESET
26 #include <langinfo.h>
27 #endif
28 #include <string.h>
30 #ifdef G_PLATFORM_WIN32
31 #include <stdio.h>
32 #define STRICT
33 #include <windows.h>
34 #undef STRICT
35 #endif
37 #include "gconvert.h"
38 #include "ghash.h"
39 #include "gstrfuncs.h"
40 #include "gtestutils.h"
41 #include "gtypes.h"
42 #include "gthread.h"
43 #include "glibintl.h"
45 #define UTF8_COMPUTE(Char, Mask, Len) \
46 if (Char < 128) \
47 { \
48 Len = 1; \
49 Mask = 0x7f; \
50 } \
51 else if ((Char & 0xe0) == 0xc0) \
52 { \
53 Len = 2; \
54 Mask = 0x1f; \
55 } \
56 else if ((Char & 0xf0) == 0xe0) \
57 { \
58 Len = 3; \
59 Mask = 0x0f; \
60 } \
61 else if ((Char & 0xf8) == 0xf0) \
62 { \
63 Len = 4; \
64 Mask = 0x07; \
65 } \
66 else if ((Char & 0xfc) == 0xf8) \
67 { \
68 Len = 5; \
69 Mask = 0x03; \
70 } \
71 else if ((Char & 0xfe) == 0xfc) \
72 { \
73 Len = 6; \
74 Mask = 0x01; \
75 } \
76 else \
77 Len = -1;
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)) \
90 { \
91 if (((Chars)[(Count)] & 0xc0) != 0x80) \
92 { \
93 (Result) = -1; \
94 break; \
95 } \
96 (Result) <<= 6; \
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 * The last two checks cover "Noncharacter": defined as:
109 * "A code point that is permanently reserved for
110 * internal use, and that should never be interchanged. In
111 * Unicode 3.1, these consist of the values U+nFFFE and U+nFFFF
112 * (where n is from 0 to 10_16) and the values U+FDD0..U+FDEF."
114 * @param Char the character
116 #define UNICODE_VALID(Char) \
117 ((Char) < 0x110000 && \
118 (((Char) & 0xFFFFF800) != 0xD800) && \
119 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
120 ((Char) & 0xFFFE) != 0xFFFE)
123 static const gchar utf8_skip_data[256] = {
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 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,
130 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,
131 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
134 const gchar * const g_utf8_skip = utf8_skip_data;
137 * g_utf8_find_prev_char:
138 * @str: pointer to the beginning of a UTF-8 encoded string
139 * @p: pointer to some position within @str
141 * Given a position @p with a UTF-8 encoded string @str, find the start
142 * of the previous UTF-8 character starting before @p. Returns %NULL if no
143 * UTF-8 characters are present in @str before @p.
145 * @p does not have to be at the beginning of a UTF-8 character. No check
146 * is made to see if the character found is actually valid other than
147 * it starts with an appropriate byte.
149 * Return value: a pointer to the found character or %NULL.
151 gchar *
152 g_utf8_find_prev_char (const char *str,
153 const char *p)
155 for (--p; p >= str; --p)
157 if ((*p & 0xc0) != 0x80)
158 return (gchar *)p;
160 return NULL;
164 * g_utf8_find_next_char:
165 * @p: a pointer to a position within a UTF-8 encoded string
166 * @end: a pointer to the byte following the end of the string,
167 * or %NULL to indicate that the string is nul-terminated.
169 * Finds the start of the next UTF-8 character in the string after @p.
171 * @p does not have to be at the beginning of a UTF-8 character. No check
172 * is made to see if the character found is actually valid other than
173 * it starts with an appropriate byte.
175 * Return value: a pointer to the found character or %NULL
177 gchar *
178 g_utf8_find_next_char (const gchar *p,
179 const gchar *end)
181 if (*p)
183 if (end)
184 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
186 else
187 for (++p; (*p & 0xc0) == 0x80; ++p)
190 return (p == end) ? NULL : (gchar *)p;
194 * g_utf8_prev_char:
195 * @p: a pointer to a position within a UTF-8 encoded string
197 * Finds the previous UTF-8 character in the string before @p.
199 * @p does not have to be at the beginning of a UTF-8 character. No check
200 * is made to see if the character found is actually valid other than
201 * it starts with an appropriate byte. If @p might be the first
202 * character of the string, you must use g_utf8_find_prev_char() instead.
204 * Return value: a pointer to the found character.
206 gchar *
207 g_utf8_prev_char (const gchar *p)
209 while (TRUE)
211 p--;
212 if ((*p & 0xc0) != 0x80)
213 return (gchar *)p;
218 * g_utf8_strlen:
219 * @p: pointer to the start of a UTF-8 encoded string
220 * @max: the maximum number of bytes to examine. If @max
221 * is less than 0, then the string is assumed to be
222 * nul-terminated. If @max is 0, @p will not be examined and
223 * may be %NULL. If @max is greater than 0, up to @max
224 * bytes are examined
226 * Computes the length of the string in characters, not including
227 * the terminating nul character. If the @max'th byte falls in the
228 * middle of a character, the last (partial) character is not counted.
230 * Return value: the length of the string in characters
232 glong
233 g_utf8_strlen (const gchar *p,
234 gssize max)
236 glong len = 0;
237 const gchar *start = p;
238 g_return_val_if_fail (p != NULL || max == 0, 0);
240 if (max < 0)
242 while (*p)
244 p = g_utf8_next_char (p);
245 ++len;
248 else
250 if (max == 0 || !*p)
251 return 0;
253 p = g_utf8_next_char (p);
255 while (p - start < max && *p)
257 ++len;
258 p = g_utf8_next_char (p);
261 /* only do the last len increment if we got a complete
262 * char (don't count partial chars)
264 if (p - start <= max)
265 ++len;
268 return len;
272 * g_utf8_substring:
273 * @str: a UTF-8 encoded string
274 * @start_pos: a character offset within @str
275 * @end_pos: another character offset within @str
277 * Copies a substring out of a UTF-8 encoded string.
278 * The substring will contain @end_pos - @start_pos
279 * characters.
281 * Returns: a newly allocated copy of the requested
282 * substring. Free with g_free() when no longer needed.
284 * Since: 2.30
286 gchar *
287 g_utf8_substring (const gchar *str,
288 glong start_pos,
289 glong end_pos)
291 gchar *start, *end, *out;
293 start = g_utf8_offset_to_pointer (str, start_pos);
294 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
296 out = g_malloc (end - start + 1);
297 memcpy (out, start, end - start);
298 out[end - start] = 0;
300 return out;
304 * g_utf8_get_char:
305 * @p: a pointer to Unicode character encoded as UTF-8
307 * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
308 * If @p does not point to a valid UTF-8 encoded character, results are
309 * undefined. If you are not sure that the bytes are complete
310 * valid Unicode characters, you should use g_utf8_get_char_validated()
311 * instead.
313 * Return value: the resulting character
315 gunichar
316 g_utf8_get_char (const gchar *p)
318 int i, mask = 0, len;
319 gunichar result;
320 unsigned char c = (unsigned char) *p;
322 UTF8_COMPUTE (c, mask, len);
323 if (len == -1)
324 return (gunichar)-1;
325 UTF8_GET (result, p, i, mask, len);
327 return result;
331 * g_utf8_offset_to_pointer:
332 * @str: a UTF-8 encoded string
333 * @offset: a character offset within @str
335 * Converts from an integer character offset to a pointer to a position
336 * within the string.
338 * Since 2.10, this function allows to pass a negative @offset to
339 * step backwards. It is usually worth stepping backwards from the end
340 * instead of forwards if @offset is in the last fourth of the string,
341 * since moving forward is about 3 times faster than moving backward.
343 * <note><para>
344 * This function doesn't abort when reaching the end of @str. Therefore
345 * you should be sure that @offset is within string boundaries before
346 * calling that function. Call g_utf8_strlen() when unsure.
348 * This limitation exists as this function is called frequently during
349 * text rendering and therefore has to be as fast as possible.
350 * </para></note>
352 * Return value: the resulting pointer
354 gchar *
355 g_utf8_offset_to_pointer (const gchar *str,
356 glong offset)
358 const gchar *s = str;
360 if (offset > 0)
361 while (offset--)
362 s = g_utf8_next_char (s);
363 else
365 const char *s1;
367 /* This nice technique for fast backwards stepping
368 * through a UTF-8 string was dubbed "stutter stepping"
369 * by its inventor, Larry Ewing.
371 while (offset)
373 s1 = s;
374 s += offset;
375 while ((*s & 0xc0) == 0x80)
376 s--;
378 offset += g_utf8_pointer_to_offset (s, s1);
382 return (gchar *)s;
386 * g_utf8_pointer_to_offset:
387 * @str: a UTF-8 encoded string
388 * @pos: a pointer to a position within @str
390 * Converts from a pointer to position within a string to a integer
391 * character offset.
393 * Since 2.10, this function allows @pos to be before @str, and returns
394 * a negative offset in this case.
396 * Return value: the resulting character offset
398 glong
399 g_utf8_pointer_to_offset (const gchar *str,
400 const gchar *pos)
402 const gchar *s = str;
403 glong offset = 0;
405 if (pos < str)
406 offset = - g_utf8_pointer_to_offset (pos, str);
407 else
408 while (s < pos)
410 s = g_utf8_next_char (s);
411 offset++;
414 return offset;
419 * g_utf8_strncpy:
420 * @dest: buffer to fill with characters from @src
421 * @src: UTF-8 encoded string
422 * @n: character count
424 * Like the standard C strncpy() function, but
425 * copies a given number of characters instead of a given number of
426 * bytes. The @src string must be valid UTF-8 encoded text.
427 * (Use g_utf8_validate() on all text before trying to use UTF-8
428 * utility functions with it.)
430 * Return value: @dest
432 gchar *
433 g_utf8_strncpy (gchar *dest,
434 const gchar *src,
435 gsize n)
437 const gchar *s = src;
438 while (n && *s)
440 s = g_utf8_next_char(s);
441 n--;
443 strncpy(dest, src, s - src);
444 dest[s - src] = 0;
445 return dest;
448 /* unicode_strchr */
451 * g_unichar_to_utf8:
452 * @c: a Unicode character code
453 * @outbuf: output buffer, must have at least 6 bytes of space.
454 * If %NULL, the length will be computed and returned
455 * and nothing will be written to @outbuf.
457 * Converts a single character to UTF-8.
459 * Return value: number of bytes written
462 g_unichar_to_utf8 (gunichar c,
463 gchar *outbuf)
465 /* If this gets modified, also update the copy in g_string_insert_unichar() */
466 guint len = 0;
467 int first;
468 int i;
470 if (c < 0x80)
472 first = 0;
473 len = 1;
475 else if (c < 0x800)
477 first = 0xc0;
478 len = 2;
480 else if (c < 0x10000)
482 first = 0xe0;
483 len = 3;
485 else if (c < 0x200000)
487 first = 0xf0;
488 len = 4;
490 else if (c < 0x4000000)
492 first = 0xf8;
493 len = 5;
495 else
497 first = 0xfc;
498 len = 6;
501 if (outbuf)
503 for (i = len - 1; i > 0; --i)
505 outbuf[i] = (c & 0x3f) | 0x80;
506 c >>= 6;
508 outbuf[0] = c | first;
511 return len;
515 * g_utf8_strchr:
516 * @p: a nul-terminated UTF-8 encoded string
517 * @len: the maximum length of @p
518 * @c: a Unicode character
520 * Finds the leftmost occurrence of the given Unicode character
521 * in a UTF-8 encoded string, while limiting the search to @len bytes.
522 * If @len is -1, allow unbounded search.
524 * Return value: %NULL if the string does not contain the character,
525 * otherwise, a pointer to the start of the leftmost occurrence of
526 * the character in the string.
528 gchar *
529 g_utf8_strchr (const char *p,
530 gssize len,
531 gunichar c)
533 gchar ch[10];
535 gint charlen = g_unichar_to_utf8 (c, ch);
536 ch[charlen] = '\0';
538 return g_strstr_len (p, len, ch);
543 * g_utf8_strrchr:
544 * @p: a nul-terminated UTF-8 encoded string
545 * @len: the maximum length of @p
546 * @c: a Unicode character
548 * Find the rightmost occurrence of the given Unicode character
549 * in a UTF-8 encoded string, while limiting the search to @len bytes.
550 * If @len is -1, allow unbounded search.
552 * Return value: %NULL if the string does not contain the character,
553 * otherwise, a pointer to the start of the rightmost occurrence of the
554 * character in the string.
556 gchar *
557 g_utf8_strrchr (const char *p,
558 gssize len,
559 gunichar c)
561 gchar ch[10];
563 gint charlen = g_unichar_to_utf8 (c, ch);
564 ch[charlen] = '\0';
566 return g_strrstr_len (p, len, ch);
570 /* Like g_utf8_get_char, but take a maximum length
571 * and return (gunichar)-2 on incomplete trailing character;
572 * also check for malformed or overlong sequences
573 * and return (gunichar)-1 in this case.
575 static inline gunichar
576 g_utf8_get_char_extended (const gchar *p,
577 gssize max_len)
579 guint i, len;
580 gunichar min_code;
581 gunichar wc = (guchar) *p;
583 if (wc < 0x80)
585 return wc;
587 else if (G_UNLIKELY (wc < 0xc0))
589 return (gunichar)-1;
591 else if (wc < 0xe0)
593 len = 2;
594 wc &= 0x1f;
595 min_code = 1 << 7;
597 else if (wc < 0xf0)
599 len = 3;
600 wc &= 0x0f;
601 min_code = 1 << 11;
603 else if (wc < 0xf8)
605 len = 4;
606 wc &= 0x07;
607 min_code = 1 << 16;
609 else if (wc < 0xfc)
611 len = 5;
612 wc &= 0x03;
613 min_code = 1 << 21;
615 else if (wc < 0xfe)
617 len = 6;
618 wc &= 0x01;
619 min_code = 1 << 26;
621 else
623 return (gunichar)-1;
626 if (G_UNLIKELY (max_len >= 0 && len > max_len))
628 for (i = 1; i < max_len; i++)
630 if ((((guchar *)p)[i] & 0xc0) != 0x80)
631 return (gunichar)-1;
633 return (gunichar)-2;
636 for (i = 1; i < len; ++i)
638 gunichar ch = ((guchar *)p)[i];
640 if (G_UNLIKELY ((ch & 0xc0) != 0x80))
642 if (ch)
643 return (gunichar)-1;
644 else
645 return (gunichar)-2;
648 wc <<= 6;
649 wc |= (ch & 0x3f);
652 if (G_UNLIKELY (wc < min_code))
653 return (gunichar)-1;
655 return wc;
659 * g_utf8_get_char_validated:
660 * @p: a pointer to Unicode character encoded as UTF-8
661 * @max_len: the maximum number of bytes to read, or -1, for no maximum or
662 * if @p is nul-terminated
664 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
665 * This function checks for incomplete characters, for invalid characters
666 * such as characters that are out of the range of Unicode, and for
667 * overlong encodings of valid characters.
669 * Return value: the resulting character. If @p points to a partial
670 * sequence at the end of a string that could begin a valid
671 * character (or if @max_len is zero), returns (gunichar)-2;
672 * otherwise, if @p does not point to a valid UTF-8 encoded
673 * Unicode character, returns (gunichar)-1.
675 gunichar
676 g_utf8_get_char_validated (const gchar *p,
677 gssize max_len)
679 gunichar result;
681 if (max_len == 0)
682 return (gunichar)-2;
684 result = g_utf8_get_char_extended (p, max_len);
686 if (result & 0x80000000)
687 return result;
688 else if (!UNICODE_VALID (result))
689 return (gunichar)-1;
690 else
691 return result;
695 * g_utf8_to_ucs4_fast:
696 * @str: a UTF-8 encoded string
697 * @len: the maximum length of @str to use, in bytes. If @len < 0,
698 * then the string is nul-terminated.
699 * @items_written: location to store the number of characters in the
700 * result, or %NULL.
702 * Convert a string from UTF-8 to a 32-bit fixed width
703 * representation as UCS-4, assuming valid UTF-8 input.
704 * This function is roughly twice as fast as g_utf8_to_ucs4()
705 * but does no error checking on the input. A trailing 0 character
706 * will be added to the string after the converted text.
708 * Return value: a pointer to a newly allocated UCS-4 string.
709 * This value must be freed with g_free().
711 gunichar *
712 g_utf8_to_ucs4_fast (const gchar *str,
713 glong len,
714 glong *items_written)
716 gunichar *result;
717 gint n_chars, i;
718 const gchar *p;
720 g_return_val_if_fail (str != NULL, NULL);
722 p = str;
723 n_chars = 0;
724 if (len < 0)
726 while (*p)
728 p = g_utf8_next_char (p);
729 ++n_chars;
732 else
734 while (p < str + len && *p)
736 p = g_utf8_next_char (p);
737 ++n_chars;
741 result = g_new (gunichar, n_chars + 1);
743 p = str;
744 for (i=0; i < n_chars; i++)
746 gunichar wc = (guchar)*p++;
748 if (wc < 0x80)
750 result[i] = wc;
752 else
754 gunichar mask = 0x40;
756 if (G_UNLIKELY ((wc & mask) == 0))
758 /* It's an out-of-sequence 10xxxxxxx byte.
759 * Rather than making an ugly hash of this and the next byte
760 * and overrunning the buffer, it's more useful to treat it
761 * with a replacement character */
762 result[i] = 0xfffd;
763 continue;
768 wc <<= 6;
769 wc |= (guchar)(*p++) & 0x3f;
770 mask <<= 5;
772 while((wc & mask) != 0);
774 wc &= mask - 1;
776 result[i] = wc;
779 result[i] = 0;
781 if (items_written)
782 *items_written = i;
784 return result;
788 * g_utf8_to_ucs4:
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_read: location to store number of bytes read, or %NULL.
793 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
794 * returned in case @str contains a trailing partial
795 * character. If an error occurs then the index of the
796 * invalid input is stored here.
797 * @items_written: location to store number of characters written or %NULL.
798 * The value here stored does not include the trailing 0
799 * character.
800 * @error: location to store the error occurring, or %NULL to ignore
801 * errors. Any of the errors in #GConvertError other than
802 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
804 * Convert a string from UTF-8 to a 32-bit fixed width
805 * representation as UCS-4. A trailing 0 character will be added to the
806 * string after the converted text.
808 * Return value: a pointer to a newly allocated UCS-4 string.
809 * This value must be freed with g_free(). If an
810 * error occurs, %NULL will be returned and
811 * @error set.
813 gunichar *
814 g_utf8_to_ucs4 (const gchar *str,
815 glong len,
816 glong *items_read,
817 glong *items_written,
818 GError **error)
820 gunichar *result = NULL;
821 gint n_chars, i;
822 const gchar *in;
824 in = str;
825 n_chars = 0;
826 while ((len < 0 || str + len - in > 0) && *in)
828 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
829 if (wc & 0x80000000)
831 if (wc == (gunichar)-2)
833 if (items_read)
834 break;
835 else
836 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
837 _("Partial character sequence at end of input"));
839 else
840 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
841 _("Invalid byte sequence in conversion input"));
843 goto err_out;
846 n_chars++;
848 in = g_utf8_next_char (in);
851 result = g_new (gunichar, n_chars + 1);
853 in = str;
854 for (i=0; i < n_chars; i++)
856 result[i] = g_utf8_get_char (in);
857 in = g_utf8_next_char (in);
859 result[i] = 0;
861 if (items_written)
862 *items_written = n_chars;
864 err_out:
865 if (items_read)
866 *items_read = in - str;
868 return result;
872 * g_ucs4_to_utf8:
873 * @str: a UCS-4 encoded string
874 * @len: the maximum length (number of characters) of @str to use.
875 * If @len < 0, then the string is nul-terminated.
876 * @items_read: location to store number of characters read, or %NULL.
877 * @items_written: location to store number of bytes written or %NULL.
878 * The value here stored does not include the trailing 0
879 * byte.
880 * @error: location to store the error occurring, or %NULL to ignore
881 * errors. Any of the errors in #GConvertError other than
882 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
884 * Convert a string from a 32-bit fixed width representation as UCS-4.
885 * to UTF-8. The result will be terminated with a 0 byte.
887 * Return value: a pointer to a newly allocated UTF-8 string.
888 * This value must be freed with g_free(). If an
889 * error occurs, %NULL will be returned and
890 * @error set. In that case, @items_read will be
891 * set to the position of the first invalid input
892 * character.
894 gchar *
895 g_ucs4_to_utf8 (const gunichar *str,
896 glong len,
897 glong *items_read,
898 glong *items_written,
899 GError **error)
901 gint result_length;
902 gchar *result = NULL;
903 gchar *p;
904 gint i;
906 result_length = 0;
907 for (i = 0; len < 0 || i < len ; i++)
909 if (!str[i])
910 break;
912 if (str[i] >= 0x80000000)
914 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
915 _("Character out of range for UTF-8"));
916 goto err_out;
919 result_length += UTF8_LENGTH (str[i]);
922 result = g_malloc (result_length + 1);
923 p = result;
925 i = 0;
926 while (p < result + result_length)
927 p += g_unichar_to_utf8 (str[i++], p);
929 *p = '\0';
931 if (items_written)
932 *items_written = p - result;
934 err_out:
935 if (items_read)
936 *items_read = i;
938 return result;
941 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
944 * g_utf16_to_utf8:
945 * @str: a UTF-16 encoded string
946 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
947 * If @len < 0, then the string is nul-terminated.
948 * @items_read: location to store number of words read, or %NULL.
949 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
950 * returned in case @str contains a trailing partial
951 * character. If an error occurs then the index of the
952 * invalid input is stored here.
953 * @items_written: location to store number of bytes written, or %NULL.
954 * The value stored here does not include the trailing
955 * 0 byte.
956 * @error: location to store the error occurring, or %NULL to ignore
957 * errors. Any of the errors in #GConvertError other than
958 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
960 * Convert a string from UTF-16 to UTF-8. The result will be
961 * terminated with a 0 byte.
963 * Note that the input is expected to be already in native endianness,
964 * an initial byte-order-mark character is not handled specially.
965 * g_convert() can be used to convert a byte buffer of UTF-16 data of
966 * ambiguous endianess.
968 * Further note that this function does not validate the result
969 * string; it may e.g. include embedded NUL characters. The only
970 * validation done by this function is to ensure that the input can
971 * be correctly interpreted as UTF-16, i.e. it doesn't contain
972 * things unpaired surrogates.
974 * Return value: a pointer to a newly allocated UTF-8 string.
975 * This value must be freed with g_free(). If an
976 * error occurs, %NULL will be returned and
977 * @error set.
979 gchar *
980 g_utf16_to_utf8 (const gunichar2 *str,
981 glong len,
982 glong *items_read,
983 glong *items_written,
984 GError **error)
986 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
987 * are marked.
989 const gunichar2 *in;
990 gchar *out;
991 gchar *result = NULL;
992 gint n_bytes;
993 gunichar high_surrogate;
995 g_return_val_if_fail (str != NULL, NULL);
997 n_bytes = 0;
998 in = str;
999 high_surrogate = 0;
1000 while ((len < 0 || in - str < len) && *in)
1002 gunichar2 c = *in;
1003 gunichar wc;
1005 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1007 if (high_surrogate)
1009 wc = SURROGATE_VALUE (high_surrogate, c);
1010 high_surrogate = 0;
1012 else
1014 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1015 _("Invalid sequence in conversion input"));
1016 goto err_out;
1019 else
1021 if (high_surrogate)
1023 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1024 _("Invalid sequence in conversion input"));
1025 goto err_out;
1028 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1030 high_surrogate = c;
1031 goto next1;
1033 else
1034 wc = c;
1037 /********** DIFFERENT for UTF8/UCS4 **********/
1038 n_bytes += UTF8_LENGTH (wc);
1040 next1:
1041 in++;
1044 if (high_surrogate && !items_read)
1046 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1047 _("Partial character sequence at end of input"));
1048 goto err_out;
1051 /* At this point, everything is valid, and we just need to convert
1053 /********** DIFFERENT for UTF8/UCS4 **********/
1054 result = g_malloc (n_bytes + 1);
1056 high_surrogate = 0;
1057 out = result;
1058 in = str;
1059 while (out < result + n_bytes)
1061 gunichar2 c = *in;
1062 gunichar wc;
1064 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1066 wc = SURROGATE_VALUE (high_surrogate, c);
1067 high_surrogate = 0;
1069 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1071 high_surrogate = c;
1072 goto next2;
1074 else
1075 wc = c;
1077 /********** DIFFERENT for UTF8/UCS4 **********/
1078 out += g_unichar_to_utf8 (wc, out);
1080 next2:
1081 in++;
1084 /********** DIFFERENT for UTF8/UCS4 **********/
1085 *out = '\0';
1087 if (items_written)
1088 /********** DIFFERENT for UTF8/UCS4 **********/
1089 *items_written = out - result;
1091 err_out:
1092 if (items_read)
1093 *items_read = in - str;
1095 return result;
1099 * g_utf16_to_ucs4:
1100 * @str: a UTF-16 encoded string
1101 * @len: the maximum length (number of <type>gunichar2</type>) of @str to use.
1102 * If @len < 0, then the string is nul-terminated.
1103 * @items_read: location to store number of words read, or %NULL.
1104 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1105 * returned in case @str contains a trailing partial
1106 * character. If an error occurs then the index of the
1107 * invalid input is stored here.
1108 * @items_written: location to store number of characters written, or %NULL.
1109 * The value stored here does not include the trailing
1110 * 0 character.
1111 * @error: location to store the error occurring, or %NULL to ignore
1112 * errors. Any of the errors in #GConvertError other than
1113 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1115 * Convert a string from UTF-16 to UCS-4. The result will be
1116 * nul-terminated.
1118 * Return value: a pointer to a newly allocated UCS-4 string.
1119 * This value must be freed with g_free(). If an
1120 * error occurs, %NULL will be returned and
1121 * @error set.
1123 gunichar *
1124 g_utf16_to_ucs4 (const gunichar2 *str,
1125 glong len,
1126 glong *items_read,
1127 glong *items_written,
1128 GError **error)
1130 const gunichar2 *in;
1131 gchar *out;
1132 gchar *result = NULL;
1133 gint n_bytes;
1134 gunichar high_surrogate;
1136 g_return_val_if_fail (str != NULL, NULL);
1138 n_bytes = 0;
1139 in = str;
1140 high_surrogate = 0;
1141 while ((len < 0 || in - str < len) && *in)
1143 gunichar2 c = *in;
1145 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1147 if (high_surrogate)
1149 high_surrogate = 0;
1151 else
1153 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1154 _("Invalid sequence in conversion input"));
1155 goto err_out;
1158 else
1160 if (high_surrogate)
1162 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163 _("Invalid sequence in conversion input"));
1164 goto err_out;
1167 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1169 high_surrogate = c;
1170 goto next1;
1174 /********** DIFFERENT for UTF8/UCS4 **********/
1175 n_bytes += sizeof (gunichar);
1177 next1:
1178 in++;
1181 if (high_surrogate && !items_read)
1183 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1184 _("Partial character sequence at end of input"));
1185 goto err_out;
1188 /* At this point, everything is valid, and we just need to convert
1190 /********** DIFFERENT for UTF8/UCS4 **********/
1191 result = g_malloc (n_bytes + 4);
1193 high_surrogate = 0;
1194 out = result;
1195 in = str;
1196 while (out < result + n_bytes)
1198 gunichar2 c = *in;
1199 gunichar wc;
1201 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1203 wc = SURROGATE_VALUE (high_surrogate, c);
1204 high_surrogate = 0;
1206 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1208 high_surrogate = c;
1209 goto next2;
1211 else
1212 wc = c;
1214 /********** DIFFERENT for UTF8/UCS4 **********/
1215 *(gunichar *)out = wc;
1216 out += sizeof (gunichar);
1218 next2:
1219 in++;
1222 /********** DIFFERENT for UTF8/UCS4 **********/
1223 *(gunichar *)out = 0;
1225 if (items_written)
1226 /********** DIFFERENT for UTF8/UCS4 **********/
1227 *items_written = (out - result) / sizeof (gunichar);
1229 err_out:
1230 if (items_read)
1231 *items_read = in - str;
1233 return (gunichar *)result;
1237 * g_utf8_to_utf16:
1238 * @str: a UTF-8 encoded string
1239 * @len: the maximum length (number of bytes) of @str to use.
1240 * If @len < 0, then the string is nul-terminated.
1241 * @items_read: location to store number of bytes read, or %NULL.
1242 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1243 * returned in case @str contains a trailing partial
1244 * character. If an error occurs then the index of the
1245 * invalid input is stored here.
1246 * @items_written: location to store number of <type>gunichar2</type> written,
1247 * or %NULL.
1248 * The value stored here does not include the trailing 0.
1249 * @error: location to store the error occurring, or %NULL to ignore
1250 * errors. Any of the errors in #GConvertError other than
1251 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1253 * Convert a string from UTF-8 to UTF-16. A 0 character will be
1254 * added to the result after the converted text.
1256 * Return value: a pointer to a newly allocated UTF-16 string.
1257 * This value must be freed with g_free(). If an
1258 * error occurs, %NULL will be returned and
1259 * @error set.
1261 gunichar2 *
1262 g_utf8_to_utf16 (const gchar *str,
1263 glong len,
1264 glong *items_read,
1265 glong *items_written,
1266 GError **error)
1268 gunichar2 *result = NULL;
1269 gint n16;
1270 const gchar *in;
1271 gint i;
1273 g_return_val_if_fail (str != NULL, NULL);
1275 in = str;
1276 n16 = 0;
1277 while ((len < 0 || str + len - in > 0) && *in)
1279 gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1280 if (wc & 0x80000000)
1282 if (wc == (gunichar)-2)
1284 if (items_read)
1285 break;
1286 else
1287 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1288 _("Partial character sequence at end of input"));
1290 else
1291 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1292 _("Invalid byte sequence in conversion input"));
1294 goto err_out;
1297 if (wc < 0xd800)
1298 n16 += 1;
1299 else if (wc < 0xe000)
1301 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1302 _("Invalid sequence in conversion input"));
1304 goto err_out;
1306 else if (wc < 0x10000)
1307 n16 += 1;
1308 else if (wc < 0x110000)
1309 n16 += 2;
1310 else
1312 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1313 _("Character out of range for UTF-16"));
1315 goto err_out;
1318 in = g_utf8_next_char (in);
1321 result = g_new (gunichar2, n16 + 1);
1323 in = str;
1324 for (i = 0; i < n16;)
1326 gunichar wc = g_utf8_get_char (in);
1328 if (wc < 0x10000)
1330 result[i++] = wc;
1332 else
1334 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1335 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1338 in = g_utf8_next_char (in);
1341 result[i] = 0;
1343 if (items_written)
1344 *items_written = n16;
1346 err_out:
1347 if (items_read)
1348 *items_read = in - str;
1350 return result;
1354 * g_ucs4_to_utf16:
1355 * @str: a UCS-4 encoded string
1356 * @len: the maximum length (number of characters) of @str to use.
1357 * If @len < 0, then the string is nul-terminated.
1358 * @items_read: location to store number of bytes read, or %NULL.
1359 * If an error occurs then the index of the invalid input
1360 * is stored here.
1361 * @items_written: location to store number of <type>gunichar2</type>
1362 * written, or %NULL. The value stored here does not
1363 * include the trailing 0.
1364 * @error: location to store the error occurring, or %NULL to ignore
1365 * errors. Any of the errors in #GConvertError other than
1366 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1368 * Convert a string from UCS-4 to UTF-16. A 0 character will be
1369 * added to the result after the converted text.
1371 * Return value: a pointer to a newly allocated UTF-16 string.
1372 * This value must be freed with g_free(). If an
1373 * error occurs, %NULL will be returned and
1374 * @error set.
1376 gunichar2 *
1377 g_ucs4_to_utf16 (const gunichar *str,
1378 glong len,
1379 glong *items_read,
1380 glong *items_written,
1381 GError **error)
1383 gunichar2 *result = NULL;
1384 gint n16;
1385 gint i, j;
1387 n16 = 0;
1388 i = 0;
1389 while ((len < 0 || i < len) && str[i])
1391 gunichar wc = str[i];
1393 if (wc < 0xd800)
1394 n16 += 1;
1395 else if (wc < 0xe000)
1397 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1398 _("Invalid sequence in conversion input"));
1400 goto err_out;
1402 else if (wc < 0x10000)
1403 n16 += 1;
1404 else if (wc < 0x110000)
1405 n16 += 2;
1406 else
1408 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1409 _("Character out of range for UTF-16"));
1411 goto err_out;
1414 i++;
1417 result = g_new (gunichar2, n16 + 1);
1419 for (i = 0, j = 0; j < n16; i++)
1421 gunichar wc = str[i];
1423 if (wc < 0x10000)
1425 result[j++] = wc;
1427 else
1429 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1430 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1433 result[j] = 0;
1435 if (items_written)
1436 *items_written = n16;
1438 err_out:
1439 if (items_read)
1440 *items_read = i;
1442 return result;
1445 #define CONTINUATION_CHAR \
1446 G_STMT_START { \
1447 if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1448 goto error; \
1449 val <<= 6; \
1450 val |= (*(guchar *)p) & 0x3f; \
1451 } G_STMT_END
1453 static const gchar *
1454 fast_validate (const char *str)
1457 gunichar val = 0;
1458 gunichar min = 0;
1459 const gchar *p;
1461 for (p = str; *p; p++)
1463 if (*(guchar *)p < 128)
1464 /* done */;
1465 else
1467 const gchar *last;
1469 last = p;
1470 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1472 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1473 goto error;
1474 p++;
1475 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1476 goto error;
1478 else
1480 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1482 min = (1 << 11);
1483 val = *(guchar *)p & 0x0f;
1484 goto TWO_REMAINING;
1486 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1488 min = (1 << 16);
1489 val = *(guchar *)p & 0x07;
1491 else
1492 goto error;
1494 p++;
1495 CONTINUATION_CHAR;
1496 TWO_REMAINING:
1497 p++;
1498 CONTINUATION_CHAR;
1499 p++;
1500 CONTINUATION_CHAR;
1502 if (G_UNLIKELY (val < min))
1503 goto error;
1505 if (G_UNLIKELY (!UNICODE_VALID(val)))
1506 goto error;
1509 continue;
1511 error:
1512 return last;
1516 return p;
1519 static const gchar *
1520 fast_validate_len (const char *str,
1521 gssize max_len)
1524 gunichar val = 0;
1525 gunichar min = 0;
1526 const gchar *p;
1528 g_assert (max_len >= 0);
1530 for (p = str; ((p - str) < max_len) && *p; p++)
1532 if (*(guchar *)p < 128)
1533 /* done */;
1534 else
1536 const gchar *last;
1538 last = p;
1539 if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1541 if (G_UNLIKELY (max_len - (p - str) < 2))
1542 goto error;
1544 if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1545 goto error;
1546 p++;
1547 if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1548 goto error;
1550 else
1552 if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1554 if (G_UNLIKELY (max_len - (p - str) < 3))
1555 goto error;
1557 min = (1 << 11);
1558 val = *(guchar *)p & 0x0f;
1559 goto TWO_REMAINING;
1561 else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1563 if (G_UNLIKELY (max_len - (p - str) < 4))
1564 goto error;
1566 min = (1 << 16);
1567 val = *(guchar *)p & 0x07;
1569 else
1570 goto error;
1572 p++;
1573 CONTINUATION_CHAR;
1574 TWO_REMAINING:
1575 p++;
1576 CONTINUATION_CHAR;
1577 p++;
1578 CONTINUATION_CHAR;
1580 if (G_UNLIKELY (val < min))
1581 goto error;
1582 if (G_UNLIKELY (!UNICODE_VALID(val)))
1583 goto error;
1586 continue;
1588 error:
1589 return last;
1593 return p;
1597 * g_utf8_validate:
1598 * @str: a pointer to character data
1599 * @max_len: max bytes to validate, or -1 to go until NUL
1600 * @end: (allow-none) (out): return location for end of valid data
1602 * Validates UTF-8 encoded text. @str is the text to validate;
1603 * if @str is nul-terminated, then @max_len can be -1, otherwise
1604 * @max_len should be the number of bytes to validate.
1605 * If @end is non-%NULL, then the end of the valid range
1606 * will be stored there (i.e. the start of the first invalid
1607 * character if some bytes were invalid, or the end of the text
1608 * being validated otherwise).
1610 * Note that g_utf8_validate() returns %FALSE if @max_len is
1611 * positive and any of the @max_len bytes are NUL.
1613 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1614 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1615 * so data read from a file or the network should be checked
1616 * with g_utf8_validate() before doing anything else with it.
1618 * Return value: %TRUE if the text was valid UTF-8
1620 gboolean
1621 g_utf8_validate (const char *str,
1622 gssize max_len,
1623 const gchar **end)
1626 const gchar *p;
1628 if (max_len < 0)
1629 p = fast_validate (str);
1630 else
1631 p = fast_validate_len (str, max_len);
1633 if (end)
1634 *end = p;
1636 if ((max_len >= 0 && p != str + max_len) ||
1637 (max_len < 0 && *p != '\0'))
1638 return FALSE;
1639 else
1640 return TRUE;
1644 * g_unichar_validate:
1645 * @ch: a Unicode character
1647 * Checks whether @ch is a valid Unicode character. Some possible
1648 * integer values of @ch will not be valid. 0 is considered a valid
1649 * character, though it's normally a string terminator.
1651 * Return value: %TRUE if @ch is a valid Unicode character
1653 gboolean
1654 g_unichar_validate (gunichar ch)
1656 return UNICODE_VALID (ch);
1660 * g_utf8_strreverse:
1661 * @str: a UTF-8 encoded string
1662 * @len: the maximum length of @str to use, in bytes. If @len < 0,
1663 * then the string is nul-terminated.
1665 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1666 * (Use g_utf8_validate() on all text before trying to use UTF-8
1667 * utility functions with it.)
1669 * This function is intended for programmatic uses of reversed strings.
1670 * It pays no attention to decomposed characters, combining marks, byte
1671 * order marks, directional indicators (LRM, LRO, etc) and similar
1672 * characters which might need special handling when reversing a string
1673 * for display purposes.
1675 * Note that unlike g_strreverse(), this function returns
1676 * newly-allocated memory, which should be freed with g_free() when
1677 * no longer needed.
1679 * Returns: a newly-allocated string which is the reverse of @str.
1681 * Since: 2.2
1683 gchar *
1684 g_utf8_strreverse (const gchar *str,
1685 gssize len)
1687 gchar *r, *result;
1688 const gchar *p;
1690 if (len < 0)
1691 len = strlen (str);
1693 result = g_new (gchar, len + 1);
1694 r = result + len;
1695 p = str;
1696 while (r > result)
1698 gchar *m, skip = g_utf8_skip[*(guchar*) p];
1699 r -= skip;
1700 for (m = r; skip; skip--)
1701 *m++ = *p++;
1703 result[len] = 0;
1705 return result;
1709 gchar *
1710 _g_utf8_make_valid (const gchar *name)
1712 GString *string;
1713 const gchar *remainder, *invalid;
1714 gint remaining_bytes, valid_bytes;
1716 g_return_val_if_fail (name != NULL, NULL);
1718 string = NULL;
1719 remainder = name;
1720 remaining_bytes = strlen (name);
1722 while (remaining_bytes != 0)
1724 if (g_utf8_validate (remainder, remaining_bytes, &invalid))
1725 break;
1726 valid_bytes = invalid - remainder;
1728 if (string == NULL)
1729 string = g_string_sized_new (remaining_bytes);
1731 g_string_append_len (string, remainder, valid_bytes);
1732 /* append U+FFFD REPLACEMENT CHARACTER */
1733 g_string_append (string, "\357\277\275");
1735 remaining_bytes -= valid_bytes + 1;
1736 remainder = invalid + 1;
1739 if (string == NULL)
1740 return g_strdup (name);
1742 g_string_append (string, remainder);
1744 g_assert (g_utf8_validate (string->str, -1, NULL));
1746 return g_string_free (string, FALSE);