7977f3a765ff1643cd3f81e9ab1eca5e2610744c
[platform/upstream/glib.git] / glib / gutf8.c
1 /* gutf8.c - Operations on UTF-8 strings.
2  *
3  * Copyright (C) 1999 Tom Tromey
4  * Copyright (C) 2000 Red Hat, Inc.
5  *
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.
10  *
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.
15  *
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.
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #ifdef HAVE_CODESET
26 #include <langinfo.h>
27 #endif
28 #include <string.h>
29
30 #ifdef G_PLATFORM_WIN32
31 #include <stdio.h>
32 #define STRICT
33 #include <windows.h>
34 #undef STRICT
35 #endif
36
37 #include "libcharset/libcharset.h"
38
39 #include "gconvert.h"
40 #include "ghash.h"
41 #include "gstrfuncs.h"
42 #include "gtestutils.h"
43 #include "gtypes.h"
44 #include "gthread.h"
45 #include "glibintl.h"
46
47 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
48   if (Char < 128)                                                             \
49     {                                                                         \
50       Len = 1;                                                                \
51       Mask = 0x7f;                                                            \
52     }                                                                         \
53   else if ((Char & 0xe0) == 0xc0)                                             \
54     {                                                                         \
55       Len = 2;                                                                \
56       Mask = 0x1f;                                                            \
57     }                                                                         \
58   else if ((Char & 0xf0) == 0xe0)                                             \
59     {                                                                         \
60       Len = 3;                                                                \
61       Mask = 0x0f;                                                            \
62     }                                                                         \
63   else if ((Char & 0xf8) == 0xf0)                                             \
64     {                                                                         \
65       Len = 4;                                                                \
66       Mask = 0x07;                                                            \
67     }                                                                         \
68   else if ((Char & 0xfc) == 0xf8)                                             \
69     {                                                                         \
70       Len = 5;                                                                \
71       Mask = 0x03;                                                            \
72     }                                                                         \
73   else if ((Char & 0xfe) == 0xfc)                                             \
74     {                                                                         \
75       Len = 6;                                                                \
76       Mask = 0x01;                                                            \
77     }                                                                         \
78   else                                                                        \
79     Len = -1;
80
81 #define UTF8_LENGTH(Char)              \
82   ((Char) < 0x80 ? 1 :                 \
83    ((Char) < 0x800 ? 2 :               \
84     ((Char) < 0x10000 ? 3 :            \
85      ((Char) < 0x200000 ? 4 :          \
86       ((Char) < 0x4000000 ? 5 : 6)))))
87    
88
89 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
90   (Result) = (Chars)[0] & (Mask);                                             \
91   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
92     {                                                                         \
93       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
94         {                                                                     \
95           (Result) = -1;                                                      \
96           break;                                                              \
97         }                                                                     \
98       (Result) <<= 6;                                                         \
99       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
100     }
101     
102 /*
103  * Check whether a Unicode (5.2) char is in a valid range.
104  *
105  * The first check comes from the Unicode guarantee to never encode
106  * a point above 0x0010ffff, since UTF-16 couldn't represent it.
107  * 
108  * The second check covers surrogate pairs (category Cs).
109  * 
110  * The last two checks cover "Noncharacter": defined as:
111  *   "A code point that is permanently reserved for
112  *    internal use, and that should never be interchanged. In
113  *    Unicode 3.1, these consist of the values U+nFFFE and U+nFFFF
114  *    (where n is from 0 to 10_16) and the values U+FDD0..U+FDEF."
115  *
116  * @param Char the character
117  */
118 #define UNICODE_VALID(Char)                   \
119     ((Char) < 0x110000 &&                     \
120      (((Char) & 0xFFFFF800) != 0xD800) &&     \
121      ((Char) < 0xFDD0 || (Char) > 0xFDEF) &&  \
122      ((Char) & 0xFFFE) != 0xFFFE)
123    
124      
125 static const gchar utf8_skip_data[256] = {
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   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,
131   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,
132   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,
133   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 };
135
136 const gchar * const g_utf8_skip = utf8_skip_data;
137
138 /**
139  * g_utf8_find_prev_char:
140  * @str: pointer to the beginning of a UTF-8 encoded string
141  * @p: pointer to some position within @str
142  * 
143  * Given a position @p with a UTF-8 encoded string @str, find the start
144  * of the previous UTF-8 character starting before @p. Returns %NULL if no
145  * UTF-8 characters are present in @str before @p.
146  *
147  * @p does not have to be at the beginning of a UTF-8 character. No check
148  * is made to see if the character found is actually valid other than
149  * it starts with an appropriate byte.
150  *
151  * Return value: a pointer to the found character or %NULL.
152  **/
153 gchar *
154 g_utf8_find_prev_char (const char *str,
155                        const char *p)
156 {
157   for (--p; p >= str; --p)
158     {
159       if ((*p & 0xc0) != 0x80)
160         return (gchar *)p;
161     }
162   return NULL;
163 }
164
165 /**
166  * g_utf8_find_next_char:
167  * @p: a pointer to a position within a UTF-8 encoded string
168  * @end: a pointer to the byte following the end of the string,
169  * or %NULL to indicate that the string is nul-terminated.
170  *
171  * Finds the start of the next UTF-8 character in the string after @p.
172  *
173  * @p does not have to be at the beginning of a UTF-8 character. No check
174  * is made to see if the character found is actually valid other than
175  * it starts with an appropriate byte.
176  * 
177  * Return value: a pointer to the found character or %NULL
178  **/
179 gchar *
180 g_utf8_find_next_char (const gchar *p,
181                        const gchar *end)
182 {
183   if (*p)
184     {
185       if (end)
186         for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
187           ;
188       else
189         for (++p; (*p & 0xc0) == 0x80; ++p)
190           ;
191     }
192   return (p == end) ? NULL : (gchar *)p;
193 }
194
195 /**
196  * g_utf8_prev_char:
197  * @p: a pointer to a position within a UTF-8 encoded string
198  *
199  * Finds the previous UTF-8 character in the string before @p.
200  *
201  * @p does not have to be at the beginning of a UTF-8 character. No check
202  * is made to see if the character found is actually valid other than
203  * it starts with an appropriate byte. If @p might be the first
204  * character of the string, you must use g_utf8_find_prev_char() instead.
205  * 
206  * Return value: a pointer to the found character.
207  **/
208 gchar *
209 g_utf8_prev_char (const gchar *p)
210 {
211   while (TRUE)
212     {
213       p--;
214       if ((*p & 0xc0) != 0x80)
215         return (gchar *)p;
216     }
217 }
218
219 /**
220  * g_utf8_strlen:
221  * @p: pointer to the start of a UTF-8 encoded string
222  * @max: the maximum number of bytes to examine. If @max
223  *       is less than 0, then the string is assumed to be
224  *       nul-terminated. If @max is 0, @p will not be examined and
225  *       may be %NULL.
226  *
227  * Computes the length of the string in characters, not including
228  * the terminating nul character.
229  *
230  * Return value: the length of the string in characters
231  **/
232 glong
233 g_utf8_strlen (const gchar *p,
234                gssize       max)
235 {
236   glong len = 0;
237   const gchar *start = p;
238   g_return_val_if_fail (p != NULL || max == 0, 0);
239
240   if (max < 0)
241     {
242       while (*p)
243         {
244           p = g_utf8_next_char (p);
245           ++len;
246         }
247     }
248   else
249     {
250       if (max == 0 || !*p)
251         return 0;
252
253       p = g_utf8_next_char (p);
254
255       while (p - start < max && *p)
256         {
257           ++len;
258           p = g_utf8_next_char (p);
259         }
260
261       /* only do the last len increment if we got a complete
262        * char (don't count partial chars)
263        */
264       if (p - start <= max)
265         ++len;
266     }
267
268   return len;
269 }
270
271 /**
272  * g_utf8_get_char:
273  * @p: a pointer to Unicode character encoded as UTF-8
274  * 
275  * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
276  * If @p does not point to a valid UTF-8 encoded character, results are
277  * undefined. If you are not sure that the bytes are complete
278  * valid Unicode characters, you should use g_utf8_get_char_validated()
279  * instead.
280  * 
281  * Return value: the resulting character
282  **/
283 gunichar
284 g_utf8_get_char (const gchar *p)
285 {
286   int i, mask = 0, len;
287   gunichar result;
288   unsigned char c = (unsigned char) *p;
289
290   UTF8_COMPUTE (c, mask, len);
291   if (len == -1)
292     return (gunichar)-1;
293   UTF8_GET (result, p, i, mask, len);
294
295   return result;
296 }
297
298 /**
299  * g_utf8_offset_to_pointer:
300  * @str: a UTF-8 encoded string
301  * @offset: a character offset within @str
302  *
303  * Converts from an integer character offset to a pointer to a position
304  * within the string.
305  *
306  * Since 2.10, this function allows to pass a negative @offset to
307  * step backwards. It is usually worth stepping backwards from the end
308  * instead of forwards if @offset is in the last fourth of the string,
309  * since moving forward is about 3 times faster than moving backward.
310  *
311  * <note><para>
312  * This function doesn't abort when reaching the end of @str. Therefore
313  * you should be sure that @offset is within string boundaries before
314  * calling that function. Call g_utf8_strlen() when unsure.
315  *
316  * This limitation exists as this function is called frequently during
317  * text rendering and therefore has to be as fast as possible.
318  * </para></note>
319  *
320  * Return value: the resulting pointer
321  **/
322 gchar *
323 g_utf8_offset_to_pointer  (const gchar *str,
324                            glong        offset)
325 {
326   const gchar *s = str;
327
328   if (offset > 0) 
329     while (offset--)
330       s = g_utf8_next_char (s);
331   else
332     {
333       const char *s1;
334
335       /* This nice technique for fast backwards stepping 
336        * through a UTF-8 string was dubbed "stutter stepping" 
337        * by its inventor, Larry Ewing.
338        */
339       while (offset)
340         {
341           s1 = s;
342           s += offset;
343           while ((*s & 0xc0) == 0x80)
344             s--;
345
346           offset += g_utf8_pointer_to_offset (s, s1);
347         }
348     }
349
350   return (gchar *)s;
351 }
352
353 /**
354  * g_utf8_pointer_to_offset:
355  * @str: a UTF-8 encoded string
356  * @pos: a pointer to a position within @str
357  * 
358  * Converts from a pointer to position within a string to a integer
359  * character offset.
360  *
361  * Since 2.10, this function allows @pos to be before @str, and returns
362  * a negative offset in this case.
363  * 
364  * Return value: the resulting character offset
365  **/
366 glong    
367 g_utf8_pointer_to_offset (const gchar *str,
368                           const gchar *pos)
369 {
370   const gchar *s = str;
371   glong offset = 0;    
372
373   if (pos < str) 
374     offset = - g_utf8_pointer_to_offset (pos, str);
375   else
376     while (s < pos)
377       {
378         s = g_utf8_next_char (s);
379         offset++;
380       }
381   
382   return offset;
383 }
384
385
386 /**
387  * g_utf8_strncpy:
388  * @dest: buffer to fill with characters from @src
389  * @src: UTF-8 encoded string
390  * @n: character count
391  * 
392  * Like the standard C strncpy() function, but 
393  * copies a given number of characters instead of a given number of 
394  * bytes. The @src string must be valid UTF-8 encoded text. 
395  * (Use g_utf8_validate() on all text before trying to use UTF-8 
396  * utility functions with it.)
397  * 
398  * Return value: @dest
399  **/
400 gchar *
401 g_utf8_strncpy (gchar       *dest,
402                 const gchar *src,
403                 gsize        n)
404 {
405   const gchar *s = src;
406   while (n && *s)
407     {
408       s = g_utf8_next_char(s);
409       n--;
410     }
411   strncpy(dest, src, s - src);
412   dest[s - src] = 0;
413   return dest;
414 }
415
416 G_LOCK_DEFINE_STATIC (aliases);
417
418 static GHashTable *
419 get_alias_hash (void)
420 {
421   static GHashTable *alias_hash = NULL;
422   const char *aliases;
423
424   G_LOCK (aliases);
425
426   if (!alias_hash)
427     {
428       alias_hash = g_hash_table_new (g_str_hash, g_str_equal);
429       
430       aliases = _g_locale_get_charset_aliases ();
431       while (*aliases != '\0')
432         {
433           const char *canonical;
434           const char *alias;
435           const char **alias_array;
436           int count = 0;
437           
438           alias = aliases;
439           aliases += strlen (aliases) + 1;
440           canonical = aliases;
441           aliases += strlen (aliases) + 1;
442           
443           alias_array = g_hash_table_lookup (alias_hash, canonical);
444           if (alias_array)
445             {
446               while (alias_array[count])
447                 count++;
448             }
449           
450           alias_array = g_renew (const char *, alias_array, count + 2);
451           alias_array[count] = alias;
452           alias_array[count + 1] = NULL;
453           
454           g_hash_table_insert (alias_hash, (char *)canonical, alias_array);
455         }
456     }
457
458   G_UNLOCK (aliases);
459
460   return alias_hash;
461 }
462
463 /* As an abuse of the alias table, the following routines gets
464  * the charsets that are aliases for the canonical name.
465  */
466 G_GNUC_INTERNAL const char ** 
467 _g_charset_get_aliases (const char *canonical_name)
468 {
469   GHashTable *alias_hash = get_alias_hash ();
470
471   return g_hash_table_lookup (alias_hash, canonical_name);
472 }
473
474 static gboolean
475 g_utf8_get_charset_internal (const char  *raw_data,
476                              const char **a)
477 {
478   const char *charset = getenv("CHARSET");
479
480   if (charset && *charset)
481     {
482       *a = charset;
483
484       if (charset && strstr (charset, "UTF-8"))
485         return TRUE;
486       else
487         return FALSE;
488     }
489
490   /* The libcharset code tries to be thread-safe without
491    * a lock, but has a memory leak and a missing memory
492    * barrier, so we lock for it
493    */
494   G_LOCK (aliases);
495   charset = _g_locale_charset_unalias (raw_data);
496   G_UNLOCK (aliases);
497   
498   if (charset && *charset)
499     {
500       *a = charset;
501       
502       if (charset && strstr (charset, "UTF-8"))
503         return TRUE;
504       else
505         return FALSE;
506     }
507
508   /* Assume this for compatibility at present.  */
509   *a = "US-ASCII";
510   
511   return FALSE;
512 }
513
514 typedef struct _GCharsetCache GCharsetCache;
515
516 struct _GCharsetCache {
517   gboolean is_utf8;
518   gchar *raw;
519   gchar *charset;
520 };
521
522 static void
523 charset_cache_free (gpointer data)
524 {
525   GCharsetCache *cache = data;
526   g_free (cache->raw);
527   g_free (cache->charset);
528   g_free (cache);
529 }
530
531 /**
532  * g_get_charset:
533  * @charset: return location for character set name
534  * 
535  * Obtains the character set for the <link linkend="setlocale">current 
536  * locale</link>; you might use this character set as an argument to 
537  * g_convert(), to convert from the current locale's encoding to some 
538  * other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8()
539  * are nice shortcuts, though.)
540  *
541  * On Windows the character set returned by this function is the
542  * so-called system default ANSI code-page. That is the character set
543  * used by the "narrow" versions of C library and Win32 functions that
544  * handle file names. It might be different from the character set
545  * used by the C library's current locale.
546  *
547  * The return value is %TRUE if the locale's encoding is UTF-8, in that
548  * case you can perhaps avoid calling g_convert().
549  *
550  * The string returned in @charset is not allocated, and should not be
551  * freed.
552  * 
553  * Return value: %TRUE if the returned charset is UTF-8
554  **/
555 gboolean
556 g_get_charset (const char **charset) 
557 {
558   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
559   GCharsetCache *cache = g_static_private_get (&cache_private);
560   const gchar *raw;
561
562   if (!cache)
563     {
564       cache = g_new0 (GCharsetCache, 1);
565       g_static_private_set (&cache_private, cache, charset_cache_free);
566     }
567
568   raw = _g_locale_charset_raw ();
569   
570   if (!(cache->raw && strcmp (cache->raw, raw) == 0))
571     {
572       const gchar *new_charset;
573             
574       g_free (cache->raw);
575       g_free (cache->charset);
576       cache->raw = g_strdup (raw);
577       cache->is_utf8 = g_utf8_get_charset_internal (raw, &new_charset);
578       cache->charset = g_strdup (new_charset);
579     }
580
581   if (charset)
582     *charset = cache->charset;
583   
584   return cache->is_utf8;
585 }
586
587 /* unicode_strchr */
588
589 /**
590  * g_unichar_to_utf8:
591  * @c: a Unicode character code
592  * @outbuf: output buffer, must have at least 6 bytes of space.
593  *       If %NULL, the length will be computed and returned
594  *       and nothing will be written to @outbuf.
595  * 
596  * Converts a single character to UTF-8.
597  * 
598  * Return value: number of bytes written
599  **/
600 int
601 g_unichar_to_utf8 (gunichar c,
602                    gchar   *outbuf)
603 {
604   /* If this gets modified, also update the copy in g_string_insert_unichar() */
605   guint len = 0;    
606   int first;
607   int i;
608
609   if (c < 0x80)
610     {
611       first = 0;
612       len = 1;
613     }
614   else if (c < 0x800)
615     {
616       first = 0xc0;
617       len = 2;
618     }
619   else if (c < 0x10000)
620     {
621       first = 0xe0;
622       len = 3;
623     }
624    else if (c < 0x200000)
625     {
626       first = 0xf0;
627       len = 4;
628     }
629   else if (c < 0x4000000)
630     {
631       first = 0xf8;
632       len = 5;
633     }
634   else
635     {
636       first = 0xfc;
637       len = 6;
638     }
639
640   if (outbuf)
641     {
642       for (i = len - 1; i > 0; --i)
643         {
644           outbuf[i] = (c & 0x3f) | 0x80;
645           c >>= 6;
646         }
647       outbuf[0] = c | first;
648     }
649
650   return len;
651 }
652
653 /**
654  * g_utf8_strchr:
655  * @p: a nul-terminated UTF-8 encoded string
656  * @len: the maximum length of @p
657  * @c: a Unicode character
658  * 
659  * Finds the leftmost occurrence of the given Unicode character
660  * in a UTF-8 encoded string, while limiting the search to @len bytes.
661  * If @len is -1, allow unbounded search.
662  * 
663  * Return value: %NULL if the string does not contain the character, 
664  *   otherwise, a pointer to the start of the leftmost occurrence of 
665  *   the character in the string.
666  **/
667 gchar *
668 g_utf8_strchr (const char *p,
669                gssize      len,
670                gunichar    c)
671 {
672   gchar ch[10];
673
674   gint charlen = g_unichar_to_utf8 (c, ch);
675   ch[charlen] = '\0';
676   
677   return g_strstr_len (p, len, ch);
678 }
679
680
681 /**
682  * g_utf8_strrchr:
683  * @p: a nul-terminated UTF-8 encoded string
684  * @len: the maximum length of @p
685  * @c: a Unicode character
686  * 
687  * Find the rightmost occurrence of the given Unicode character
688  * in a UTF-8 encoded string, while limiting the search to @len bytes.
689  * If @len is -1, allow unbounded search.
690  * 
691  * Return value: %NULL if the string does not contain the character, 
692  *   otherwise, a pointer to the start of the rightmost occurrence of the 
693  *   character in the string.
694  **/
695 gchar *
696 g_utf8_strrchr (const char *p,
697                 gssize      len,
698                 gunichar    c)
699 {
700   gchar ch[10];
701
702   gint charlen = g_unichar_to_utf8 (c, ch);
703   ch[charlen] = '\0';
704   
705   return g_strrstr_len (p, len, ch);
706 }
707
708
709 /* Like g_utf8_get_char, but take a maximum length
710  * and return (gunichar)-2 on incomplete trailing character;
711  * also check for malformed or overlong sequences
712  * and return (gunichar)-1 in this case.
713  */
714 static inline gunichar
715 g_utf8_get_char_extended (const  gchar *p,
716                           gssize max_len)
717 {
718   guint i, len;
719   gunichar min_code;
720   gunichar wc = (guchar) *p;
721
722   if (wc < 0x80)
723     {
724       return wc;
725     }
726   else if (G_UNLIKELY (wc < 0xc0))
727     {
728       return (gunichar)-1;
729     }
730   else if (wc < 0xe0)
731     {
732       len = 2;
733       wc &= 0x1f;
734       min_code = 1 << 7;
735     }
736   else if (wc < 0xf0)
737     {
738       len = 3;
739       wc &= 0x0f;
740       min_code = 1 << 11;
741     }
742   else if (wc < 0xf8)
743     {
744       len = 4;
745       wc &= 0x07;
746       min_code = 1 << 16;
747     }
748   else if (wc < 0xfc)
749     {
750       len = 5;
751       wc &= 0x03;
752       min_code = 1 << 21;
753     }
754   else if (wc < 0xfe)
755     {
756       len = 6;
757       wc &= 0x01;
758       min_code = 1 << 26;
759     }
760   else
761     {
762       return (gunichar)-1;
763     }
764
765   if (G_UNLIKELY (max_len >= 0 && len > max_len))
766     {
767       for (i = 1; i < max_len; i++)
768         {
769           if ((((guchar *)p)[i] & 0xc0) != 0x80)
770             return (gunichar)-1;
771         }
772       return (gunichar)-2;
773     }
774
775   for (i = 1; i < len; ++i)
776     {
777       gunichar ch = ((guchar *)p)[i];
778
779       if (G_UNLIKELY ((ch & 0xc0) != 0x80))
780         {
781           if (ch)
782             return (gunichar)-1;
783           else
784             return (gunichar)-2;
785         }
786
787       wc <<= 6;
788       wc |= (ch & 0x3f);
789     }
790
791   if (G_UNLIKELY (wc < min_code))
792     return (gunichar)-1;
793
794   return wc;
795 }
796
797 /**
798  * g_utf8_get_char_validated:
799  * @p: a pointer to Unicode character encoded as UTF-8
800  * @max_len: the maximum number of bytes to read, or -1, for no maximum or
801  *           if @p is nul-terminated
802  * 
803  * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
804  * This function checks for incomplete characters, for invalid characters
805  * such as characters that are out of the range of Unicode, and for
806  * overlong encodings of valid characters.
807  * 
808  * Return value: the resulting character. If @p points to a partial
809  *    sequence at the end of a string that could begin a valid 
810  *    character (or if @max_len is zero), returns (gunichar)-2; 
811  *    otherwise, if @p does not point to a valid UTF-8 encoded 
812  *    Unicode character, returns (gunichar)-1.
813  **/
814 gunichar
815 g_utf8_get_char_validated (const  gchar *p,
816                            gssize max_len)
817 {
818   gunichar result;
819
820   if (max_len == 0)
821     return (gunichar)-2;
822
823   result = g_utf8_get_char_extended (p, max_len);
824
825   if (result & 0x80000000)
826     return result;
827   else if (!UNICODE_VALID (result))
828     return (gunichar)-1;
829   else
830     return result;
831 }
832
833 /**
834  * g_utf8_to_ucs4_fast:
835  * @str: a UTF-8 encoded string
836  * @len: the maximum length of @str to use, in bytes. If @len < 0,
837  *       then the string is nul-terminated.
838  * @items_written: location to store the number of characters in the
839  *                 result, or %NULL.
840  *
841  * Convert a string from UTF-8 to a 32-bit fixed width
842  * representation as UCS-4, assuming valid UTF-8 input.
843  * This function is roughly twice as fast as g_utf8_to_ucs4()
844  * but does no error checking on the input. A trailing 0 character
845  * will be added to the string after the converted text.
846  * 
847  * Return value: a pointer to a newly allocated UCS-4 string.
848  *               This value must be freed with g_free().
849  **/
850 gunichar *
851 g_utf8_to_ucs4_fast (const gchar *str,
852                      glong        len,              
853                      glong       *items_written)    
854 {
855   gunichar *result;
856   gint n_chars, i;
857   const gchar *p;
858
859   g_return_val_if_fail (str != NULL, NULL);
860
861   p = str;
862   n_chars = 0;
863   if (len < 0)
864     {
865       while (*p)
866         {
867           p = g_utf8_next_char (p);
868           ++n_chars;
869         }
870     }
871   else
872     {
873       while (p < str + len && *p)
874         {
875           p = g_utf8_next_char (p);
876           ++n_chars;
877         }
878     }
879   
880   result = g_new (gunichar, n_chars + 1);
881   
882   p = str;
883   for (i=0; i < n_chars; i++)
884     {
885       gunichar wc = (guchar)*p++;
886
887       if (wc < 0x80)
888         {
889           result[i] = wc;
890         }
891       else
892         { 
893           gunichar mask = 0x40;
894
895           if (G_UNLIKELY ((wc & mask) == 0))
896             {
897               /* It's an out-of-sequence 10xxxxxxx byte.
898                * Rather than making an ugly hash of this and the next byte
899                * and overrunning the buffer, it's more useful to treat it
900                * with a replacement character */
901               result[i] = 0xfffd;
902               continue;
903             }
904
905           do
906             {
907               wc <<= 6;
908               wc |= (guchar)(*p++) & 0x3f;
909               mask <<= 5;
910             }
911           while((wc & mask) != 0);
912
913           wc &= mask - 1;
914
915           result[i] = wc;
916         }
917     }
918   result[i] = 0;
919
920   if (items_written)
921     *items_written = i;
922
923   return result;
924 }
925
926 /**
927  * g_utf8_to_ucs4:
928  * @str: a UTF-8 encoded string
929  * @len: the maximum length of @str to use, in bytes. If @len < 0,
930  *       then the string is nul-terminated.
931  * @items_read: location to store number of bytes read, or %NULL.
932  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
933  *              returned in case @str contains a trailing partial
934  *              character. If an error occurs then the index of the
935  *              invalid input is stored here.
936  * @items_written: location to store number of characters written or %NULL.
937  *                 The value here stored does not include the trailing 0
938  *                 character. 
939  * @error: location to store the error occuring, or %NULL to ignore
940  *         errors. Any of the errors in #GConvertError other than
941  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
942  *
943  * Convert a string from UTF-8 to a 32-bit fixed width
944  * representation as UCS-4. A trailing 0 character will be added to the
945  * string after the converted text.
946  * 
947  * Return value: a pointer to a newly allocated UCS-4 string.
948  *               This value must be freed with g_free(). If an
949  *               error occurs, %NULL will be returned and
950  *               @error set.
951  **/
952 gunichar *
953 g_utf8_to_ucs4 (const gchar *str,
954                 glong        len,             
955                 glong       *items_read,      
956                 glong       *items_written,   
957                 GError     **error)
958 {
959   gunichar *result = NULL;
960   gint n_chars, i;
961   const gchar *in;
962   
963   in = str;
964   n_chars = 0;
965   while ((len < 0 || str + len - in > 0) && *in)
966     {
967       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
968       if (wc & 0x80000000)
969         {
970           if (wc == (gunichar)-2)
971             {
972               if (items_read)
973                 break;
974               else
975                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
976                                      _("Partial character sequence at end of input"));
977             }
978           else
979             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
980                                  _("Invalid byte sequence in conversion input"));
981
982           goto err_out;
983         }
984
985       n_chars++;
986
987       in = g_utf8_next_char (in);
988     }
989
990   result = g_new (gunichar, n_chars + 1);
991   
992   in = str;
993   for (i=0; i < n_chars; i++)
994     {
995       result[i] = g_utf8_get_char (in);
996       in = g_utf8_next_char (in);
997     }
998   result[i] = 0;
999
1000   if (items_written)
1001     *items_written = n_chars;
1002
1003  err_out:
1004   if (items_read)
1005     *items_read = in - str;
1006
1007   return result;
1008 }
1009
1010 /**
1011  * g_ucs4_to_utf8:
1012  * @str: a UCS-4 encoded string
1013  * @len: the maximum length (number of characters) of @str to use. 
1014  *       If @len < 0, then the string is nul-terminated.
1015  * @items_read: location to store number of characters read, or %NULL.
1016  * @items_written: location to store number of bytes written or %NULL.
1017  *                 The value here stored does not include the trailing 0
1018  *                 byte. 
1019  * @error: location to store the error occuring, or %NULL to ignore
1020  *         errors. Any of the errors in #GConvertError other than
1021  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1022  *
1023  * Convert a string from a 32-bit fixed width representation as UCS-4.
1024  * to UTF-8. The result will be terminated with a 0 byte.
1025  * 
1026  * Return value: a pointer to a newly allocated UTF-8 string.
1027  *               This value must be freed with g_free(). If an
1028  *               error occurs, %NULL will be returned and
1029  *               @error set. In that case, @items_read will be
1030  *               set to the position of the first invalid input 
1031  *               character.
1032  **/
1033 gchar *
1034 g_ucs4_to_utf8 (const gunichar *str,
1035                 glong           len,              
1036                 glong          *items_read,       
1037                 glong          *items_written,    
1038                 GError        **error)
1039 {
1040   gint result_length;
1041   gchar *result = NULL;
1042   gchar *p;
1043   gint i;
1044
1045   result_length = 0;
1046   for (i = 0; len < 0 || i < len ; i++)
1047     {
1048       if (!str[i])
1049         break;
1050
1051       if (str[i] >= 0x80000000)
1052         {
1053           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1054                                _("Character out of range for UTF-8"));
1055           goto err_out;
1056         }
1057       
1058       result_length += UTF8_LENGTH (str[i]);
1059     }
1060
1061   result = g_malloc (result_length + 1);
1062   p = result;
1063
1064   i = 0;
1065   while (p < result + result_length)
1066     p += g_unichar_to_utf8 (str[i++], p);
1067   
1068   *p = '\0';
1069
1070   if (items_written)
1071     *items_written = p - result;
1072
1073  err_out:
1074   if (items_read)
1075     *items_read = i;
1076
1077   return result;
1078 }
1079
1080 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1081
1082 /**
1083  * g_utf16_to_utf8:
1084  * @str: a UTF-16 encoded string
1085  * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
1086  *       If @len < 0, then the string is nul-terminated.
1087  * @items_read: location to store number of words read, or %NULL.
1088  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1089  *              returned in case @str contains a trailing partial
1090  *              character. If an error occurs then the index of the
1091  *              invalid input is stored here.
1092  * @items_written: location to store number of bytes written, or %NULL.
1093  *                 The value stored here does not include the trailing
1094  *                 0 byte.
1095  * @error: location to store the error occuring, or %NULL to ignore
1096  *         errors. Any of the errors in #GConvertError other than
1097  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1098  *
1099  * Convert a string from UTF-16 to UTF-8. The result will be
1100  * terminated with a 0 byte.
1101  *
1102  * Note that the input is expected to be already in native endianness,
1103  * an initial byte-order-mark character is not handled specially.
1104  * g_convert() can be used to convert a byte buffer of UTF-16 data of
1105  * ambiguous endianess.
1106  *
1107  * Further note that this function does not validate the result
1108  * string; it may e.g. include embedded NUL characters. The only
1109  * validation done by this function is to ensure that the input can
1110  * be correctly interpreted as UTF-16, i.e. it doesn't contain
1111  * things unpaired surrogates.
1112  *
1113  * Return value: a pointer to a newly allocated UTF-8 string.
1114  *               This value must be freed with g_free(). If an
1115  *               error occurs, %NULL will be returned and
1116  *               @error set.
1117  **/
1118 gchar *
1119 g_utf16_to_utf8 (const gunichar2  *str,
1120                  glong             len,
1121                  glong            *items_read,
1122                  glong            *items_written,
1123                  GError          **error)
1124 {
1125   /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1126    * are marked.
1127    */
1128   const gunichar2 *in;
1129   gchar *out;
1130   gchar *result = NULL;
1131   gint n_bytes;
1132   gunichar high_surrogate;
1133
1134   g_return_val_if_fail (str != NULL, NULL);
1135
1136   n_bytes = 0;
1137   in = str;
1138   high_surrogate = 0;
1139   while ((len < 0 || in - str < len) && *in)
1140     {
1141       gunichar2 c = *in;
1142       gunichar wc;
1143
1144       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1145         {
1146           if (high_surrogate)
1147             {
1148               wc = SURROGATE_VALUE (high_surrogate, c);
1149               high_surrogate = 0;
1150             }
1151           else
1152             {
1153               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1154                                    _("Invalid sequence in conversion input"));
1155               goto err_out;
1156             }
1157         }
1158       else
1159         {
1160           if (high_surrogate)
1161             {
1162               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163                                    _("Invalid sequence in conversion input"));
1164               goto err_out;
1165             }
1166
1167           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1168             {
1169               high_surrogate = c;
1170               goto next1;
1171             }
1172           else
1173             wc = c;
1174         }
1175
1176       /********** DIFFERENT for UTF8/UCS4 **********/
1177       n_bytes += UTF8_LENGTH (wc);
1178
1179     next1:
1180       in++;
1181     }
1182
1183   if (high_surrogate && !items_read)
1184     {
1185       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1186                            _("Partial character sequence at end of input"));
1187       goto err_out;
1188     }
1189   
1190   /* At this point, everything is valid, and we just need to convert
1191    */
1192   /********** DIFFERENT for UTF8/UCS4 **********/
1193   result = g_malloc (n_bytes + 1);
1194   
1195   high_surrogate = 0;
1196   out = result;
1197   in = str;
1198   while (out < result + n_bytes)
1199     {
1200       gunichar2 c = *in;
1201       gunichar wc;
1202
1203       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1204         {
1205           wc = SURROGATE_VALUE (high_surrogate, c);
1206           high_surrogate = 0;
1207         }
1208       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1209         {
1210           high_surrogate = c;
1211           goto next2;
1212         }
1213       else
1214         wc = c;
1215
1216       /********** DIFFERENT for UTF8/UCS4 **********/
1217       out += g_unichar_to_utf8 (wc, out);
1218
1219     next2:
1220       in++;
1221     }
1222   
1223   /********** DIFFERENT for UTF8/UCS4 **********/
1224   *out = '\0';
1225
1226   if (items_written)
1227     /********** DIFFERENT for UTF8/UCS4 **********/
1228     *items_written = out - result;
1229
1230  err_out:
1231   if (items_read)
1232     *items_read = in - str;
1233
1234   return result;
1235 }
1236
1237 /**
1238  * g_utf16_to_ucs4:
1239  * @str: a UTF-16 encoded string
1240  * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
1241  *       If @len < 0, then the string is nul-terminated.
1242  * @items_read: location to store number of words read, or %NULL.
1243  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1244  *              returned in case @str contains a trailing partial
1245  *              character. If an error occurs then the index of the
1246  *              invalid input is stored here.
1247  * @items_written: location to store number of characters written, or %NULL.
1248  *                 The value stored here does not include the trailing
1249  *                 0 character.
1250  * @error: location to store the error occuring, or %NULL to ignore
1251  *         errors. Any of the errors in #GConvertError other than
1252  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1253  *
1254  * Convert a string from UTF-16 to UCS-4. The result will be
1255  * nul-terminated.
1256  * 
1257  * Return value: a pointer to a newly allocated UCS-4 string.
1258  *               This value must be freed with g_free(). If an
1259  *               error occurs, %NULL will be returned and
1260  *               @error set.
1261  **/
1262 gunichar *
1263 g_utf16_to_ucs4 (const gunichar2  *str,
1264                  glong             len,              
1265                  glong            *items_read,       
1266                  glong            *items_written,    
1267                  GError          **error)
1268 {
1269   const gunichar2 *in;
1270   gchar *out;
1271   gchar *result = NULL;
1272   gint n_bytes;
1273   gunichar high_surrogate;
1274
1275   g_return_val_if_fail (str != NULL, NULL);
1276
1277   n_bytes = 0;
1278   in = str;
1279   high_surrogate = 0;
1280   while ((len < 0 || in - str < len) && *in)
1281     {
1282       gunichar2 c = *in;
1283
1284       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1285         {
1286           if (high_surrogate)
1287             {
1288               high_surrogate = 0;
1289             }
1290           else
1291             {
1292               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1293                                    _("Invalid sequence in conversion input"));
1294               goto err_out;
1295             }
1296         }
1297       else
1298         {
1299           if (high_surrogate)
1300             {
1301               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1302                                    _("Invalid sequence in conversion input"));
1303               goto err_out;
1304             }
1305
1306           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1307             {
1308               high_surrogate = c;
1309               goto next1;
1310             }
1311         }
1312
1313       /********** DIFFERENT for UTF8/UCS4 **********/
1314       n_bytes += sizeof (gunichar);
1315
1316     next1:
1317       in++;
1318     }
1319
1320   if (high_surrogate && !items_read)
1321     {
1322       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1323                            _("Partial character sequence at end of input"));
1324       goto err_out;
1325     }
1326   
1327   /* At this point, everything is valid, and we just need to convert
1328    */
1329   /********** DIFFERENT for UTF8/UCS4 **********/
1330   result = g_malloc (n_bytes + 4);
1331   
1332   high_surrogate = 0;
1333   out = result;
1334   in = str;
1335   while (out < result + n_bytes)
1336     {
1337       gunichar2 c = *in;
1338       gunichar wc;
1339
1340       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1341         {
1342           wc = SURROGATE_VALUE (high_surrogate, c);
1343           high_surrogate = 0;
1344         }
1345       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1346         {
1347           high_surrogate = c;
1348           goto next2;
1349         }
1350       else
1351         wc = c;
1352
1353       /********** DIFFERENT for UTF8/UCS4 **********/
1354       *(gunichar *)out = wc;
1355       out += sizeof (gunichar);
1356
1357     next2:
1358       in++;
1359     }
1360
1361   /********** DIFFERENT for UTF8/UCS4 **********/
1362   *(gunichar *)out = 0;
1363
1364   if (items_written)
1365     /********** DIFFERENT for UTF8/UCS4 **********/
1366     *items_written = (out - result) / sizeof (gunichar);
1367
1368  err_out:
1369   if (items_read)
1370     *items_read = in - str;
1371
1372   return (gunichar *)result;
1373 }
1374
1375 /**
1376  * g_utf8_to_utf16:
1377  * @str: a UTF-8 encoded string
1378  * @len: the maximum length (number of bytes) of @str to use.
1379  *       If @len < 0, then the string is nul-terminated.
1380  * @items_read: location to store number of bytes read, or %NULL.
1381  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1382  *              returned in case @str contains a trailing partial
1383  *              character. If an error occurs then the index of the
1384  *              invalid input is stored here.
1385  * @items_written: location to store number of <type>gunichar2</type> written,
1386  *                 or %NULL.
1387  *                 The value stored here does not include the trailing 0.
1388  * @error: location to store the error occuring, or %NULL to ignore
1389  *         errors. Any of the errors in #GConvertError other than
1390  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1391  *
1392  * Convert a string from UTF-8 to UTF-16. A 0 character will be
1393  * added to the result after the converted text.
1394  *
1395  * Return value: a pointer to a newly allocated UTF-16 string.
1396  *               This value must be freed with g_free(). If an
1397  *               error occurs, %NULL will be returned and
1398  *               @error set.
1399  **/
1400 gunichar2 *
1401 g_utf8_to_utf16 (const gchar *str,
1402                  glong        len,
1403                  glong       *items_read,
1404                  glong       *items_written,
1405                  GError     **error)
1406 {
1407   gunichar2 *result = NULL;
1408   gint n16;
1409   const gchar *in;
1410   gint i;
1411
1412   g_return_val_if_fail (str != NULL, NULL);
1413
1414   in = str;
1415   n16 = 0;
1416   while ((len < 0 || str + len - in > 0) && *in)
1417     {
1418       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1419       if (wc & 0x80000000)
1420         {
1421           if (wc == (gunichar)-2)
1422             {
1423               if (items_read)
1424                 break;
1425               else
1426                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1427                                      _("Partial character sequence at end of input"));
1428             }
1429           else
1430             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1431                                  _("Invalid byte sequence in conversion input"));
1432
1433           goto err_out;
1434         }
1435
1436       if (wc < 0xd800)
1437         n16 += 1;
1438       else if (wc < 0xe000)
1439         {
1440           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1441                                _("Invalid sequence in conversion input"));
1442
1443           goto err_out;
1444         }
1445       else if (wc < 0x10000)
1446         n16 += 1;
1447       else if (wc < 0x110000)
1448         n16 += 2;
1449       else
1450         {
1451           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1452                                _("Character out of range for UTF-16"));
1453
1454           goto err_out;
1455         }
1456       
1457       in = g_utf8_next_char (in);
1458     }
1459
1460   result = g_new (gunichar2, n16 + 1);
1461   
1462   in = str;
1463   for (i = 0; i < n16;)
1464     {
1465       gunichar wc = g_utf8_get_char (in);
1466
1467       if (wc < 0x10000)
1468         {
1469           result[i++] = wc;
1470         }
1471       else
1472         {
1473           result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1474           result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1475         }
1476       
1477       in = g_utf8_next_char (in);
1478     }
1479
1480   result[i] = 0;
1481
1482   if (items_written)
1483     *items_written = n16;
1484
1485  err_out:
1486   if (items_read)
1487     *items_read = in - str;
1488   
1489   return result;
1490 }
1491
1492 /**
1493  * g_ucs4_to_utf16:
1494  * @str: a UCS-4 encoded string
1495  * @len: the maximum length (number of characters) of @str to use. 
1496  *       If @len < 0, then the string is nul-terminated.
1497  * @items_read: location to store number of bytes read, or %NULL.
1498  *              If an error occurs then the index of the invalid input
1499  *              is stored here.
1500  * @items_written: location to store number of <type>gunichar2</type> 
1501  *                 written, or %NULL. The value stored here does not 
1502  *                 include the trailing 0.
1503  * @error: location to store the error occuring, or %NULL to ignore
1504  *         errors. Any of the errors in #GConvertError other than
1505  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1506  *
1507  * Convert a string from UCS-4 to UTF-16. A 0 character will be
1508  * added to the result after the converted text.
1509  * 
1510  * Return value: a pointer to a newly allocated UTF-16 string.
1511  *               This value must be freed with g_free(). If an
1512  *               error occurs, %NULL will be returned and
1513  *               @error set.
1514  **/
1515 gunichar2 *
1516 g_ucs4_to_utf16 (const gunichar  *str,
1517                  glong            len,              
1518                  glong           *items_read,       
1519                  glong           *items_written,    
1520                  GError         **error)
1521 {
1522   gunichar2 *result = NULL;
1523   gint n16;
1524   gint i, j;
1525
1526   n16 = 0;
1527   i = 0;
1528   while ((len < 0 || i < len) && str[i])
1529     {
1530       gunichar wc = str[i];
1531
1532       if (wc < 0xd800)
1533         n16 += 1;
1534       else if (wc < 0xe000)
1535         {
1536           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1537                                _("Invalid sequence in conversion input"));
1538
1539           goto err_out;
1540         }
1541       else if (wc < 0x10000)
1542         n16 += 1;
1543       else if (wc < 0x110000)
1544         n16 += 2;
1545       else
1546         {
1547           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1548                                _("Character out of range for UTF-16"));
1549
1550           goto err_out;
1551         }
1552
1553       i++;
1554     }
1555   
1556   result = g_new (gunichar2, n16 + 1);
1557   
1558   for (i = 0, j = 0; j < n16; i++)
1559     {
1560       gunichar wc = str[i];
1561
1562       if (wc < 0x10000)
1563         {
1564           result[j++] = wc;
1565         }
1566       else
1567         {
1568           result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1569           result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1570         }
1571     }
1572   result[j] = 0;
1573
1574   if (items_written)
1575     *items_written = n16;
1576   
1577  err_out:
1578   if (items_read)
1579     *items_read = i;
1580   
1581   return result;
1582 }
1583
1584 #define CONTINUATION_CHAR                           \
1585  G_STMT_START {                                     \
1586   if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1587     goto error;                                     \
1588   val <<= 6;                                        \
1589   val |= (*(guchar *)p) & 0x3f;                     \
1590  } G_STMT_END
1591
1592 static const gchar *
1593 fast_validate (const char *str)
1594
1595 {
1596   gunichar val = 0;
1597   gunichar min = 0;
1598   const gchar *p;
1599
1600   for (p = str; *p; p++)
1601     {
1602       if (*(guchar *)p < 128)
1603         /* done */;
1604       else 
1605         {
1606           const gchar *last;
1607           
1608           last = p;
1609           if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1610             {
1611               if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1612                 goto error;
1613               p++;
1614               if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1615                 goto error;
1616             }
1617           else
1618             {
1619               if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1620                 {
1621                   min = (1 << 11);
1622                   val = *(guchar *)p & 0x0f;
1623                   goto TWO_REMAINING;
1624                 }
1625               else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1626                 {
1627                   min = (1 << 16);
1628                   val = *(guchar *)p & 0x07;
1629                 }
1630               else
1631                 goto error;
1632               
1633               p++;
1634               CONTINUATION_CHAR;
1635             TWO_REMAINING:
1636               p++;
1637               CONTINUATION_CHAR;
1638               p++;
1639               CONTINUATION_CHAR;
1640               
1641               if (G_UNLIKELY (val < min))
1642                 goto error;
1643
1644               if (G_UNLIKELY (!UNICODE_VALID(val)))
1645                 goto error;
1646             } 
1647           
1648           continue;
1649           
1650         error:
1651           return last;
1652         }
1653     }
1654
1655   return p;
1656 }
1657
1658 static const gchar *
1659 fast_validate_len (const char *str,
1660                    gssize      max_len)
1661
1662 {
1663   gunichar val = 0;
1664   gunichar min = 0;
1665   const gchar *p;
1666
1667   g_assert (max_len >= 0);
1668
1669   for (p = str; ((p - str) < max_len) && *p; p++)
1670     {
1671       if (*(guchar *)p < 128)
1672         /* done */;
1673       else 
1674         {
1675           const gchar *last;
1676           
1677           last = p;
1678           if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1679             {
1680               if (G_UNLIKELY (max_len - (p - str) < 2))
1681                 goto error;
1682               
1683               if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1684                 goto error;
1685               p++;
1686               if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1687                 goto error;
1688             }
1689           else
1690             {
1691               if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1692                 {
1693                   if (G_UNLIKELY (max_len - (p - str) < 3))
1694                     goto error;
1695                   
1696                   min = (1 << 11);
1697                   val = *(guchar *)p & 0x0f;
1698                   goto TWO_REMAINING;
1699                 }
1700               else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1701                 {
1702                   if (G_UNLIKELY (max_len - (p - str) < 4))
1703                     goto error;
1704                   
1705                   min = (1 << 16);
1706                   val = *(guchar *)p & 0x07;
1707                 }
1708               else
1709                 goto error;
1710               
1711               p++;
1712               CONTINUATION_CHAR;
1713             TWO_REMAINING:
1714               p++;
1715               CONTINUATION_CHAR;
1716               p++;
1717               CONTINUATION_CHAR;
1718               
1719               if (G_UNLIKELY (val < min))
1720                 goto error;
1721               if (G_UNLIKELY (!UNICODE_VALID(val)))
1722                 goto error;
1723             } 
1724           
1725           continue;
1726           
1727         error:
1728           return last;
1729         }
1730     }
1731
1732   return p;
1733 }
1734
1735 /**
1736  * g_utf8_validate:
1737  * @str: a pointer to character data
1738  * @max_len: max bytes to validate, or -1 to go until NUL
1739  * @end: return location for end of valid data
1740  * 
1741  * Validates UTF-8 encoded text. @str is the text to validate;
1742  * if @str is nul-terminated, then @max_len can be -1, otherwise
1743  * @max_len should be the number of bytes to validate.
1744  * If @end is non-%NULL, then the end of the valid range
1745  * will be stored there (i.e. the start of the first invalid 
1746  * character if some bytes were invalid, or the end of the text 
1747  * being validated otherwise).
1748  *
1749  * Note that g_utf8_validate() returns %FALSE if @max_len is 
1750  * positive and NUL is met before @max_len bytes have been read.
1751  *
1752  * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1753  * routines <emphasis>require</emphasis> valid UTF-8 as input;
1754  * so data read from a file or the network should be checked
1755  * with g_utf8_validate() before doing anything else with it.
1756  * 
1757  * Return value: %TRUE if the text was valid UTF-8
1758  **/
1759 gboolean
1760 g_utf8_validate (const char   *str,
1761                  gssize        max_len,    
1762                  const gchar **end)
1763
1764 {
1765   const gchar *p;
1766
1767   if (max_len < 0)
1768     p = fast_validate (str);
1769   else
1770     p = fast_validate_len (str, max_len);
1771
1772   if (end)
1773     *end = p;
1774
1775   if ((max_len >= 0 && p != str + max_len) ||
1776       (max_len < 0 && *p != '\0'))
1777     return FALSE;
1778   else
1779     return TRUE;
1780 }
1781
1782 /**
1783  * g_unichar_validate:
1784  * @ch: a Unicode character
1785  * 
1786  * Checks whether @ch is a valid Unicode character. Some possible
1787  * integer values of @ch will not be valid. 0 is considered a valid
1788  * character, though it's normally a string terminator.
1789  * 
1790  * Return value: %TRUE if @ch is a valid Unicode character
1791  **/
1792 gboolean
1793 g_unichar_validate (gunichar ch)
1794 {
1795   return UNICODE_VALID (ch);
1796 }
1797
1798 /**
1799  * g_utf8_strreverse:
1800  * @str: a UTF-8 encoded string
1801  * @len: the maximum length of @str to use, in bytes. If @len < 0,
1802  *       then the string is nul-terminated.
1803  *
1804  * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text. 
1805  * (Use g_utf8_validate() on all text before trying to use UTF-8 
1806  * utility functions with it.)
1807  *
1808  * This function is intended for programmatic uses of reversed strings.
1809  * It pays no attention to decomposed characters, combining marks, byte 
1810  * order marks, directional indicators (LRM, LRO, etc) and similar 
1811  * characters which might need special handling when reversing a string 
1812  * for display purposes.
1813  *
1814  * Note that unlike g_strreverse(), this function returns
1815  * newly-allocated memory, which should be freed with g_free() when
1816  * no longer needed. 
1817  *
1818  * Returns: a newly-allocated string which is the reverse of @str.
1819  *
1820  * Since: 2.2
1821  */
1822 gchar *
1823 g_utf8_strreverse (const gchar *str,
1824                    gssize       len)
1825 {
1826   gchar *r, *result;
1827   const gchar *p;
1828
1829   if (len < 0)
1830     len = strlen (str);
1831
1832   result = g_new (gchar, len + 1);
1833   r = result + len;
1834   p = str;
1835   while (r > result)
1836     {
1837       gchar *m, skip = g_utf8_skip[*(guchar*) p];
1838       r -= skip;
1839       for (m = r; skip; skip--)
1840         *m++ = *p++;
1841     }
1842   result[len] = 0;
1843
1844   return result;
1845 }
1846
1847
1848 gchar *
1849 _g_utf8_make_valid (const gchar *name)
1850 {
1851   GString *string;
1852   const gchar *remainder, *invalid;
1853   gint remaining_bytes, valid_bytes;
1854
1855   g_return_val_if_fail (name != NULL, NULL);
1856
1857   string = NULL;
1858   remainder = name;
1859   remaining_bytes = strlen (name);
1860
1861   while (remaining_bytes != 0) 
1862     {
1863       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1864         break;
1865       valid_bytes = invalid - remainder;
1866     
1867       if (string == NULL) 
1868         string = g_string_sized_new (remaining_bytes);
1869
1870       g_string_append_len (string, remainder, valid_bytes);
1871       /* append U+FFFD REPLACEMENT CHARACTER */
1872       g_string_append (string, "\357\277\275");
1873       
1874       remaining_bytes -= valid_bytes + 1;
1875       remainder = invalid + 1;
1876     }
1877   
1878   if (string == NULL)
1879     return g_strdup (name);
1880   
1881   g_string_append (string, remainder);
1882
1883   g_assert (g_utf8_validate (string->str, -1, NULL));
1884   
1885   return g_string_free (string, FALSE);
1886 }