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