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