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