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  * also check for malformed or overlong sequences
709  * and return (gunichar)-1 in this case.
710  */
711 static inline gunichar
712 g_utf8_get_char_extended (const  gchar *p,
713                           gssize max_len)
714 {
715   guint i, len;
716   gunichar min_code;
717   gunichar wc = (guchar) *p;
718
719   if (wc < 0x80)
720     {
721       return wc;
722     }
723   else if (G_UNLIKELY (wc < 0xc0))
724     {
725       return (gunichar)-1;
726     }
727   else if (wc < 0xe0)
728     {
729       len = 2;
730       wc &= 0x1f;
731       min_code = 1 << 7;
732     }
733   else if (wc < 0xf0)
734     {
735       len = 3;
736       wc &= 0x0f;
737       min_code = 1 << 11;
738     }
739   else if (wc < 0xf8)
740     {
741       len = 4;
742       wc &= 0x07;
743       min_code = 1 << 16;
744     }
745   else if (wc < 0xfc)
746     {
747       len = 5;
748       wc &= 0x03;
749       min_code = 1 << 21;
750     }
751   else if (wc < 0xfe)
752     {
753       len = 6;
754       wc &= 0x01;
755       min_code = 1 << 26;
756     }
757   else
758     {
759       return (gunichar)-1;
760     }
761
762   if (G_UNLIKELY (max_len >= 0 && len > max_len))
763     {
764       for (i = 1; i < max_len; i++)
765         {
766           if ((((guchar *)p)[i] & 0xc0) != 0x80)
767             return (gunichar)-1;
768         }
769       return (gunichar)-2;
770     }
771
772   for (i = 1; i < len; ++i)
773     {
774       gunichar ch = ((guchar *)p)[i];
775
776       if (G_UNLIKELY ((ch & 0xc0) != 0x80))
777         {
778           if (ch)
779             return (gunichar)-1;
780           else
781             return (gunichar)-2;
782         }
783
784       wc <<= 6;
785       wc |= (ch & 0x3f);
786     }
787
788   if (G_UNLIKELY (wc < min_code))
789     return (gunichar)-1;
790
791   return wc;
792 }
793
794 /**
795  * g_utf8_get_char_validated:
796  * @p: a pointer to Unicode character encoded as UTF-8
797  * @max_len: the maximum number of bytes to read, or -1, for no maximum or
798  *           if @p is nul-terminated
799  * 
800  * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
801  * This function checks for incomplete characters, for invalid characters
802  * such as characters that are out of the range of Unicode, and for
803  * overlong encodings of valid characters.
804  * 
805  * Return value: the resulting character. If @p points to a partial
806  *    sequence at the end of a string that could begin a valid 
807  *    character (or if @max_len is zero), returns (gunichar)-2; 
808  *    otherwise, if @p does not point to a valid UTF-8 encoded 
809  *    Unicode character, returns (gunichar)-1.
810  **/
811 gunichar
812 g_utf8_get_char_validated (const  gchar *p,
813                            gssize max_len)
814 {
815   gunichar result;
816
817   if (max_len == 0)
818     return (gunichar)-2;
819
820   result = g_utf8_get_char_extended (p, max_len);
821
822   if (result & 0x80000000)
823     return result;
824   else if (!UNICODE_VALID (result))
825     return (gunichar)-1;
826   else
827     return result;
828 }
829
830 /**
831  * g_utf8_to_ucs4_fast:
832  * @str: a UTF-8 encoded string
833  * @len: the maximum length of @str to use, in bytes. If @len < 0,
834  *       then the string is nul-terminated.
835  * @items_written: location to store the number of characters in the
836  *                 result, or %NULL.
837  *
838  * Convert a string from UTF-8 to a 32-bit fixed width
839  * representation as UCS-4, assuming valid UTF-8 input.
840  * This function is roughly twice as fast as g_utf8_to_ucs4()
841  * but does no error checking on the input.
842  * 
843  * Return value: a pointer to a newly allocated UCS-4 string.
844  *               This value must be freed with g_free().
845  **/
846 gunichar *
847 g_utf8_to_ucs4_fast (const gchar *str,
848                      glong        len,              
849                      glong       *items_written)    
850 {
851   gint j, charlen;
852   gunichar *result;
853   gint n_chars, i;
854   const gchar *p;
855
856   g_return_val_if_fail (str != NULL, NULL);
857
858   p = str;
859   n_chars = 0;
860   if (len < 0)
861     {
862       while (*p)
863         {
864           p = g_utf8_next_char (p);
865           ++n_chars;
866         }
867     }
868   else
869     {
870       while (p < str + len && *p)
871         {
872           p = g_utf8_next_char (p);
873           ++n_chars;
874         }
875     }
876   
877   result = g_new (gunichar, n_chars + 1);
878   
879   p = str;
880   for (i=0; i < n_chars; i++)
881     {
882       gunichar wc = ((unsigned char *)p)[0];
883
884       if (wc < 0x80)
885         {
886           result[i] = wc;
887           p++;
888         }
889       else
890         { 
891           if (wc < 0xe0)
892             {
893               charlen = 2;
894               wc &= 0x1f;
895             }
896           else if (wc < 0xf0)
897             {
898               charlen = 3;
899               wc &= 0x0f;
900             }
901           else if (wc < 0xf8)
902             {
903               charlen = 4;
904               wc &= 0x07;
905             }
906           else if (wc < 0xfc)
907             {
908               charlen = 5;
909               wc &= 0x03;
910             }
911           else
912             {
913               charlen = 6;
914               wc &= 0x01;
915             }
916
917           for (j = 1; j < charlen; j++)
918             {
919               wc <<= 6;
920               wc |= ((unsigned char *)p)[j] & 0x3f;
921             }
922
923           result[i] = wc;
924           p += charlen;
925         }
926     }
927   result[i] = 0;
928
929   if (items_written)
930     *items_written = i;
931
932   return result;
933 }
934
935 /**
936  * g_utf8_to_ucs4:
937  * @str: a UTF-8 encoded string
938  * @len: the maximum length of @str to use, in bytes. If @len < 0,
939  *       then the string is nul-terminated.
940  * @items_read: location to store number of bytes read, or %NULL.
941  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
942  *              returned in case @str contains a trailing partial
943  *              character. If an error occurs then the index of the
944  *              invalid input is stored here.
945  * @items_written: location to store number of characters written or %NULL.
946  *                 The value here stored does not include the trailing 0
947  *                 character. 
948  * @error: location to store the error occuring, or %NULL to ignore
949  *         errors. Any of the errors in #GConvertError other than
950  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
951  *
952  * Convert a string from UTF-8 to a 32-bit fixed width
953  * representation as UCS-4. A trailing 0 will be added to the
954  * string after the converted text.
955  * 
956  * Return value: a pointer to a newly allocated UCS-4 string.
957  *               This value must be freed with g_free(). If an
958  *               error occurs, %NULL will be returned and
959  *               @error set.
960  **/
961 gunichar *
962 g_utf8_to_ucs4 (const gchar *str,
963                 glong        len,             
964                 glong       *items_read,      
965                 glong       *items_written,   
966                 GError     **error)
967 {
968   gunichar *result = NULL;
969   gint n_chars, i;
970   const gchar *in;
971   
972   in = str;
973   n_chars = 0;
974   while ((len < 0 || str + len - in > 0) && *in)
975     {
976       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
977       if (wc & 0x80000000)
978         {
979           if (wc == (gunichar)-2)
980             {
981               if (items_read)
982                 break;
983               else
984                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
985                                      _("Partial character sequence at end of input"));
986             }
987           else
988             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
989                                  _("Invalid byte sequence in conversion input"));
990
991           goto err_out;
992         }
993
994       n_chars++;
995
996       in = g_utf8_next_char (in);
997     }
998
999   result = g_new (gunichar, n_chars + 1);
1000   
1001   in = str;
1002   for (i=0; i < n_chars; i++)
1003     {
1004       result[i] = g_utf8_get_char (in);
1005       in = g_utf8_next_char (in);
1006     }
1007   result[i] = 0;
1008
1009   if (items_written)
1010     *items_written = n_chars;
1011
1012  err_out:
1013   if (items_read)
1014     *items_read = in - str;
1015
1016   return result;
1017 }
1018
1019 /**
1020  * g_ucs4_to_utf8:
1021  * @str: a UCS-4 encoded string
1022  * @len: the maximum length (number of characters) of @str to use. 
1023  *       If @len < 0, then the string is nul-terminated.
1024  * @items_read: location to store number of characters read, or %NULL.
1025  * @items_written: location to store number of bytes written or %NULL.
1026  *                 The value here stored does not include the trailing 0
1027  *                 byte. 
1028  * @error: location to store the error occuring, or %NULL to ignore
1029  *         errors. Any of the errors in #GConvertError other than
1030  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1031  *
1032  * Convert a string from a 32-bit fixed width representation as UCS-4.
1033  * to UTF-8. The result will be terminated with a 0 byte.
1034  * 
1035  * Return value: a pointer to a newly allocated UTF-8 string.
1036  *               This value must be freed with g_free(). If an
1037  *               error occurs, %NULL will be returned and
1038  *               @error set. In that case, @items_read will be
1039  *               set to the position of the first invalid input 
1040  *               character.
1041  **/
1042 gchar *
1043 g_ucs4_to_utf8 (const gunichar *str,
1044                 glong           len,              
1045                 glong          *items_read,       
1046                 glong          *items_written,    
1047                 GError        **error)
1048 {
1049   gint result_length;
1050   gchar *result = NULL;
1051   gchar *p;
1052   gint i;
1053
1054   result_length = 0;
1055   for (i = 0; len < 0 || i < len ; i++)
1056     {
1057       if (!str[i])
1058         break;
1059
1060       if (str[i] >= 0x80000000)
1061         {
1062           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1063                                _("Character out of range for UTF-8"));
1064           goto err_out;
1065         }
1066       
1067       result_length += UTF8_LENGTH (str[i]);
1068     }
1069
1070   result = g_malloc (result_length + 1);
1071   p = result;
1072
1073   i = 0;
1074   while (p < result + result_length)
1075     p += g_unichar_to_utf8 (str[i++], p);
1076   
1077   *p = '\0';
1078
1079   if (items_written)
1080     *items_written = p - result;
1081
1082  err_out:
1083   if (items_read)
1084     *items_read = i;
1085
1086   return result;
1087 }
1088
1089 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
1090
1091 /**
1092  * g_utf16_to_utf8:
1093  * @str: a UTF-16 encoded string
1094  * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
1095  *       If @len < 0, then the string is nul-terminated.
1096  * @items_read: location to store number of words read, or %NULL.
1097  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1098  *              returned in case @str contains a trailing partial
1099  *              character. If an error occurs then the index of the
1100  *              invalid input is stored here.
1101  * @items_written: location to store number of bytes written, or %NULL.
1102  *                 The value stored here does not include the trailing
1103  *                 0 byte.
1104  * @error: location to store the error occuring, or %NULL to ignore
1105  *         errors. Any of the errors in #GConvertError other than
1106  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1107  *
1108  * Convert a string from UTF-16 to UTF-8. The result will be
1109  * terminated with a 0 byte.
1110  *
1111  * Note that the input is expected to be already in native endianness,
1112  * an initial byte-order-mark character is not handled specially.
1113  * g_convert() can be used to convert a byte buffer of UTF-16 data of
1114  * ambiguous endianess.
1115  *
1116  * Further note that this function does not validate the result
1117  * string; it may e.g. include embedded NUL characters. The only
1118  * validation done by this function is to ensure that the input can
1119  * be correctly interpreted as UTF-16, i.e. it doesn't contain
1120  * things unpaired surrogates.
1121  *
1122  * Return value: a pointer to a newly allocated UTF-8 string.
1123  *               This value must be freed with g_free(). If an
1124  *               error occurs, %NULL will be returned and
1125  *               @error set.
1126  **/
1127 gchar *
1128 g_utf16_to_utf8 (const gunichar2  *str,
1129                  glong             len,
1130                  glong            *items_read,
1131                  glong            *items_written,
1132                  GError          **error)
1133 {
1134   /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
1135    * are marked.
1136    */
1137   const gunichar2 *in;
1138   gchar *out;
1139   gchar *result = NULL;
1140   gint n_bytes;
1141   gunichar high_surrogate;
1142
1143   g_return_val_if_fail (str != NULL, NULL);
1144
1145   n_bytes = 0;
1146   in = str;
1147   high_surrogate = 0;
1148   while ((len < 0 || in - str < len) && *in)
1149     {
1150       gunichar2 c = *in;
1151       gunichar wc;
1152
1153       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1154         {
1155           if (high_surrogate)
1156             {
1157               wc = SURROGATE_VALUE (high_surrogate, c);
1158               high_surrogate = 0;
1159             }
1160           else
1161             {
1162               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1163                                    _("Invalid sequence in conversion input"));
1164               goto err_out;
1165             }
1166         }
1167       else
1168         {
1169           if (high_surrogate)
1170             {
1171               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1172                                    _("Invalid sequence in conversion input"));
1173               goto err_out;
1174             }
1175
1176           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1177             {
1178               high_surrogate = c;
1179               goto next1;
1180             }
1181           else
1182             wc = c;
1183         }
1184
1185       /********** DIFFERENT for UTF8/UCS4 **********/
1186       n_bytes += UTF8_LENGTH (wc);
1187
1188     next1:
1189       in++;
1190     }
1191
1192   if (high_surrogate && !items_read)
1193     {
1194       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1195                            _("Partial character sequence at end of input"));
1196       goto err_out;
1197     }
1198   
1199   /* At this point, everything is valid, and we just need to convert
1200    */
1201   /********** DIFFERENT for UTF8/UCS4 **********/
1202   result = g_malloc (n_bytes + 1);
1203   
1204   high_surrogate = 0;
1205   out = result;
1206   in = str;
1207   while (out < result + n_bytes)
1208     {
1209       gunichar2 c = *in;
1210       gunichar wc;
1211
1212       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1213         {
1214           wc = SURROGATE_VALUE (high_surrogate, c);
1215           high_surrogate = 0;
1216         }
1217       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1218         {
1219           high_surrogate = c;
1220           goto next2;
1221         }
1222       else
1223         wc = c;
1224
1225       /********** DIFFERENT for UTF8/UCS4 **********/
1226       out += g_unichar_to_utf8 (wc, out);
1227
1228     next2:
1229       in++;
1230     }
1231   
1232   /********** DIFFERENT for UTF8/UCS4 **********/
1233   *out = '\0';
1234
1235   if (items_written)
1236     /********** DIFFERENT for UTF8/UCS4 **********/
1237     *items_written = out - result;
1238
1239  err_out:
1240   if (items_read)
1241     *items_read = in - str;
1242
1243   return result;
1244 }
1245
1246 /**
1247  * g_utf16_to_ucs4:
1248  * @str: a UTF-16 encoded string
1249  * @len: the maximum length (number of <type>gunichar2</type>) of @str to use. 
1250  *       If @len < 0, then the string is nul-terminated.
1251  * @items_read: location to store number of words read, or %NULL.
1252  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1253  *              returned in case @str contains a trailing partial
1254  *              character. If an error occurs then the index of the
1255  *              invalid input is stored here.
1256  * @items_written: location to store number of characters written, or %NULL.
1257  *                 The value stored here does not include the trailing
1258  *                 0 character.
1259  * @error: location to store the error occuring, or %NULL to ignore
1260  *         errors. Any of the errors in #GConvertError other than
1261  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1262  *
1263  * Convert a string from UTF-16 to UCS-4. The result will be
1264  * nul-terminated.
1265  * 
1266  * Return value: a pointer to a newly allocated UCS-4 string.
1267  *               This value must be freed with g_free(). If an
1268  *               error occurs, %NULL will be returned and
1269  *               @error set.
1270  **/
1271 gunichar *
1272 g_utf16_to_ucs4 (const gunichar2  *str,
1273                  glong             len,              
1274                  glong            *items_read,       
1275                  glong            *items_written,    
1276                  GError          **error)
1277 {
1278   const gunichar2 *in;
1279   gchar *out;
1280   gchar *result = NULL;
1281   gint n_bytes;
1282   gunichar high_surrogate;
1283
1284   g_return_val_if_fail (str != NULL, NULL);
1285
1286   n_bytes = 0;
1287   in = str;
1288   high_surrogate = 0;
1289   while ((len < 0 || in - str < len) && *in)
1290     {
1291       gunichar2 c = *in;
1292       gunichar wc;
1293
1294       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1295         {
1296           if (high_surrogate)
1297             {
1298               wc = SURROGATE_VALUE (high_surrogate, c);
1299               high_surrogate = 0;
1300             }
1301           else
1302             {
1303               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1304                                    _("Invalid sequence in conversion input"));
1305               goto err_out;
1306             }
1307         }
1308       else
1309         {
1310           if (high_surrogate)
1311             {
1312               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1313                                    _("Invalid sequence in conversion input"));
1314               goto err_out;
1315             }
1316
1317           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1318             {
1319               high_surrogate = c;
1320               goto next1;
1321             }
1322           else
1323             wc = c;
1324         }
1325
1326       /********** DIFFERENT for UTF8/UCS4 **********/
1327       n_bytes += sizeof (gunichar);
1328
1329     next1:
1330       in++;
1331     }
1332
1333   if (high_surrogate && !items_read)
1334     {
1335       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1336                            _("Partial character sequence at end of input"));
1337       goto err_out;
1338     }
1339   
1340   /* At this point, everything is valid, and we just need to convert
1341    */
1342   /********** DIFFERENT for UTF8/UCS4 **********/
1343   result = g_malloc (n_bytes + 4);
1344   
1345   high_surrogate = 0;
1346   out = result;
1347   in = str;
1348   while (out < result + n_bytes)
1349     {
1350       gunichar2 c = *in;
1351       gunichar wc;
1352
1353       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1354         {
1355           wc = SURROGATE_VALUE (high_surrogate, c);
1356           high_surrogate = 0;
1357         }
1358       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1359         {
1360           high_surrogate = c;
1361           goto next2;
1362         }
1363       else
1364         wc = c;
1365
1366       /********** DIFFERENT for UTF8/UCS4 **********/
1367       *(gunichar *)out = wc;
1368       out += sizeof (gunichar);
1369
1370     next2:
1371       in++;
1372     }
1373
1374   /********** DIFFERENT for UTF8/UCS4 **********/
1375   *(gunichar *)out = 0;
1376
1377   if (items_written)
1378     /********** DIFFERENT for UTF8/UCS4 **********/
1379     *items_written = (out - result) / sizeof (gunichar);
1380
1381  err_out:
1382   if (items_read)
1383     *items_read = in - str;
1384
1385   return (gunichar *)result;
1386 }
1387
1388 /**
1389  * g_utf8_to_utf16:
1390  * @str: a UTF-8 encoded string
1391  * @len: the maximum length (number of bytes) of @str to use.
1392  *       If @len < 0, then the string is nul-terminated.
1393  * @items_read: location to store number of bytes read, or %NULL.
1394  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1395  *              returned in case @str contains a trailing partial
1396  *              character. If an error occurs then the index of the
1397  *              invalid input is stored here.
1398  * @items_written: location to store number of <type>gunichar2</type> written,
1399  *                 or %NULL.
1400  *                 The value stored here does not include the trailing 0.
1401  * @error: location to store the error occuring, or %NULL to ignore
1402  *         errors. Any of the errors in #GConvertError other than
1403  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1404  *
1405  * Convert a string from UTF-8 to UTF-16. A 0 character will be
1406  * added to the result after the converted text.
1407  *
1408  * Return value: a pointer to a newly allocated UTF-16 string.
1409  *               This value must be freed with g_free(). If an
1410  *               error occurs, %NULL will be returned and
1411  *               @error set.
1412  **/
1413 gunichar2 *
1414 g_utf8_to_utf16 (const gchar *str,
1415                  glong        len,
1416                  glong       *items_read,
1417                  glong       *items_written,
1418                  GError     **error)
1419 {
1420   gunichar2 *result = NULL;
1421   gint n16;
1422   const gchar *in;
1423   gint i;
1424
1425   g_return_val_if_fail (str != NULL, NULL);
1426
1427   in = str;
1428   n16 = 0;
1429   while ((len < 0 || str + len - in > 0) && *in)
1430     {
1431       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1432       if (wc & 0x80000000)
1433         {
1434           if (wc == (gunichar)-2)
1435             {
1436               if (items_read)
1437                 break;
1438               else
1439                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1440                                      _("Partial character sequence at end of input"));
1441             }
1442           else
1443             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1444                                  _("Invalid byte sequence in conversion input"));
1445
1446           goto err_out;
1447         }
1448
1449       if (wc < 0xd800)
1450         n16 += 1;
1451       else if (wc < 0xe000)
1452         {
1453           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1454                                _("Invalid sequence in conversion input"));
1455
1456           goto err_out;
1457         }
1458       else if (wc < 0x10000)
1459         n16 += 1;
1460       else if (wc < 0x110000)
1461         n16 += 2;
1462       else
1463         {
1464           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1465                                _("Character out of range for UTF-16"));
1466
1467           goto err_out;
1468         }
1469       
1470       in = g_utf8_next_char (in);
1471     }
1472
1473   result = g_new (gunichar2, n16 + 1);
1474   
1475   in = str;
1476   for (i = 0; i < n16;)
1477     {
1478       gunichar wc = g_utf8_get_char (in);
1479
1480       if (wc < 0x10000)
1481         {
1482           result[i++] = wc;
1483         }
1484       else
1485         {
1486           result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1487           result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1488         }
1489       
1490       in = g_utf8_next_char (in);
1491     }
1492
1493   result[i] = 0;
1494
1495   if (items_written)
1496     *items_written = n16;
1497
1498  err_out:
1499   if (items_read)
1500     *items_read = in - str;
1501   
1502   return result;
1503 }
1504
1505 /**
1506  * g_ucs4_to_utf16:
1507  * @str: a UCS-4 encoded string
1508  * @len: the maximum length (number of characters) of @str to use. 
1509  *       If @len < 0, then the string is nul-terminated.
1510  * @items_read: location to store number of bytes read, or %NULL.
1511  *              If an error occurs then the index of the invalid input
1512  *              is stored here.
1513  * @items_written: location to store number of <type>gunichar2</type> 
1514  *                 written, or %NULL. The value stored here does not 
1515  *                 include the trailing 0.
1516  * @error: location to store the error occuring, or %NULL to ignore
1517  *         errors. Any of the errors in #GConvertError other than
1518  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1519  *
1520  * Convert a string from UCS-4 to UTF-16. A 0 character will be
1521  * added to the result after the converted text.
1522  * 
1523  * Return value: a pointer to a newly allocated UTF-16 string.
1524  *               This value must be freed with g_free(). If an
1525  *               error occurs, %NULL will be returned and
1526  *               @error set.
1527  **/
1528 gunichar2 *
1529 g_ucs4_to_utf16 (const gunichar  *str,
1530                  glong            len,              
1531                  glong           *items_read,       
1532                  glong           *items_written,    
1533                  GError         **error)
1534 {
1535   gunichar2 *result = NULL;
1536   gint n16;
1537   gint i, j;
1538
1539   n16 = 0;
1540   i = 0;
1541   while ((len < 0 || i < len) && str[i])
1542     {
1543       gunichar wc = str[i];
1544
1545       if (wc < 0xd800)
1546         n16 += 1;
1547       else if (wc < 0xe000)
1548         {
1549           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1550                                _("Invalid sequence in conversion input"));
1551
1552           goto err_out;
1553         }
1554       else if (wc < 0x10000)
1555         n16 += 1;
1556       else if (wc < 0x110000)
1557         n16 += 2;
1558       else
1559         {
1560           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1561                                _("Character out of range for UTF-16"));
1562
1563           goto err_out;
1564         }
1565
1566       i++;
1567     }
1568   
1569   result = g_new (gunichar2, n16 + 1);
1570   
1571   for (i = 0, j = 0; j < n16; i++)
1572     {
1573       gunichar wc = str[i];
1574
1575       if (wc < 0x10000)
1576         {
1577           result[j++] = wc;
1578         }
1579       else
1580         {
1581           result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1582           result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1583         }
1584     }
1585   result[j] = 0;
1586
1587   if (items_written)
1588     *items_written = n16;
1589   
1590  err_out:
1591   if (items_read)
1592     *items_read = i;
1593   
1594   return result;
1595 }
1596
1597 #define CONTINUATION_CHAR                           \
1598  G_STMT_START {                                     \
1599   if ((*(guchar *)p & 0xc0) != 0x80) /* 10xxxxxx */ \
1600     goto error;                                     \
1601   val <<= 6;                                        \
1602   val |= (*(guchar *)p) & 0x3f;                     \
1603  } G_STMT_END
1604
1605 static const gchar *
1606 fast_validate (const char *str)
1607
1608 {
1609   gunichar val = 0;
1610   gunichar min = 0;
1611   const gchar *p;
1612
1613   for (p = str; *p; p++)
1614     {
1615       if (*(guchar *)p < 128)
1616         /* done */;
1617       else 
1618         {
1619           const gchar *last;
1620           
1621           last = p;
1622           if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1623             {
1624               if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1625                 goto error;
1626               p++;
1627               if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1628                 goto error;
1629             }
1630           else
1631             {
1632               if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1633                 {
1634                   min = (1 << 11);
1635                   val = *(guchar *)p & 0x0f;
1636                   goto TWO_REMAINING;
1637                 }
1638               else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1639                 {
1640                   min = (1 << 16);
1641                   val = *(guchar *)p & 0x07;
1642                 }
1643               else
1644                 goto error;
1645               
1646               p++;
1647               CONTINUATION_CHAR;
1648             TWO_REMAINING:
1649               p++;
1650               CONTINUATION_CHAR;
1651               p++;
1652               CONTINUATION_CHAR;
1653               
1654               if (G_UNLIKELY (val < min))
1655                 goto error;
1656
1657               if (G_UNLIKELY (!UNICODE_VALID(val)))
1658                 goto error;
1659             } 
1660           
1661           continue;
1662           
1663         error:
1664           return last;
1665         }
1666     }
1667
1668   return p;
1669 }
1670
1671 static const gchar *
1672 fast_validate_len (const char *str,
1673                    gssize      max_len)
1674
1675 {
1676   gunichar val = 0;
1677   gunichar min = 0;
1678   const gchar *p;
1679
1680   g_assert (max_len >= 0);
1681
1682   for (p = str; ((p - str) < max_len) && *p; p++)
1683     {
1684       if (*(guchar *)p < 128)
1685         /* done */;
1686       else 
1687         {
1688           const gchar *last;
1689           
1690           last = p;
1691           if ((*(guchar *)p & 0xe0) == 0xc0) /* 110xxxxx */
1692             {
1693               if (G_UNLIKELY (max_len - (p - str) < 2))
1694                 goto error;
1695               
1696               if (G_UNLIKELY ((*(guchar *)p & 0x1e) == 0))
1697                 goto error;
1698               p++;
1699               if (G_UNLIKELY ((*(guchar *)p & 0xc0) != 0x80)) /* 10xxxxxx */
1700                 goto error;
1701             }
1702           else
1703             {
1704               if ((*(guchar *)p & 0xf0) == 0xe0) /* 1110xxxx */
1705                 {
1706                   if (G_UNLIKELY (max_len - (p - str) < 3))
1707                     goto error;
1708                   
1709                   min = (1 << 11);
1710                   val = *(guchar *)p & 0x0f;
1711                   goto TWO_REMAINING;
1712                 }
1713               else if ((*(guchar *)p & 0xf8) == 0xf0) /* 11110xxx */
1714                 {
1715                   if (G_UNLIKELY (max_len - (p - str) < 4))
1716                     goto error;
1717                   
1718                   min = (1 << 16);
1719                   val = *(guchar *)p & 0x07;
1720                 }
1721               else
1722                 goto error;
1723               
1724               p++;
1725               CONTINUATION_CHAR;
1726             TWO_REMAINING:
1727               p++;
1728               CONTINUATION_CHAR;
1729               p++;
1730               CONTINUATION_CHAR;
1731               
1732               if (G_UNLIKELY (val < min))
1733                 goto error;
1734               if (G_UNLIKELY (!UNICODE_VALID(val)))
1735                 goto error;
1736             } 
1737           
1738           continue;
1739           
1740         error:
1741           return last;
1742         }
1743     }
1744
1745   return p;
1746 }
1747
1748 /**
1749  * g_utf8_validate:
1750  * @str: a pointer to character data
1751  * @max_len: max bytes to validate, or -1 to go until NUL
1752  * @end: return location for end of valid data
1753  * 
1754  * Validates UTF-8 encoded text. @str is the text to validate;
1755  * if @str is nul-terminated, then @max_len can be -1, otherwise
1756  * @max_len should be the number of bytes to validate.
1757  * If @end is non-%NULL, then the end of the valid range
1758  * will be stored there (i.e. the start of the first invalid 
1759  * character if some bytes were invalid, or the end of the text 
1760  * being validated otherwise).
1761  *
1762  * Note that g_utf8_validate() returns %FALSE if @max_len is 
1763  * positive and NUL is met before @max_len bytes have been read.
1764  *
1765  * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1766  * routines <emphasis>require</emphasis> valid UTF-8 as input;
1767  * so data read from a file or the network should be checked
1768  * with g_utf8_validate() before doing anything else with it.
1769  * 
1770  * Return value: %TRUE if the text was valid UTF-8
1771  **/
1772 gboolean
1773 g_utf8_validate (const char   *str,
1774                  gssize        max_len,    
1775                  const gchar **end)
1776
1777 {
1778   const gchar *p;
1779
1780   if (max_len < 0)
1781     p = fast_validate (str);
1782   else
1783     p = fast_validate_len (str, max_len);
1784
1785   if (end)
1786     *end = p;
1787
1788   if ((max_len >= 0 && p != str + max_len) ||
1789       (max_len < 0 && *p != '\0'))
1790     return FALSE;
1791   else
1792     return TRUE;
1793 }
1794
1795 /**
1796  * g_unichar_validate:
1797  * @ch: a Unicode character
1798  * 
1799  * Checks whether @ch is a valid Unicode character. Some possible
1800  * integer values of @ch will not be valid. 0 is considered a valid
1801  * character, though it's normally a string terminator.
1802  * 
1803  * Return value: %TRUE if @ch is a valid Unicode character
1804  **/
1805 gboolean
1806 g_unichar_validate (gunichar ch)
1807 {
1808   return UNICODE_VALID (ch);
1809 }
1810
1811 /**
1812  * g_utf8_strreverse:
1813  * @str: a UTF-8 encoded string
1814  * @len: the maximum length of @str to use, in bytes. If @len < 0,
1815  *       then the string is nul-terminated.
1816  *
1817  * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text. 
1818  * (Use g_utf8_validate() on all text before trying to use UTF-8 
1819  * utility functions with it.)
1820  *
1821  * This function is intended for programmatic uses of reversed strings.
1822  * It pays no attention to decomposed characters, combining marks, byte 
1823  * order marks, directional indicators (LRM, LRO, etc) and similar 
1824  * characters which might need special handling when reversing a string 
1825  * for display purposes.
1826  *
1827  * Note that unlike g_strreverse(), this function returns
1828  * newly-allocated memory, which should be freed with g_free() when
1829  * no longer needed. 
1830  *
1831  * Returns: a newly-allocated string which is the reverse of @str.
1832  *
1833  * Since: 2.2
1834  */
1835 gchar *
1836 g_utf8_strreverse (const gchar *str,
1837                    gssize       len)
1838 {
1839   gchar *r, *result;
1840   const gchar *p;
1841
1842   if (len < 0)
1843     len = strlen (str);
1844
1845   result = g_new (gchar, len + 1);
1846   r = result + len;
1847   p = str;
1848   while (r > result)
1849     {
1850       gchar *m, skip = g_utf8_skip[*(guchar*) p];
1851       r -= skip;
1852       for (m = r; skip; skip--)
1853         *m++ = *p++;
1854     }
1855   result[len] = 0;
1856
1857   return result;
1858 }
1859
1860
1861 gchar *
1862 _g_utf8_make_valid (const gchar *name)
1863 {
1864   GString *string;
1865   const gchar *remainder, *invalid;
1866   gint remaining_bytes, valid_bytes;
1867
1868   g_return_val_if_fail (name != NULL, NULL);
1869
1870   string = NULL;
1871   remainder = name;
1872   remaining_bytes = strlen (name);
1873
1874   while (remaining_bytes != 0) 
1875     {
1876       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1877         break;
1878       valid_bytes = invalid - remainder;
1879     
1880       if (string == NULL) 
1881         string = g_string_sized_new (remaining_bytes);
1882
1883       g_string_append_len (string, remainder, valid_bytes);
1884       /* append U+FFFD REPLACEMENT CHARACTER */
1885       g_string_append (string, "\357\277\275");
1886       
1887       remaining_bytes -= valid_bytes + 1;
1888       remainder = invalid + 1;
1889     }
1890   
1891   if (string == NULL)
1892     return g_strdup (name);
1893   
1894   g_string_append (string, remainder);
1895
1896   g_assert (g_utf8_validate (string->str, -1, NULL));
1897   
1898   return g_string_free (string, FALSE);
1899 }
1900
1901
1902 #define __G_UTF8_C__
1903 #include "galiasdef.c"