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