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