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