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