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