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