Remove the semicolon from the definition of g_once(), so that
[glib.git] / glib / gutf8.c
blob88627a21eccfb2d1a01597abf956f088624ea094
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 #include "glib.h"
32 #ifdef G_PLATFORM_WIN32
33 #include <stdio.h>
34 #define STRICT
35 #include <windows.h>
36 #undef STRICT
37 #endif
39 #include "libcharset/libcharset.h"
41 #include "glibintl.h"
43 #define UTF8_COMPUTE(Char, Mask, Len) \
44 if (Char < 128) \
45 { \
46 Len = 1; \
47 Mask = 0x7f; \
48 } \
49 else if ((Char & 0xe0) == 0xc0) \
50 { \
51 Len = 2; \
52 Mask = 0x1f; \
53 } \
54 else if ((Char & 0xf0) == 0xe0) \
55 { \
56 Len = 3; \
57 Mask = 0x0f; \
58 } \
59 else if ((Char & 0xf8) == 0xf0) \
60 { \
61 Len = 4; \
62 Mask = 0x07; \
63 } \
64 else if ((Char & 0xfc) == 0xf8) \
65 { \
66 Len = 5; \
67 Mask = 0x03; \
68 } \
69 else if ((Char & 0xfe) == 0xfc) \
70 { \
71 Len = 6; \
72 Mask = 0x01; \
73 } \
74 else \
75 Len = -1;
77 #define UTF8_LENGTH(Char) \
78 ((Char) < 0x80 ? 1 : \
79 ((Char) < 0x800 ? 2 : \
80 ((Char) < 0x10000 ? 3 : \
81 ((Char) < 0x200000 ? 4 : \
82 ((Char) < 0x4000000 ? 5 : 6)))))
85 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
86 (Result) = (Chars)[0] & (Mask); \
87 for ((Count) = 1; (Count) < (Len); ++(Count)) \
88 { \
89 if (((Chars)[(Count)] & 0xc0) != 0x80) \
90 { \
91 (Result) = -1; \
92 break; \
93 } \
94 (Result) <<= 6; \
95 (Result) |= ((Chars)[(Count)] & 0x3f); \
98 #define UNICODE_VALID(Char) \
99 ((Char) < 0x110000 && \
100 (((Char) & 0xFFFFF800) != 0xD800) && \
101 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
102 ((Char) & 0xFFFE) != 0xFFFE)
105 static const gchar utf8_skip_data[256] = {
106 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,
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 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,
113 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
116 const gchar * const g_utf8_skip = utf8_skip_data;
119 * g_utf8_find_prev_char:
120 * @str: pointer to the beginning of a UTF-8 encoded string
121 * @p: pointer to some position within @str
123 * Given a position @p with a UTF-8 encoded string @str, find the start
124 * of the previous UTF-8 character starting before @p. Returns %NULL if no
125 * UTF-8 characters are present in @p before @str.
127 * @p does not have to be at the beginning of a UTF-8 character. No check
128 * is made to see if the character found is actually valid other than
129 * it starts with an appropriate byte.
131 * Return value: a pointer to the found character or %NULL.
133 gchar *
134 g_utf8_find_prev_char (const char *str,
135 const char *p)
137 for (--p; p >= str; --p)
139 if ((*p & 0xc0) != 0x80)
140 return (gchar *)p;
142 return NULL;
146 * g_utf8_find_next_char:
147 * @p: a pointer to a position within a UTF-8 encoded string
148 * @end: a pointer to the end of the string, or %NULL to indicate
149 * that the string is nul-terminated, in which case
150 * the returned value will be
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
160 gchar *
161 g_utf8_find_next_char (const gchar *p,
162 const gchar *end)
164 if (*p)
166 if (end)
167 for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
169 else
170 for (++p; (*p & 0xc0) == 0x80; ++p)
173 return (p == end) ? NULL : (gchar *)p;
177 * g_utf8_prev_char:
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.
189 gchar *
190 g_utf8_prev_char (const gchar *p)
192 while (TRUE)
194 p--;
195 if ((*p & 0xc0) != 0x80)
196 return (gchar *)p;
201 * g_utf8_strlen:
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
206 * may be %NULL.
208 * Returns the length of the string in characters.
210 * Return value: the length of the string in characters
212 glong
213 g_utf8_strlen (const gchar *p,
214 gssize max)
216 glong len = 0;
217 const gchar *start = p;
218 g_return_val_if_fail (p != NULL || max == 0, 0);
220 if (max < 0)
222 while (*p)
224 p = g_utf8_next_char (p);
225 ++len;
228 else
230 if (max == 0 || !*p)
231 return 0;
233 p = g_utf8_next_char (p);
235 while (p - start < max && *p)
237 ++len;
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)
245 ++len;
248 return len;
252 * g_utf8_get_char:
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()
259 * instead.
261 * Return value: the resulting character
263 gunichar
264 g_utf8_get_char (const gchar *p)
266 int i, mask = 0, len;
267 gunichar result;
268 unsigned char c = (unsigned char) *p;
270 UTF8_COMPUTE (c, mask, len);
271 if (len == -1)
272 return (gunichar)-1;
273 UTF8_GET (result, p, i, mask, len);
275 return result;
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
284 * within the string.
286 * Return value: the resulting pointer
288 gchar *
289 g_utf8_offset_to_pointer (const gchar *str,
290 glong offset)
292 const gchar *s = str;
293 while (offset--)
294 s = g_utf8_next_char (s);
296 return (gchar *)s;
300 * g_utf8_pointer_to_offset:
301 * @str: a UTF-8 encoded string
302 * @pos: a pointer to a position within @str
304 * Converts from a pointer to position within a string to a integer
305 * character offset.
307 * Return value: the resulting character offset
309 glong
310 g_utf8_pointer_to_offset (const gchar *str,
311 const gchar *pos)
313 const gchar *s = str;
314 glong offset = 0;
316 while (s < pos)
318 s = g_utf8_next_char (s);
319 offset++;
322 return offset;
327 * g_utf8_strncpy:
328 * @dest: buffer to fill with characters from @src
329 * @src: UTF-8 encoded string
330 * @n: character count
332 * Like the standard C strncpy() function, but
333 * copies a given number of characters instead of a given number of
334 * bytes. The @src string must be valid UTF-8 encoded text.
335 * (Use g_utf8_validate() on all text before trying to use UTF-8
336 * utility functions with it.)
338 * Return value: @dest
340 gchar *
341 g_utf8_strncpy (gchar *dest,
342 const gchar *src,
343 gsize n)
345 const gchar *s = src;
346 while (n && *s)
348 s = g_utf8_next_char(s);
349 n--;
351 strncpy(dest, src, s - src);
352 dest[s - src] = 0;
353 return dest;
356 G_LOCK_DEFINE_STATIC (aliases);
358 static GHashTable *
359 get_alias_hash (void)
361 static GHashTable *alias_hash = NULL;
362 const char *aliases;
364 G_LOCK (aliases);
366 if (!alias_hash)
368 alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
370 aliases = _g_locale_get_charset_aliases ();
371 while (*aliases != '\0')
373 const char *canonical;
374 const char *alias;
375 const char **alias_array;
376 int count = 0;
378 alias = aliases;
379 aliases += strlen (aliases) + 1;
380 canonical = aliases;
381 aliases += strlen (aliases) + 1;
383 alias_array = g_hash_table_lookup (alias_hash, canonical);
384 if (alias_array)
386 while (alias_array[count])
387 count++;
390 alias_array = g_renew (const char *, alias_array, count + 2);
391 alias_array[count] = alias;
392 alias_array[count + 1] = NULL;
394 g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
398 G_UNLOCK (aliases);
400 return alias_hash;
403 /* As an abuse of the alias table, the following routines gets
404 * the charsets that are aliases for the canonical name.
406 const char **
407 _g_charset_get_aliases (const char *canonical_name)
409 GHashTable *alias_hash = get_alias_hash ();
411 return g_hash_table_lookup (alias_hash, canonical_name);
414 static gboolean
415 g_utf8_get_charset_internal (const char *raw_data,
416 const char **a)
418 const char *charset = getenv("CHARSET");
420 if (charset && *charset)
422 *a = charset;
424 if (charset && strstr (charset, "UTF-8"))
425 return TRUE;
426 else
427 return FALSE;
430 /* The libcharset code tries to be thread-safe without
431 * a lock, but has a memory leak and a missing memory
432 * barrier, so we lock for it
434 G_LOCK (aliases);
435 charset = _g_locale_charset_unalias (raw_data);
436 G_UNLOCK (aliases);
438 if (charset && *charset)
440 *a = charset;
442 if (charset && strstr (charset, "UTF-8"))
443 return TRUE;
444 else
445 return FALSE;
448 /* Assume this for compatibility at present. */
449 *a = "US-ASCII";
451 return FALSE;
454 typedef struct _GCharsetCache GCharsetCache;
456 struct _GCharsetCache {
457 gboolean is_utf8;
458 gchar *raw;
459 gchar *charset;
462 static void
463 charset_cache_free (gpointer data)
465 GCharsetCache *cache = data;
466 g_free (cache->raw);
467 g_free (cache->charset);
468 g_free (cache);
472 * g_get_charset:
473 * @charset: return location for character set name
475 * Obtains the character set for the current locale; you might use
476 * this character set as an argument to g_convert(), to convert from
477 * the current locale's encoding to some other encoding. (Frequently
478 * g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts,
479 * though.)
481 * The return value is %TRUE if the locale's encoding is UTF-8, in that
482 * case you can perhaps avoid calling g_convert().
484 * The string returned in @charset is not allocated, and should not be
485 * freed.
487 * Return value: %TRUE if the returned charset is UTF-8
489 gboolean
490 g_get_charset (G_CONST_RETURN char **charset)
492 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
493 GCharsetCache *cache = g_static_private_get (&cache_private);
494 const gchar *raw;
496 if (!cache)
498 cache = g_new0 (GCharsetCache, 1);
499 g_static_private_set (&cache_private, cache, charset_cache_free);
502 raw = _g_locale_charset_raw ();
504 if (!(cache->raw && strcmp (cache->raw, raw) == 0))
506 const gchar *new_charset;
508 g_free (cache->raw);
509 g_free (cache->charset);
510 cache->raw = g_strdup (raw);
511 cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
512 cache->charset = g_strdup (new_charset);
515 if (charset)
516 *charset = cache->charset;
518 return cache->is_utf8;
521 /* unicode_strchr */
524 * g_unichar_to_utf8:
525 * @c: a ISO10646 character code
526 * @outbuf: output buffer, must have at least 6 bytes of space.
527 * If %NULL, the length will be computed and returned
528 * and nothing will be written to @outbuf.
530 * Converts a single character to UTF-8.
532 * Return value: number of bytes written
535 g_unichar_to_utf8 (gunichar c,
536 gchar *outbuf)
538 guint len = 0;
539 int first;
540 int i;
542 if (c < 0x80)
544 first = 0;
545 len = 1;
547 else if (c < 0x800)
549 first = 0xc0;
550 len = 2;
552 else if (c < 0x10000)
554 first = 0xe0;
555 len = 3;
557 else if (c < 0x200000)
559 first = 0xf0;
560 len = 4;
562 else if (c < 0x4000000)
564 first = 0xf8;
565 len = 5;
567 else
569 first = 0xfc;
570 len = 6;
573 if (outbuf)
575 for (i = len - 1; i > 0; --i)
577 outbuf[i] = (c & 0x3f) | 0x80;
578 c >>= 6;
580 outbuf[0] = c | first;
583 return len;
587 * g_utf8_strchr:
588 * @p: a nul-terminated UTF-8 encoded string
589 * @len: the maximum length of @p
590 * @c: a ISO10646 character
592 * Finds the leftmost occurrence of the given ISO10646 character
593 * in a UTF-8 encoded string, while limiting the search to @len bytes.
594 * If @len is -1, allow unbounded search.
596 * Return value: %NULL if the string does not contain the character,
597 * otherwise, a pointer to the start of the leftmost occurrence of
598 * the character in the string.
600 gchar *
601 g_utf8_strchr (const char *p,
602 gssize len,
603 gunichar c)
605 gchar ch[10];
607 gint charlen = g_unichar_to_utf8 (c, ch);
608 ch[charlen] = '\0';
610 return g_strstr_len (p, len, ch);
615 * g_utf8_strrchr:
616 * @p: a nul-terminated UTF-8 encoded string
617 * @len: the maximum length of @p
618 * @c: a ISO10646 character
620 * Find the rightmost occurrence of the given ISO10646 character
621 * in a UTF-8 encoded string, while limiting the search to @len bytes.
622 * If @len is -1, allow unbounded search.
624 * Return value: %NULL if the string does not contain the character,
625 * otherwise, a pointer to the start of the rightmost occurrence of the
626 * character in the string.
628 gchar *
629 g_utf8_strrchr (const char *p,
630 gssize len,
631 gunichar c)
633 gchar ch[10];
635 gint charlen = g_unichar_to_utf8 (c, ch);
636 ch[charlen] = '\0';
638 return g_strrstr_len (p, len, ch);
642 /* Like g_utf8_get_char, but take a maximum length
643 * and return (gunichar)-2 on incomplete trailing character
645 static inline gunichar
646 g_utf8_get_char_extended (const gchar *p,
647 gssize max_len)
649 guint i, len;
650 gunichar wc = (guchar) *p;
652 if (wc < 0x80)
654 return wc;
656 else if (wc < 0xc0)
658 return (gunichar)-1;
660 else if (wc < 0xe0)
662 len = 2;
663 wc &= 0x1f;
665 else if (wc < 0xf0)
667 len = 3;
668 wc &= 0x0f;
670 else if (wc < 0xf8)
672 len = 4;
673 wc &= 0x07;
675 else if (wc < 0xfc)
677 len = 5;
678 wc &= 0x03;
680 else if (wc < 0xfe)
682 len = 6;
683 wc &= 0x01;
685 else
687 return (gunichar)-1;
690 if (max_len >= 0 && len > max_len)
692 for (i = 1; i < max_len; i++)
694 if ((((guchar *)p)[i] & 0xc0) != 0x80)
695 return (gunichar)-1;
697 return (gunichar)-2;
700 for (i = 1; i < len; ++i)
702 gunichar ch = ((guchar *)p)[i];
704 if ((ch & 0xc0) != 0x80)
706 if (ch)
707 return (gunichar)-1;
708 else
709 return (gunichar)-2;
712 wc <<= 6;
713 wc |= (ch & 0x3f);
716 if (UTF8_LENGTH(wc) != len)
717 return (gunichar)-1;
719 return wc;
723 * g_utf8_get_char_validated:
724 * @p: a pointer to Unicode character encoded as UTF-8
725 * @max_len: the maximum number of bytes to read, or -1, for no maximum.
727 * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
728 * This function checks for incomplete characters, for invalid characters
729 * such as characters that are out of the range of Unicode, and for
730 * overlong encodings of valid characters.
732 * Return value: the resulting character. If @p points to a partial
733 * sequence at the end of a string that could begin a valid
734 * character, returns (gunichar)-2; otherwise, if @p does not point
735 * to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.
737 gunichar
738 g_utf8_get_char_validated (const gchar *p,
739 gssize max_len)
741 gunichar result = g_utf8_get_char_extended (p, max_len);
743 if (result & 0x80000000)
744 return result;
745 else if (!UNICODE_VALID (result))
746 return (gunichar)-1;
747 else
748 return result;
752 * g_utf8_to_ucs4_fast:
753 * @str: a UTF-8 encoded string
754 * @len: the maximum length of @str to use. If @len < 0, then
755 * the string is nul-terminated.
756 * @items_written: location to store the number of characters in the
757 * result, or %NULL.
759 * Convert a string from UTF-8 to a 32-bit fixed width
760 * representation as UCS-4, assuming valid UTF-8 input.
761 * This function is roughly twice as fast as g_utf8_to_ucs4()
762 * but does no error checking on the input.
764 * Return value: a pointer to a newly allocated UCS-4 string.
765 * This value must be freed with g_free().
767 gunichar *
768 g_utf8_to_ucs4_fast (const gchar *str,
769 glong len,
770 glong *items_written)
772 gint j, charlen;
773 gunichar *result;
774 gint n_chars, i;
775 const gchar *p;
777 g_return_val_if_fail (str != NULL, NULL);
779 p = str;
780 n_chars = 0;
781 if (len < 0)
783 while (*p)
785 p = g_utf8_next_char (p);
786 ++n_chars;
789 else
791 while (p < str + len && *p)
793 p = g_utf8_next_char (p);
794 ++n_chars;
798 result = g_new (gunichar, n_chars + 1);
800 p = str;
801 for (i=0; i < n_chars; i++)
803 gunichar wc = ((unsigned char *)p)[0];
805 if (wc < 0x80)
807 result[i] = wc;
808 p++;
810 else
812 if (wc < 0xe0)
814 charlen = 2;
815 wc &= 0x1f;
817 else if (wc < 0xf0)
819 charlen = 3;
820 wc &= 0x0f;
822 else if (wc < 0xf8)
824 charlen = 4;
825 wc &= 0x07;
827 else if (wc < 0xfc)
829 charlen = 5;
830 wc &= 0x03;
832 else
834 charlen = 6;
835 wc &= 0x01;
838 for (j = 1; j < charlen; j++)
840 wc <<= 6;
841 wc |= ((unsigned char *)p)[j] & 0x3f;
844 result[i] = wc;
845 p += charlen;
848 result[i] = 0;
850 if (items_written)
851 *items_written = i;
853 return result;
857 * g_utf8_to_ucs4:
858 * @str: a UTF-8 encoded string
859 * @len: the maximum length of @str to use. If @len < 0, then
860 * the string is nul-terminated.
861 * @items_read: location to store number of bytes read, or %NULL.
862 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
863 * returned in case @str contains a trailing partial
864 * character. If an error occurs then the index of the
865 * invalid input is stored here.
866 * @items_written: location to store number of characters written or %NULL.
867 * The value here stored does not include the trailing 0
868 * character.
869 * @error: location to store the error occuring, or %NULL to ignore
870 * errors. Any of the errors in #GConvertError other than
871 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
873 * Convert a string from UTF-8 to a 32-bit fixed width
874 * representation as UCS-4. A trailing 0 will be added to the
875 * string after the converted text.
877 * Return value: a pointer to a newly allocated UCS-4 string.
878 * This value must be freed with g_free(). If an
879 * error occurs, %NULL will be returned and
880 * @error set.
882 gunichar *
883 g_utf8_to_ucs4 (const gchar *str,
884 glong len,
885 glong *items_read,
886 glong *items_written,
887 GError **error)
889 gunichar *result = NULL;
890 gint n_chars, i;
891 const gchar *in;
893 in = str;
894 n_chars = 0;
895 while ((len < 0 || str + len - in > 0) && *in)
897 gunichar wc = g_utf8_get_char_extended (in, str + len - in);
898 if (wc & 0x80000000)
900 if (wc == (gunichar)-2)
902 if (items_read)
903 break;
904 else
905 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
906 _("Partial character sequence at end of input"));
908 else
909 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
910 _("Invalid byte sequence in conversion input"));
912 goto err_out;
915 n_chars++;
917 in = g_utf8_next_char (in);
920 result = g_new (gunichar, n_chars + 1);
922 in = str;
923 for (i=0; i < n_chars; i++)
925 result[i] = g_utf8_get_char (in);
926 in = g_utf8_next_char (in);
928 result[i] = 0;
930 if (items_written)
931 *items_written = n_chars;
933 err_out:
934 if (items_read)
935 *items_read = in - str;
937 return result;
941 * g_ucs4_to_utf8:
942 * @str: a UCS-4 encoded string
943 * @len: the maximum length of @str to use. If @len < 0, then
944 * the string is terminated with a 0 character.
945 * @items_read: location to store number of characters read read, or %NULL.
946 * @items_written: location to store number of bytes written or %NULL.
947 * The value here stored does not include the trailing 0
948 * byte.
949 * @error: location to store the error occuring, or %NULL to ignore
950 * errors. Any of the errors in #GConvertError other than
951 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
953 * Convert a string from a 32-bit fixed width representation as UCS-4.
954 * to UTF-8. The result will be terminated with a 0 byte.
956 * Return value: a pointer to a newly allocated UTF-8 string.
957 * This value must be freed with g_free(). If an
958 * error occurs, %NULL will be returned and
959 * @error set.
961 gchar *
962 g_ucs4_to_utf8 (const gunichar *str,
963 glong len,
964 glong *items_read,
965 glong *items_written,
966 GError **error)
968 gint result_length;
969 gchar *result = NULL;
970 gchar *p;
971 gint i;
973 result_length = 0;
974 for (i = 0; len < 0 || i < len ; i++)
976 if (!str[i])
977 break;
979 if (str[i] >= 0x80000000)
981 if (items_read)
982 *items_read = i;
984 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
985 _("Character out of range for UTF-8"));
986 goto err_out;
989 result_length += UTF8_LENGTH (str[i]);
992 result = g_malloc (result_length + 1);
993 p = result;
995 i = 0;
996 while (p < result + result_length)
997 p += g_unichar_to_utf8 (str[i++], p);
999 *p = '\0';
1001 if (items_written)
1002 *items_written = p - result;
1004 err_out:
1005 if (items_read)
1006 *items_read = i;
1008 return result;
1011 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1014 * g_utf16_to_utf8:
1015 * @str: a UTF-16 encoded string
1016 * @len: the maximum length of @str to use. If @len < 0, then
1017 * the string is terminated with a 0 character.
1018 * @items_read: location to store number of words read, or %NULL.
1019 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1020 * returned in case @str contains a trailing partial
1021 * character. If an error occurs then the index of the
1022 * invalid input is stored here.
1023 * @items_written: location to store number of bytes written, or %NULL.
1024 * The value stored here does not include the trailing
1025 * 0 byte.
1026 * @error: location to store the error occuring, or %NULL to ignore
1027 * errors. Any of the errors in #GConvertError other than
1028 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1030 * Convert a string from UTF-16 to UTF-8. The result will be
1031 * terminated with a 0 byte.
1033 * Return value: a pointer to a newly allocated UTF-8 string.
1034 * This value must be freed with g_free(). If an
1035 * error occurs, %NULL will be returned and
1036 * @error set.
1038 gchar *
1039 g_utf16_to_utf8 (const gunichar2 *str,
1040 glong len,
1041 glong *items_read,
1042 glong *items_written,
1043 GError **error)
1045 /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1046 * are marked.
1048 const gunichar2 *in;
1049 gchar *out;
1050 gchar *result = NULL;
1051 gint n_bytes;
1052 gunichar high_surrogate;
1054 g_return_val_if_fail (str != 0, NULL);
1056 n_bytes = 0;
1057 in = str;
1058 high_surrogate = 0;
1059 while ((len < 0 || in - str < len) && *in)
1061 gunichar2 c = *in;
1062 gunichar wc;
1064 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1066 if (high_surrogate)
1068 wc = SURROGATE_VALUE (high_surrogate, c);
1069 high_surrogate = 0;
1071 else
1073 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1074 _("Invalid sequence in conversion input"));
1075 goto err_out;
1078 else
1080 if (high_surrogate)
1082 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1083 _("Invalid sequence in conversion input"));
1084 goto err_out;
1087 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1089 high_surrogate = c;
1090 goto next1;
1092 else
1093 wc = c;
1096 /********** DIFFERENT for UTF8/UCS4 **********/
1097 n_bytes += UTF8_LENGTH (wc);
1099 next1:
1100 in++;
1103 if (high_surrogate && !items_read)
1105 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1106 _("Partial character sequence at end of input"));
1107 goto err_out;
1110 /* At this point, everything is valid, and we just need to convert
1112 /********** DIFFERENT for UTF8/UCS4 **********/
1113 result = g_malloc (n_bytes + 1);
1115 high_surrogate = 0;
1116 out = result;
1117 in = str;
1118 while (out < result + n_bytes)
1120 gunichar2 c = *in;
1121 gunichar wc;
1123 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1125 wc = SURROGATE_VALUE (high_surrogate, c);
1126 high_surrogate = 0;
1128 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1130 high_surrogate = c;
1131 goto next2;
1133 else
1134 wc = c;
1136 /********** DIFFERENT for UTF8/UCS4 **********/
1137 out += g_unichar_to_utf8 (wc, out);
1139 next2:
1140 in++;
1143 /********** DIFFERENT for UTF8/UCS4 **********/
1144 *out = '\0';
1146 if (items_written)
1147 /********** DIFFERENT for UTF8/UCS4 **********/
1148 *items_written = out - result;
1150 err_out:
1151 if (items_read)
1152 *items_read = in - str;
1154 return result;
1158 * g_utf16_to_ucs4:
1159 * @str: a UTF-16 encoded string
1160 * @len: the maximum length of @str to use. If @len < 0, then
1161 * the string is terminated with a 0 character.
1162 * @items_read: location to store number of words read, or %NULL.
1163 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1164 * returned in case @str contains a trailing partial
1165 * character. If an error occurs then the index of the
1166 * invalid input is stored here.
1167 * @items_written: location to store number of characters written, or %NULL.
1168 * The value stored here does not include the trailing
1169 * 0 character.
1170 * @error: location to store the error occuring, or %NULL to ignore
1171 * errors. Any of the errors in #GConvertError other than
1172 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1174 * Convert a string from UTF-16 to UCS-4. The result will be
1175 * terminated with a 0 character.
1177 * Return value: a pointer to a newly allocated UCS-4 string.
1178 * This value must be freed with g_free(). If an
1179 * error occurs, %NULL will be returned and
1180 * @error set.
1182 gunichar *
1183 g_utf16_to_ucs4 (const gunichar2 *str,
1184 glong len,
1185 glong *items_read,
1186 glong *items_written,
1187 GError **error)
1189 const gunichar2 *in;
1190 gchar *out;
1191 gchar *result = NULL;
1192 gint n_bytes;
1193 gunichar high_surrogate;
1195 g_return_val_if_fail (str != 0, NULL);
1197 n_bytes = 0;
1198 in = str;
1199 high_surrogate = 0;
1200 while ((len < 0 || in - str < len) && *in)
1202 gunichar2 c = *in;
1203 gunichar wc;
1205 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1207 if (high_surrogate)
1209 wc = SURROGATE_VALUE (high_surrogate, c);
1210 high_surrogate = 0;
1212 else
1214 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1215 _("Invalid sequence in conversion input"));
1216 goto err_out;
1219 else
1221 if (high_surrogate)
1223 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1224 _("Invalid sequence in conversion input"));
1225 goto err_out;
1228 if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1230 high_surrogate = c;
1231 goto next1;
1233 else
1234 wc = c;
1237 /********** DIFFERENT for UTF8/UCS4 **********/
1238 n_bytes += sizeof (gunichar);
1240 next1:
1241 in++;
1244 if (high_surrogate && !items_read)
1246 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1247 _("Partial character sequence at end of input"));
1248 goto err_out;
1251 /* At this point, everything is valid, and we just need to convert
1253 /********** DIFFERENT for UTF8/UCS4 **********/
1254 result = g_malloc (n_bytes + 4);
1256 high_surrogate = 0;
1257 out = result;
1258 in = str;
1259 while (out < result + n_bytes)
1261 gunichar2 c = *in;
1262 gunichar wc;
1264 if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1266 wc = SURROGATE_VALUE (high_surrogate, c);
1267 high_surrogate = 0;
1269 else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1271 high_surrogate = c;
1272 goto next2;
1274 else
1275 wc = c;
1277 /********** DIFFERENT for UTF8/UCS4 **********/
1278 *(gunichar *)out = wc;
1279 out += sizeof (gunichar);
1281 next2:
1282 in++;
1285 /********** DIFFERENT for UTF8/UCS4 **********/
1286 *(gunichar *)out = 0;
1288 if (items_written)
1289 /********** DIFFERENT for UTF8/UCS4 **********/
1290 *items_written = (out - result) / sizeof (gunichar);
1292 err_out:
1293 if (items_read)
1294 *items_read = in - str;
1296 return (gunichar *)result;
1300 * g_utf8_to_utf16:
1301 * @str: a UTF-8 encoded string
1302 * @len: the maximum length of @str to use. If @len < 0, then
1303 * the string is nul-terminated.
1304 * @items_read: location to store number of bytes read, or %NULL.
1305 * If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1306 * returned in case @str contains a trailing partial
1307 * character. If an error occurs then the index of the
1308 * invalid input is stored here.
1309 * @items_written: location to store number of words written, or %NULL.
1310 * The value stored here does not include the trailing
1311 * 0 word.
1312 * @error: location to store the error occuring, or %NULL to ignore
1313 * errors. Any of the errors in #GConvertError other than
1314 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1316 * Convert a string from UTF-8 to UTF-16. A 0 word will be
1317 * added to the result after the converted text.
1319 * Return value: a pointer to a newly allocated UTF-16 string.
1320 * This value must be freed with g_free(). If an
1321 * error occurs, %NULL will be returned and
1322 * @error set.
1324 gunichar2 *
1325 g_utf8_to_utf16 (const gchar *str,
1326 glong len,
1327 glong *items_read,
1328 glong *items_written,
1329 GError **error)
1331 gunichar2 *result = NULL;
1332 gint n16;
1333 const gchar *in;
1334 gint i;
1336 g_return_val_if_fail (str != NULL, NULL);
1338 in = str;
1339 n16 = 0;
1340 while ((len < 0 || str + len - in > 0) && *in)
1342 gunichar wc = g_utf8_get_char_extended (in, str + len - in);
1343 if (wc & 0x80000000)
1345 if (wc == (gunichar)-2)
1347 if (items_read)
1348 break;
1349 else
1350 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1351 _("Partial character sequence at end of input"));
1353 else
1354 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1355 _("Invalid byte sequence in conversion input"));
1357 goto err_out;
1360 if (wc < 0xd800)
1361 n16 += 1;
1362 else if (wc < 0xe000)
1364 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1365 _("Invalid sequence in conversion input"));
1367 goto err_out;
1369 else if (wc < 0x10000)
1370 n16 += 1;
1371 else if (wc < 0x110000)
1372 n16 += 2;
1373 else
1375 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1376 _("Character out of range for UTF-16"));
1378 goto err_out;
1381 in = g_utf8_next_char (in);
1384 result = g_new (gunichar2, n16 + 1);
1386 in = str;
1387 for (i = 0; i < n16;)
1389 gunichar wc = g_utf8_get_char (in);
1391 if (wc < 0x10000)
1393 result[i++] = wc;
1395 else
1397 result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1398 result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1401 in = g_utf8_next_char (in);
1404 result[i] = 0;
1406 if (items_written)
1407 *items_written = n16;
1409 err_out:
1410 if (items_read)
1411 *items_read = in - str;
1413 return result;
1417 * g_ucs4_to_utf16:
1418 * @str: a UCS-4 encoded string
1419 * @len: the maximum length of @str to use. If @len < 0, then
1420 * the string is terminated with a 0 character.
1421 * @items_read: location to store number of bytes read, or %NULL.
1422 * If an error occurs then the index of the invalid input
1423 * is stored here.
1424 * @items_written: location to store number of words written, or %NULL.
1425 * The value stored here does not include the trailing
1426 * 0 word.
1427 * @error: location to store the error occuring, or %NULL to ignore
1428 * errors. Any of the errors in #GConvertError other than
1429 * %G_CONVERT_ERROR_NO_CONVERSION may occur.
1431 * Convert a string from UCS-4 to UTF-16. A 0 word will be
1432 * added to the result after the converted text.
1434 * Return value: a pointer to a newly allocated UTF-16 string.
1435 * This value must be freed with g_free(). If an
1436 * error occurs, %NULL will be returned and
1437 * @error set.
1439 gunichar2 *
1440 g_ucs4_to_utf16 (const gunichar *str,
1441 glong len,
1442 glong *items_read,
1443 glong *items_written,
1444 GError **error)
1446 gunichar2 *result = NULL;
1447 gint n16;
1448 gint i, j;
1450 n16 = 0;
1451 i = 0;
1452 while ((len < 0 || i < len) && str[i])
1454 gunichar wc = str[i];
1456 if (wc < 0xd800)
1457 n16 += 1;
1458 else if (wc < 0xe000)
1460 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1461 _("Invalid sequence in conversion input"));
1463 goto err_out;
1465 else if (wc < 0x10000)
1466 n16 += 1;
1467 else if (wc < 0x110000)
1468 n16 += 2;
1469 else
1471 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1472 _("Character out of range for UTF-16"));
1474 goto err_out;
1477 i++;
1480 result = g_new (gunichar2, n16 + 1);
1482 for (i = 0, j = 0; j < n16; i++)
1484 gunichar wc = str[i];
1486 if (wc < 0x10000)
1488 result[j++] = wc;
1490 else
1492 result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1493 result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1496 result[j] = 0;
1498 if (items_written)
1499 *items_written = n16;
1501 err_out:
1502 if (items_read)
1503 *items_read = i;
1505 return result;
1509 * g_utf8_validate:
1510 * @str: a pointer to character data
1511 * @max_len: max bytes to validate, or -1 to go until nul
1512 * @end: return location for end of valid data
1514 * Validates UTF-8 encoded text. @str is the text to validate;
1515 * if @str is nul-terminated, then @max_len can be -1, otherwise
1516 * @max_len should be the number of bytes to validate.
1517 * If @end is non-%NULL, then the end of the valid range
1518 * will be stored there (i.e. the address of the first invalid byte
1519 * if some bytes were invalid, or the end of the text being validated
1520 * otherwise).
1522 * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1523 * routines <emphasis>require</emphasis> valid UTF-8 as input;
1524 * so data read from a file or the network should be checked
1525 * with g_utf8_validate() before doing anything else with it.
1527 * Return value: %TRUE if the text was valid UTF-8
1529 gboolean
1530 g_utf8_validate (const gchar *str,
1531 gssize max_len,
1532 const gchar **end)
1535 const gchar *p;
1537 g_return_val_if_fail (str != NULL, FALSE);
1539 if (end)
1540 *end = str;
1542 p = str;
1544 while ((max_len < 0 || (p - str) < max_len) && *p)
1546 int i, mask = 0, len;
1547 gunichar result;
1548 unsigned char c = (unsigned char) *p;
1550 UTF8_COMPUTE (c, mask, len);
1552 if (len == -1)
1553 break;
1555 /* check that the expected number of bytes exists in str */
1556 if (max_len >= 0 &&
1557 ((max_len - (p - str)) < len))
1558 break;
1560 UTF8_GET (result, p, i, mask, len);
1562 if (UTF8_LENGTH (result) != len) /* Check for overlong UTF-8 */
1563 break;
1565 if (result == (gunichar)-1)
1566 break;
1568 if (!UNICODE_VALID (result))
1569 break;
1571 p += len;
1574 if (end)
1575 *end = p;
1577 /* See that we covered the entire length if a length was
1578 * passed in, or that we ended on a nul if not
1580 if (max_len >= 0 &&
1581 p != (str + max_len))
1582 return FALSE;
1583 else if (max_len < 0 &&
1584 *p != '\0')
1585 return FALSE;
1586 else
1587 return TRUE;
1591 * g_unichar_validate:
1592 * @ch: a Unicode character
1594 * Checks whether @ch is a valid Unicode character. Some possible
1595 * integer values of @ch will not be valid. 0 is considered a valid
1596 * character, though it's normally a string terminator.
1598 * Return value: %TRUE if @ch is a valid Unicode character
1600 gboolean
1601 g_unichar_validate (gunichar ch)
1603 return UNICODE_VALID (ch);
1607 * g_utf8_strreverse:
1608 * @str: a UTF-8 encoded string
1609 * @len: the maximum length of @str to use. If @len < 0, then
1610 * the string is nul-terminated.
1612 * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text.
1613 * (Use g_utf8_validate() on all text before trying to use UTF-8
1614 * utility functions with it.)
1616 * Note that unlike g_strreverse(), this function returns
1617 * newly-allocated memory, which should be freed with g_free() when
1618 * no longer needed.
1620 * Returns: a newly-allocated string which is the reverse of @str.
1622 * Since: 2.2
1624 gchar *
1625 g_utf8_strreverse (const gchar *str,
1626 gssize len)
1628 gchar *result;
1629 const gchar *p;
1630 gchar *m, *r, skip;
1632 if (len < 0)
1633 len = strlen (str);
1635 result = g_new (gchar, len + 1);
1636 r = result + len;
1637 p = str;
1638 while (*p)
1640 skip = g_utf8_skip[*(guchar*)p];
1641 r -= skip;
1642 for (m = r; skip; skip--)
1643 *m++ = *p++;
1645 result[len] = 0;
1647 return result;