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