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