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