[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[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: 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 (*p)
172     {
173       if (end)
174         for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
175           ;
176       else
177         for (++p; (*p & 0xc0) == 0x80; ++p)
178           ;
179     }
180   return (p == end) ? NULL : (gchar *)p;
181 }
182
183 /**
184  * g_utf8_prev_char:
185  * @p: a pointer to a position within a UTF-8 encoded string
186  *
187  * Finds the previous UTF-8 character in the string before @p.
188  *
189  * @p does not have to be at the beginning of a UTF-8 character. No check
190  * is made to see if the character found is actually valid other than
191  * it starts with an appropriate byte. If @p might be the first
192  * character of the string, you must use g_utf8_find_prev_char() instead.
193  * 
194  * Returns: a pointer to the found character
195  */
196 gchar *
197 g_utf8_prev_char (const gchar *p)
198 {
199   while (TRUE)
200     {
201       p--;
202       if ((*p & 0xc0) != 0x80)
203         return (gchar *)p;
204     }
205 }
206  
207 /**
208  * g_utf8_strlen:
209  * @p: pointer to the start of a UTF-8 encoded string
210  * @max: the maximum number of bytes to examine. If @max
211  *       is less than 0, then the string is assumed to be
212  *       nul-terminated. If @max is 0, @p will not be examined and
213  *       may be %NULL. If @max is greater than 0, up to @max
214  *       bytes are examined
215  *
216  * Computes the length of the string in characters, not including
217  * the terminating nul character. If the @max'th byte falls in the
218  * middle of a character, the last (partial) character is not counted.
219  *
220  * Returns: the length of the string in characters
221  */
222 glong
223 g_utf8_strlen (const gchar *p,
224                gssize       max)
225 {
226   glong len = 0;
227   const gchar *start = p;
228   g_return_val_if_fail (p != NULL || max == 0, 0);
229
230   if (max < 0)
231     {
232       while (*p)
233         {
234           p = g_utf8_next_char (p);
235           ++len;
236         }
237     }
238   else
239     {
240       if (max == 0 || !*p)
241         return 0;
242
243       p = g_utf8_next_char (p);
244
245       while (p - start < max && *p)
246         {
247           ++len;
248           p = g_utf8_next_char (p);
249         }
250
251       /* only do the last len increment if we got a complete
252        * char (don't count partial chars)
253        */
254       if (p - start <= max)
255         ++len;
256     }
257
258   return len;
259 }
260
261 /**
262  * g_utf8_substring:
263  * @str: a UTF-8 encoded string
264  * @start_pos: a character offset within @str
265  * @end_pos: another character offset within @str
266  *
267  * Copies a substring out of a UTF-8 encoded string.
268  * The substring will contain @end_pos - @start_pos characters.
269  *
270  * Returns: a newly allocated copy of the requested
271  *     substring. Free with g_free() when no longer needed.
272  *
273  * Since: 2.30
274  */
275 gchar *
276 g_utf8_substring (const gchar *str,
277                   glong        start_pos,
278                   glong        end_pos)
279 {
280   gchar *start, *end, *out;
281
282   start = g_utf8_offset_to_pointer (str, start_pos);
283   end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
284
285   out = g_malloc (end - start + 1);
286   memcpy (out, start, end - start);
287   out[end - start] = 0;
288
289   return out;
290 }
291
292 /**
293  * g_utf8_get_char:
294  * @p: a pointer to Unicode character encoded as UTF-8
295  * 
296  * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
297  *
298  * If @p does not point to a valid UTF-8 encoded character, results
299  * are undefined. If you are not sure that the bytes are complete
300  * valid Unicode characters, you should use g_utf8_get_char_validated()
301  * instead.
302  * 
303  * Returns: the resulting character
304  */
305 gunichar
306 g_utf8_get_char (const gchar *p)
307 {
308   int i, mask = 0, len;
309   gunichar result;
310   unsigned char c = (unsigned char) *p;
311
312   UTF8_COMPUTE (c, mask, len);
313   if (len == -1)
314     return (gunichar)-1;
315   UTF8_GET (result, p, i, mask, len);
316
317   return result;
318 }
319
320 /**
321  * g_utf8_offset_to_pointer:
322  * @str: a UTF-8 encoded string
323  * @offset: a character offset within @str
324  *
325  * Converts from an integer character offset to a pointer to a position
326  * within the string.
327  *
328  * Since 2.10, this function allows to pass a negative @offset to
329  * step backwards. It is usually worth stepping backwards from the end
330  * instead of forwards if @offset is in the last fourth of the string,
331  * since moving forward is about 3 times faster than moving backward.
332  *
333  * Note that this function doesn't abort when reaching the end of @str.
334  * Therefore you should be sure that @offset is within string boundaries
335  * before calling that function. Call g_utf8_strlen() when unsure.
336  * This limitation exists as this function is called frequently during
337  * text rendering and therefore has to be as fast as possible.
338  *
339  * Returns: the resulting pointer
340  */
341 gchar *
342 g_utf8_offset_to_pointer  (const gchar *str,
343                            glong        offset)
344 {
345   const gchar *s = str;
346
347   if (offset > 0) 
348     while (offset--)
349       s = g_utf8_next_char (s);
350   else
351     {
352       const char *s1;
353
354       /* This nice technique for fast backwards stepping 
355        * through a UTF-8 string was dubbed "stutter stepping" 
356        * by its inventor, Larry Ewing.
357        */
358       while (offset)
359         {
360           s1 = s;
361           s += offset;
362           while ((*s & 0xc0) == 0x80)
363             s--;
364
365           offset += g_utf8_pointer_to_offset (s, s1);
366         }
367     }
368
369   return (gchar *)s;
370 }
371
372 /**
373  * g_utf8_pointer_to_offset:
374  * @str: a UTF-8 encoded string
375  * @pos: a pointer to a position within @str
376  * 
377  * Converts from a pointer to position within a string to a integer
378  * character offset.
379  *
380  * Since 2.10, this function allows @pos to be before @str, and returns
381  * a negative offset in this case.
382  * 
383  * Returns: the resulting character offset
384  */
385 glong    
386 g_utf8_pointer_to_offset (const gchar *str,
387                           const gchar *pos)
388 {
389   const gchar *s = str;
390   glong offset = 0;    
391
392   if (pos < str) 
393     offset = - g_utf8_pointer_to_offset (pos, str);
394   else
395     while (s < pos)
396       {
397         s = g_utf8_next_char (s);
398         offset++;
399       }
400   
401   return offset;
402 }
403
404
405 /**
406  * g_utf8_strncpy:
407  * @dest: buffer to fill with characters from @src
408  * @src: UTF-8 encoded string
409  * @n: character count
410  * 
411  * Like the standard C strncpy() function, but copies a given number
412  * of characters instead of a given number of bytes. The @src string
413  * must be valid UTF-8 encoded text. (Use g_utf8_validate() on all
414  * text before trying to use UTF-8 utility functions with it.)
415  * 
416  * Returns: @dest
417  */
418 gchar *
419 g_utf8_strncpy (gchar       *dest,
420                 const gchar *src,
421                 gsize        n)
422 {
423   const gchar *s = src;
424   while (n && *s)
425     {
426       s = g_utf8_next_char(s);
427       n--;
428     }
429   strncpy(dest, src, s - src);
430   dest[s - src] = 0;
431   return dest;
432 }
433
434 /* unicode_strchr */
435
436 /**
437  * g_unichar_to_utf8:
438  * @c: a Unicode character code
439  * @outbuf: output buffer, must have at least 6 bytes of space.
440  *       If %NULL, the length will be computed and returned
441  *       and nothing will be written to @outbuf.
442  * 
443  * Converts a single character to UTF-8.
444  * 
445  * Returns: number of bytes written
446  */
447 int
448 g_unichar_to_utf8 (gunichar c,
449                    gchar   *outbuf)
450 {
451   /* If this gets modified, also update the copy in g_string_insert_unichar() */
452   guint len = 0;    
453   int first;
454   int i;
455
456   if (c < 0x80)
457     {
458       first = 0;
459       len = 1;
460     }
461   else if (c < 0x800)
462     {
463       first = 0xc0;
464       len = 2;
465     }
466   else if (c < 0x10000)
467     {
468       first = 0xe0;
469       len = 3;
470     }
471    else if (c < 0x200000)
472     {
473       first = 0xf0;
474       len = 4;
475     }
476   else if (c < 0x4000000)
477     {
478       first = 0xf8;
479       len = 5;
480     }
481   else
482     {
483       first = 0xfc;
484       len = 6;
485     }
486
487   if (outbuf)
488     {
489       for (i = len - 1; i > 0; --i)
490         {
491           outbuf[i] = (c & 0x3f) | 0x80;
492           c >>= 6;
493         }
494       outbuf[0] = c | first;
495     }
496
497   return len;
498 }
499
500 /**
501  * g_utf8_strchr:
502  * @p: a nul-terminated UTF-8 encoded string
503  * @len: the maximum length of @p
504  * @c: a Unicode character
505  * 
506  * Finds the leftmost occurrence of the given Unicode character
507  * in a UTF-8 encoded string, while limiting the search to @len bytes.
508  * If @len is -1, allow unbounded search.
509  * 
510  * Returns: %NULL if the string does not contain the character, 
511  *     otherwise, a pointer to the start of the leftmost occurrence
512  *     of the character in the string.
513  */
514 gchar *
515 g_utf8_strchr (const char *p,
516                gssize      len,
517                gunichar    c)
518 {
519   gchar ch[10];
520
521   gint charlen = g_unichar_to_utf8 (c, ch);
522   ch[charlen] = '\0';
523   
524   return g_strstr_len (p, len, ch);
525 }
526
527
528 /**
529  * g_utf8_strrchr:
530  * @p: a nul-terminated UTF-8 encoded string
531  * @len: the maximum length of @p
532  * @c: a Unicode character
533  * 
534  * Find the rightmost occurrence of the given Unicode character
535  * in a UTF-8 encoded string, while limiting the search to @len bytes.
536  * If @len is -1, allow unbounded search.
537  * 
538  * Returns: %NULL if the string does not contain the character, 
539  *     otherwise, a pointer to the start of the rightmost occurrence
540  *     of the character in the string.
541  */
542 gchar *
543 g_utf8_strrchr (const char *p,
544                 gssize      len,
545                 gunichar    c)
546 {
547   gchar ch[10];
548
549   gint charlen = g_unichar_to_utf8 (c, ch);
550   ch[charlen] = '\0';
551   
552   return g_strrstr_len (p, len, ch);
553 }
554
555
556 /* Like g_utf8_get_char, but take a maximum length
557  * and return (gunichar)-2 on incomplete trailing character;
558  * also check for malformed or overlong sequences
559  * and return (gunichar)-1 in this case.
560  */
561 static inline gunichar
562 g_utf8_get_char_extended (const  gchar *p,
563                           gssize max_len)
564 {
565   guint i, len;
566   gunichar min_code;
567   gunichar wc = (guchar) *p;
568
569   if (wc < 0x80)
570     {
571       return wc;
572     }
573   else if (G_UNLIKELY (wc < 0xc0))
574     {
575       return (gunichar)-1;
576     }
577   else if (wc < 0xe0)
578     {
579       len = 2;
580       wc &= 0x1f;
581       min_code = 1 << 7;
582     }
583   else if (wc < 0xf0)
584     {
585       len = 3;
586       wc &= 0x0f;
587       min_code = 1 << 11;
588     }
589   else if (wc < 0xf8)
590     {
591       len = 4;
592       wc &= 0x07;
593       min_code = 1 << 16;
594     }
595   else if (wc < 0xfc)
596     {
597       len = 5;
598       wc &= 0x03;
599       min_code = 1 << 21;
600     }
601   else if (wc < 0xfe)
602     {
603       len = 6;
604       wc &= 0x01;
605       min_code = 1 << 26;
606     }
607   else
608     {
609       return (gunichar)-1;
610     }
611
612   if (G_UNLIKELY (max_len >= 0 && len > max_len))
613     {
614       for (i = 1; i < max_len; i++)
615         {
616           if ((((guchar *)p)[i] & 0xc0) != 0x80)
617             return (gunichar)-1;
618         }
619       return (gunichar)-2;
620     }
621
622   for (i = 1; i < len; ++i)
623     {
624       gunichar ch = ((guchar *)p)[i];
625
626       if (G_UNLIKELY ((ch & 0xc0) != 0x80))
627         {
628           if (ch)
629             return (gunichar)-1;
630           else
631             return (gunichar)-2;
632         }
633
634       wc <<= 6;
635       wc |= (ch & 0x3f);
636     }
637
638   if (G_UNLIKELY (wc < min_code))
639     return (gunichar)-1;
640
641   return wc;
642 }
643
644 /**
645  * g_utf8_get_char_validated:
646  * @p: a pointer to Unicode character encoded as UTF-8
647  * @max_len: the maximum number of bytes to read, or -1, for no maximum or
648  *     if @p is nul-terminated
649  * 
650  * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
651  * This function checks for incomplete characters, for invalid characters
652  * such as characters that are out of the range of Unicode, and for
653  * overlong encodings of valid characters.
654  * 
655  * Returns: the resulting character. If @p points to a partial
656  *     sequence at the end of a string that could begin a valid 
657  *     character (or if @max_len is zero), returns (gunichar)-2; 
658  *     otherwise, if @p does not point to a valid UTF-8 encoded 
659  *     Unicode character, returns (gunichar)-1.
660  */
661 gunichar
662 g_utf8_get_char_validated (const gchar *p,
663                            gssize       max_len)
664 {
665   gunichar result;
666
667   if (max_len == 0)
668     return (gunichar)-2;
669
670   result = g_utf8_get_char_extended (p, max_len);
671
672   if (result & 0x80000000)
673     return result;
674   else if (!UNICODE_VALID (result))
675     return (gunichar)-1;
676   else
677     return result;
678 }
679
680 /**
681  * g_utf8_to_ucs4_fast:
682  * @str: a UTF-8 encoded string
683  * @len: the maximum length of @str to use, in bytes. If @len < 0,
684  *     then the string is nul-terminated.
685  * @items_written: (allow-none): location to store the number of
686  *     characters in the result, or %NULL.
687  *
688  * Convert a string from UTF-8 to a 32-bit fixed width
689  * representation as UCS-4, assuming valid UTF-8 input.
690  * This function is roughly twice as fast as g_utf8_to_ucs4()
691  * but does no error checking on the input. A trailing 0 character
692  * will be added to the string after the converted text.
693  * 
694  * Returns: a pointer to a newly allocated UCS-4 string.
695  *     This value must be freed with g_free().
696  */
697 gunichar *
698 g_utf8_to_ucs4_fast (const gchar *str,
699                      glong        len,              
700                      glong       *items_written)    
701 {
702   gunichar *result;
703   gint n_chars, i;
704   const gchar *p;
705
706   g_return_val_if_fail (str != NULL, NULL);
707
708   p = str;
709   n_chars = 0;
710   if (len < 0)
711     {
712       while (*p)
713         {
714           p = g_utf8_next_char (p);
715           ++n_chars;
716         }
717     }
718   else
719     {
720       while (p < str + len && *p)
721         {
722           p = g_utf8_next_char (p);
723           ++n_chars;
724         }
725     }
726   
727   result = g_new (gunichar, n_chars + 1);
728   
729   p = str;
730   for (i=0; i < n_chars; i++)
731     {
732       gunichar wc = (guchar)*p++;
733
734       if (wc < 0x80)
735         {
736           result[i] = wc;
737         }
738       else
739         { 
740           gunichar mask = 0x40;
741
742           if (G_UNLIKELY ((wc & mask) == 0))
743             {
744               /* It's an out-of-sequence 10xxxxxxx byte.
745                * Rather than making an ugly hash of this and the next byte
746                * and overrunning the buffer, it's more useful to treat it
747                * with a replacement character
748                */
749               result[i] = 0xfffd;
750               continue;
751             }
752
753           do
754             {
755               wc <<= 6;
756               wc |= (guchar)(*p++) & 0x3f;
757               mask <<= 5;
758             }
759           while((wc & mask) != 0);
760
761           wc &= mask - 1;
762
763           result[i] = wc;
764         }
765     }
766   result[i] = 0;
767
768   if (items_written)
769     *items_written = i;
770
771   return result;
772 }
773
774 static gpointer
775 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
776 {
777     gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
778     if (ptr == NULL)
779       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
780                            _("Failed to allocate memory"));
781     return ptr;
782 }
783
784 /**
785  * g_utf8_to_ucs4:
786  * @str: a UTF-8 encoded string
787  * @len: the maximum length of @str to use, in bytes. If @len < 0,
788  *     then the string is nul-terminated.
789  * @items_read: (allow-none): location to store number of bytes read, or %NULL.
790  *     If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
791  *     returned in case @str contains a trailing partial
792  *     character. If an error occurs then the index of the
793  *     invalid input is stored here.
794  * @items_written: (allow-none): location to store number of characters
795  *     written or %NULL. The value here stored does not include the
796  *     trailing 0 character. 
797  * @error: location to store the error occurring, or %NULL to ignore
798  *     errors. Any of the errors in #GConvertError other than
799  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
800  *
801  * Convert a string from UTF-8 to a 32-bit fixed width
802  * representation as UCS-4. A trailing 0 character will be added to the
803  * string after the converted text.
804  * 
805  * Returns: a pointer to a newly allocated UCS-4 string.
806  *     This value must be freed with g_free(). If an error occurs,
807  *     %NULL will be returned and @error set.
808  */
809 gunichar *
810 g_utf8_to_ucs4 (const gchar *str,
811                 glong        len,             
812                 glong       *items_read,      
813                 glong       *items_written,   
814                 GError     **error)
815 {
816   gunichar *result = NULL;
817   gint n_chars, i;
818   const gchar *in;
819   
820   in = str;
821   n_chars = 0;
822   while ((len < 0 || str + len - in > 0) && *in)
823     {
824       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
825       if (wc & 0x80000000)
826         {
827           if (wc == (gunichar)-2)
828             {
829               if (items_read)
830                 break;
831               else
832                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
833                                      _("Partial character sequence at end of input"));
834             }
835           else
836             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
837                                  _("Invalid byte sequence in conversion input"));
838
839           goto err_out;
840         }
841
842       n_chars++;
843
844       in = g_utf8_next_char (in);
845     }
846
847   result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
848   if (result == NULL)
849       goto err_out;
850
851   in = str;
852   for (i=0; i < n_chars; i++)
853     {
854       result[i] = g_utf8_get_char (in);
855       in = g_utf8_next_char (in);
856     }
857   result[i] = 0;
858
859   if (items_written)
860     *items_written = n_chars;
861
862  err_out:
863   if (items_read)
864     *items_read = in - str;
865
866   return result;
867 }
868
869 /**
870  * g_ucs4_to_utf8:
871  * @str: a UCS-4 encoded string
872  * @len: the maximum length (number of characters) of @str to use. 
873  *     If @len < 0, then the string is nul-terminated.
874  * @items_read: (allow-none): location to store number of characters
875  *     read, or %NULL.
876  * @items_written: (allow-none): location to store number of bytes
877  *     written or %NULL. The value here stored does not include the
878  *     trailing 0 byte. 
879  * @error: location to store the error occurring, or %NULL to ignore
880  *         errors. Any of the errors in #GConvertError other than
881  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
882  *
883  * Convert a string from a 32-bit fixed width representation as UCS-4.
884  * to UTF-8. The result will be terminated with a 0 byte.
885  * 
886  * Returns: a pointer to a newly allocated UTF-8 string.
887  *     This value must be freed with g_free(). If an error occurs,
888  *     %NULL will be returned and @error set. In that case, @items_read
889  *     will be set to the position of the first invalid input character.
890  */
891 gchar *
892 g_ucs4_to_utf8 (const gunichar *str,
893                 glong           len,              
894                 glong          *items_read,       
895                 glong          *items_written,    
896                 GError        **error)
897 {
898   gint result_length;
899   gchar *result = NULL;
900   gchar *p;
901   gint i;
902
903   result_length = 0;
904   for (i = 0; len < 0 || i < len ; i++)
905     {
906       if (!str[i])
907         break;
908
909       if (str[i] >= 0x80000000)
910         {
911           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
912                                _("Character out of range for UTF-8"));
913           goto err_out;
914         }
915       
916       result_length += UTF8_LENGTH (str[i]);
917     }
918
919   result = try_malloc_n (result_length + 1, 1, error);
920   if (result == NULL)
921       goto err_out;
922
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 #gunichar2) 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,
949  *     or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
950  *     returned in case @str contains a trailing partial character. If
951  *     an error occurs then the index of the invalid input is stored here.
952  * @items_written: (allow-none): location to store number of bytes written,
953  *     or %NULL. The value stored here does not include the trailing 0 byte.
954  * @error: location to store the error occurring, or %NULL to ignore
955  *     errors. Any of the errors in #GConvertError other than
956  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
957  *
958  * Convert a string from UTF-16 to UTF-8. The result will be
959  * terminated with a 0 byte.
960  *
961  * Note that the input is expected to be already in native endianness,
962  * an initial byte-order-mark character is not handled specially.
963  * g_convert() can be used to convert a byte buffer of UTF-16 data of
964  * ambiguous endianess.
965  *
966  * Further note that this function does not validate the result
967  * string; it may e.g. include embedded NUL characters. The only
968  * validation done by this function is to ensure that the input can
969  * be correctly interpreted as UTF-16, i.e. it doesn't contain
970  * things unpaired surrogates.
971  *
972  * Returns: a pointer to a newly allocated UTF-8 string.
973  *     This value must be freed with g_free(). If an error occurs,
974  *     %NULL will be returned and @error set.
975  **/
976 gchar *
977 g_utf16_to_utf8 (const gunichar2  *str,
978                  glong             len,
979                  glong            *items_read,
980                  glong            *items_written,
981                  GError          **error)
982 {
983   /* This function and g_utf16_to_ucs4 are almost exactly identical -
984    * The lines that differ are marked.
985    */
986   const gunichar2 *in;
987   gchar *out;
988   gchar *result = NULL;
989   gint n_bytes;
990   gunichar high_surrogate;
991
992   g_return_val_if_fail (str != NULL, NULL);
993
994   n_bytes = 0;
995   in = str;
996   high_surrogate = 0;
997   while ((len < 0 || in - str < len) && *in)
998     {
999       gunichar2 c = *in;
1000       gunichar wc;
1001
1002       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1003         {
1004           if (high_surrogate)
1005             {
1006               wc = SURROGATE_VALUE (high_surrogate, c);
1007               high_surrogate = 0;
1008             }
1009           else
1010             {
1011               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1012                                    _("Invalid sequence in conversion input"));
1013               goto err_out;
1014             }
1015         }
1016       else
1017         {
1018           if (high_surrogate)
1019             {
1020               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1021                                    _("Invalid sequence in conversion input"));
1022               goto err_out;
1023             }
1024
1025           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1026             {
1027               high_surrogate = c;
1028               goto next1;
1029             }
1030           else
1031             wc = c;
1032         }
1033
1034       /********** DIFFERENT for UTF8/UCS4 **********/
1035       n_bytes += UTF8_LENGTH (wc);
1036
1037     next1:
1038       in++;
1039     }
1040
1041   if (high_surrogate && !items_read)
1042     {
1043       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1044                            _("Partial character sequence at end of input"));
1045       goto err_out;
1046     }
1047   
1048   /* At this point, everything is valid, and we just need to convert
1049    */
1050   /********** DIFFERENT for UTF8/UCS4 **********/
1051   result = try_malloc_n (n_bytes + 1, 1, error);
1052   if (result == NULL)
1053       goto err_out;
1054
1055   high_surrogate = 0;
1056   out = result;
1057   in = str;
1058   while (out < result + n_bytes)
1059     {
1060       gunichar2 c = *in;
1061       gunichar wc;
1062
1063       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1064         {
1065           wc = SURROGATE_VALUE (high_surrogate, c);
1066           high_surrogate = 0;
1067         }
1068       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1069         {
1070           high_surrogate = c;
1071           goto next2;
1072         }
1073       else
1074         wc = c;
1075
1076       /********** DIFFERENT for UTF8/UCS4 **********/
1077       out += g_unichar_to_utf8 (wc, out);
1078
1079     next2:
1080       in++;
1081     }
1082   
1083   /********** DIFFERENT for UTF8/UCS4 **********/
1084   *out = '\0';
1085
1086   if (items_written)
1087     /********** DIFFERENT for UTF8/UCS4 **********/
1088     *items_written = out - result;
1089
1090  err_out:
1091   if (items_read)
1092     *items_read = in - str;
1093
1094   return result;
1095 }
1096
1097 /**
1098  * g_utf16_to_ucs4:
1099  * @str: a UTF-16 encoded string
1100  * @len: the maximum length (number of #gunichar2) of @str to use. 
1101  *     If @len < 0, then the string is nul-terminated.
1102  * @items_read: (allow-none): location to store number of words read,
1103  *     or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1104  *     returned in case @str contains a trailing partial character. If
1105  *     an error occurs then the index of the invalid input is stored here.
1106  * @items_written: (allow-none): location to store number of characters
1107  *     written, or %NULL. The value stored here does not include the trailing
1108  *     0 character.
1109  * @error: location to store the error occurring, or %NULL to ignore
1110  *     errors. Any of the errors in #GConvertError other than
1111  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1112  *
1113  * Convert a string from UTF-16 to UCS-4. The result will be
1114  * nul-terminated.
1115  * 
1116  * Returns: a pointer to a newly allocated UCS-4 string.
1117  *     This value must be freed with g_free(). If an error occurs,
1118  *     %NULL will be returned and @error set.
1119  */
1120 gunichar *
1121 g_utf16_to_ucs4 (const gunichar2  *str,
1122                  glong             len,              
1123                  glong            *items_read,       
1124                  glong            *items_written,    
1125                  GError          **error)
1126 {
1127   const gunichar2 *in;
1128   gchar *out;
1129   gchar *result = NULL;
1130   gint n_bytes;
1131   gunichar high_surrogate;
1132
1133   g_return_val_if_fail (str != NULL, NULL);
1134
1135   n_bytes = 0;
1136   in = str;
1137   high_surrogate = 0;
1138   while ((len < 0 || in - str < len) && *in)
1139     {
1140       gunichar2 c = *in;
1141
1142       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1143         {
1144           if (high_surrogate)
1145             {
1146               high_surrogate = 0;
1147             }
1148           else
1149             {
1150               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1151                                    _("Invalid sequence in conversion input"));
1152               goto err_out;
1153             }
1154         }
1155       else
1156         {
1157           if (high_surrogate)
1158             {
1159               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1160                                    _("Invalid sequence in conversion input"));
1161               goto err_out;
1162             }
1163
1164           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1165             {
1166               high_surrogate = c;
1167               goto next1;
1168             }
1169         }
1170
1171       /********** DIFFERENT for UTF8/UCS4 **********/
1172       n_bytes += sizeof (gunichar);
1173
1174     next1:
1175       in++;
1176     }
1177
1178   if (high_surrogate && !items_read)
1179     {
1180       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1181                            _("Partial character sequence at end of input"));
1182       goto err_out;
1183     }
1184   
1185   /* At this point, everything is valid, and we just need to convert
1186    */
1187   /********** DIFFERENT for UTF8/UCS4 **********/
1188   result = try_malloc_n (n_bytes + 4, 1, error);
1189   if (result == NULL)
1190       goto err_out;
1191
1192   high_surrogate = 0;
1193   out = result;
1194   in = str;
1195   while (out < result + n_bytes)
1196     {
1197       gunichar2 c = *in;
1198       gunichar wc;
1199
1200       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1201         {
1202           wc = SURROGATE_VALUE (high_surrogate, c);
1203           high_surrogate = 0;
1204         }
1205       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1206         {
1207           high_surrogate = c;
1208           goto next2;
1209         }
1210       else
1211         wc = c;
1212
1213       /********** DIFFERENT for UTF8/UCS4 **********/
1214       *(gunichar *)out = wc;
1215       out += sizeof (gunichar);
1216
1217     next2:
1218       in++;
1219     }
1220
1221   /********** DIFFERENT for UTF8/UCS4 **********/
1222   *(gunichar *)out = 0;
1223
1224   if (items_written)
1225     /********** DIFFERENT for UTF8/UCS4 **********/
1226     *items_written = (out - result) / sizeof (gunichar);
1227
1228  err_out:
1229   if (items_read)
1230     *items_read = in - str;
1231
1232   return (gunichar *)result;
1233 }
1234
1235 /**
1236  * g_utf8_to_utf16:
1237  * @str: a UTF-8 encoded string
1238  * @len: the maximum length (number of bytes) of @str to use.
1239  *     If @len < 0, then the string is nul-terminated.
1240  * @items_read: (allow-none): location to store number of bytes read,
1241  *     or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1242  *     returned in case @str contains a trailing partial character. If
1243  *     an error occurs then the index of the invalid input is stored here.
1244  * @items_written: (allow-none): location to store number of #gunichar2
1245  *     written, or %NULL. The value stored here does not include the
1246  *     trailing 0.
1247  * @error: location to store the error occurring, or %NULL to ignore
1248  *     errors. Any of the errors in #GConvertError other than
1249  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1250  *
1251  * Convert a string from UTF-8 to UTF-16. A 0 character will be
1252  * added to the result after the converted text.
1253  *
1254  * Returns: a pointer to a newly allocated UTF-16 string.
1255  *     This value must be freed with g_free(). If an error occurs,
1256  *     %NULL will be returned and @error set.
1257  */
1258 gunichar2 *
1259 g_utf8_to_utf16 (const gchar *str,
1260                  glong        len,
1261                  glong       *items_read,
1262                  glong       *items_written,
1263                  GError     **error)
1264 {
1265   gunichar2 *result = NULL;
1266   gint n16;
1267   const gchar *in;
1268   gint i;
1269
1270   g_return_val_if_fail (str != NULL, NULL);
1271
1272   in = str;
1273   n16 = 0;
1274   while ((len < 0 || str + len - in > 0) && *in)
1275     {
1276       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1277       if (wc & 0x80000000)
1278         {
1279           if (wc == (gunichar)-2)
1280             {
1281               if (items_read)
1282                 break;
1283               else
1284                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1285                                      _("Partial character sequence at end of input"));
1286             }
1287           else
1288             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1289                                  _("Invalid byte sequence in conversion input"));
1290
1291           goto err_out;
1292         }
1293
1294       if (wc < 0xd800)
1295         n16 += 1;
1296       else if (wc < 0xe000)
1297         {
1298           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1299                                _("Invalid sequence in conversion input"));
1300
1301           goto err_out;
1302         }
1303       else if (wc < 0x10000)
1304         n16 += 1;
1305       else if (wc < 0x110000)
1306         n16 += 2;
1307       else
1308         {
1309           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1310                                _("Character out of range for UTF-16"));
1311
1312           goto err_out;
1313         }
1314       
1315       in = g_utf8_next_char (in);
1316     }
1317
1318   result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1319   if (result == NULL)
1320       goto err_out;
1321
1322   in = str;
1323   for (i = 0; i < n16;)
1324     {
1325       gunichar wc = g_utf8_get_char (in);
1326
1327       if (wc < 0x10000)
1328         {
1329           result[i++] = wc;
1330         }
1331       else
1332         {
1333           result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1334           result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1335         }
1336       
1337       in = g_utf8_next_char (in);
1338     }
1339
1340   result[i] = 0;
1341
1342   if (items_written)
1343     *items_written = n16;
1344
1345  err_out:
1346   if (items_read)
1347     *items_read = in - str;
1348   
1349   return result;
1350 }
1351
1352 /**
1353  * g_ucs4_to_utf16:
1354  * @str: a UCS-4 encoded string
1355  * @len: the maximum length (number of characters) of @str to use. 
1356  *     If @len < 0, then the string is nul-terminated.
1357  * @items_read: (allow-none): location to store number of bytes read,
1358  *     or %NULL. If an error occurs then the index of the invalid input
1359  *     is stored here.
1360  * @items_written: (allow-none): location to store number of #gunichar2 
1361  *     written, or %NULL. The value stored here does not include the
1362  *     trailing 0.
1363  * @error: location to store the error occurring, or %NULL to ignore
1364  *     errors. Any of the errors in #GConvertError other than
1365  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1366  *
1367  * Convert a string from UCS-4 to UTF-16. A 0 character will be
1368  * added to the result after the converted text.
1369  * 
1370  * Returns: a pointer to a newly allocated UTF-16 string.
1371  *     This value must be freed with g_free(). If an error occurs,
1372  *     %NULL will be returned and @error set.
1373  */
1374 gunichar2 *
1375 g_ucs4_to_utf16 (const gunichar  *str,
1376                  glong            len,              
1377                  glong           *items_read,       
1378                  glong           *items_written,    
1379                  GError         **error)
1380 {
1381   gunichar2 *result = NULL;
1382   gint n16;
1383   gint i, j;
1384
1385   n16 = 0;
1386   i = 0;
1387   while ((len < 0 || i < len) && str[i])
1388     {
1389       gunichar wc = str[i];
1390
1391       if (wc < 0xd800)
1392         n16 += 1;
1393       else if (wc < 0xe000)
1394         {
1395           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1396                                _("Invalid sequence in conversion input"));
1397
1398           goto err_out;
1399         }
1400       else if (wc < 0x10000)
1401         n16 += 1;
1402       else if (wc < 0x110000)
1403         n16 += 2;
1404       else
1405         {
1406           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1407                                _("Character out of range for UTF-16"));
1408
1409           goto err_out;
1410         }
1411
1412       i++;
1413     }
1414
1415   result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1416   if (result == NULL)
1417       goto err_out;
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: (array length=max_len) (element-type guint8): a pointer to character data
1599  * @max_len: max bytes to validate, or -1 to go until NUL
1600  * @end: (allow-none) (out) (transfer none): 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 require valid UTF-8 as input; so data read from a file
1615  * or the network should be checked with g_utf8_validate() before
1616  * doing anything else with it.
1617  * 
1618  * Returns: %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  * Returns: %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 }