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