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