Imported Upstream version 2.50.2
[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
571   if (wc < 0x80)
572     {
573       return wc;
574     }
575   else if (G_UNLIKELY (wc < 0xc0))
576     {
577       return (gunichar)-1;
578     }
579   else if (wc < 0xe0)
580     {
581       len = 2;
582       wc &= 0x1f;
583       min_code = 1 << 7;
584     }
585   else if (wc < 0xf0)
586     {
587       len = 3;
588       wc &= 0x0f;
589       min_code = 1 << 11;
590     }
591   else if (wc < 0xf8)
592     {
593       len = 4;
594       wc &= 0x07;
595       min_code = 1 << 16;
596     }
597   else if (wc < 0xfc)
598     {
599       len = 5;
600       wc &= 0x03;
601       min_code = 1 << 21;
602     }
603   else if (wc < 0xfe)
604     {
605       len = 6;
606       wc &= 0x01;
607       min_code = 1 << 26;
608     }
609   else
610     {
611       return (gunichar)-1;
612     }
613
614   if (G_UNLIKELY (max_len >= 0 && len > max_len))
615     {
616       for (i = 1; i < max_len; i++)
617         {
618           if ((((guchar *)p)[i] & 0xc0) != 0x80)
619             return (gunichar)-1;
620         }
621       return (gunichar)-2;
622     }
623
624   for (i = 1; i < len; ++i)
625     {
626       gunichar ch = ((guchar *)p)[i];
627
628       if (G_UNLIKELY ((ch & 0xc0) != 0x80))
629         {
630           if (ch)
631             return (gunichar)-1;
632           else
633             return (gunichar)-2;
634         }
635
636       wc <<= 6;
637       wc |= (ch & 0x3f);
638     }
639
640   if (G_UNLIKELY (wc < min_code))
641     return (gunichar)-1;
642
643   return wc;
644 }
645
646 /**
647  * g_utf8_get_char_validated:
648  * @p: a pointer to Unicode character encoded as UTF-8
649  * @max_len: the maximum number of bytes to read, or -1, for no maximum or
650  *     if @p is nul-terminated
651  * 
652  * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
653  * This function checks for incomplete characters, for invalid characters
654  * such as characters that are out of the range of Unicode, and for
655  * overlong encodings of valid characters.
656  * 
657  * Returns: the resulting character. If @p points to a partial
658  *     sequence at the end of a string that could begin a valid 
659  *     character (or if @max_len is zero), returns (gunichar)-2; 
660  *     otherwise, if @p does not point to a valid UTF-8 encoded 
661  *     Unicode character, returns (gunichar)-1.
662  */
663 gunichar
664 g_utf8_get_char_validated (const gchar *p,
665                            gssize       max_len)
666 {
667   gunichar result;
668
669   if (max_len == 0)
670     return (gunichar)-2;
671
672   result = g_utf8_get_char_extended (p, max_len);
673
674   if (result & 0x80000000)
675     return result;
676   else if (!UNICODE_VALID (result))
677     return (gunichar)-1;
678   else
679     return result;
680 }
681
682 #define CONT_BYTE_FAST(p) ((guchar)*p++ & 0x3f)
683
684 /**
685  * g_utf8_to_ucs4_fast:
686  * @str: a UTF-8 encoded string
687  * @len: the maximum length of @str to use, in bytes. If @len < 0,
688  *     then the string is nul-terminated.
689  * @items_written: (out caller-allocates) (optional): location to store the
690  *     number of characters in the result, or %NULL.
691  *
692  * Convert a string from UTF-8 to a 32-bit fixed width
693  * representation as UCS-4, assuming valid UTF-8 input.
694  * This function is roughly twice as fast as g_utf8_to_ucs4()
695  * but does no error checking on the input. A trailing 0 character
696  * will be added to the string after the converted text.
697  * 
698  * Returns: a pointer to a newly allocated UCS-4 string.
699  *     This value must be freed with g_free().
700  */
701 gunichar *
702 g_utf8_to_ucs4_fast (const gchar *str,
703                      glong        len,              
704                      glong       *items_written)    
705 {
706   gunichar *result;
707   gint n_chars, i;
708   const gchar *p;
709
710   g_return_val_if_fail (str != NULL, NULL);
711
712   p = str;
713   n_chars = 0;
714   if (len < 0)
715     {
716       while (*p)
717         {
718           p = g_utf8_next_char (p);
719           ++n_chars;
720         }
721     }
722   else
723     {
724       while (p < str + len && *p)
725         {
726           p = g_utf8_next_char (p);
727           ++n_chars;
728         }
729     }
730   
731   result = g_new (gunichar, n_chars + 1);
732   
733   p = str;
734   for (i=0; i < n_chars; i++)
735     {
736       guchar first = (guchar)*p++;
737       gunichar wc;
738
739       if (first < 0xc0)
740         {
741           /* We really hope first < 0x80, but we don't want to test an
742            * extra branch for invalid input, which this function
743            * does not care about. Handling unexpected continuation bytes
744            * here will do the least damage. */
745           wc = first;
746         }
747       else
748         {
749           gunichar c1 = CONT_BYTE_FAST(p);
750           if (first < 0xe0)
751             {
752               wc = ((first & 0x1f) << 6) | c1;
753             }
754           else
755             {
756               gunichar c2 = CONT_BYTE_FAST(p);
757               if (first < 0xf0)
758                 {
759                   wc = ((first & 0x0f) << 12) | (c1 << 6) | c2;
760                 }
761               else
762                 {
763                   gunichar c3 = CONT_BYTE_FAST(p);
764                   wc = ((first & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
765                   if (G_UNLIKELY (first >= 0xf8))
766                     {
767                       /* This can't be valid UTF-8, but g_utf8_next_char()
768                        * and company allow out-of-range sequences */
769                       gunichar mask = 1 << 20;
770                       while ((wc & mask) != 0)
771                         {
772                           wc <<= 6;
773                           wc |= CONT_BYTE_FAST(p);
774                           mask <<= 5;
775                         }
776                       wc &= mask - 1;
777                     }
778                 }
779             }
780         }
781       result[i] = wc;
782     }
783   result[i] = 0;
784
785   if (items_written)
786     *items_written = i;
787
788   return result;
789 }
790
791 static gpointer
792 try_malloc_n (gsize n_blocks, gsize n_block_bytes, GError **error)
793 {
794     gpointer ptr = g_try_malloc_n (n_blocks, n_block_bytes);
795     if (ptr == NULL)
796       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_MEMORY,
797                            _("Failed to allocate memory"));
798     return ptr;
799 }
800
801 /**
802  * g_utf8_to_ucs4:
803  * @str: a UTF-8 encoded string
804  * @len: the maximum length of @str to use, in bytes. If @len < 0,
805  *     then the string is nul-terminated.
806  * @items_read: (out caller-allocates) (optional): location to store number of
807   *    bytes read, or %NULL.
808  *     If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
809  *     returned in case @str contains a trailing partial
810  *     character. If an error occurs then the index of the
811  *     invalid input is stored here.
812  * @items_written: (out caller-allocates) (optional): location to store number
813  *     of characters written or %NULL. The value here stored does not include
814  *     the trailing 0 character.
815  * @error: location to store the error occurring, or %NULL to ignore
816  *     errors. Any of the errors in #GConvertError other than
817  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
818  *
819  * Convert a string from UTF-8 to a 32-bit fixed width
820  * representation as UCS-4. A trailing 0 character will be added to the
821  * string after the converted text.
822  * 
823  * Returns: a pointer to a newly allocated UCS-4 string.
824  *     This value must be freed with g_free(). If an error occurs,
825  *     %NULL will be returned and @error set.
826  */
827 gunichar *
828 g_utf8_to_ucs4 (const gchar *str,
829                 glong        len,             
830                 glong       *items_read,      
831                 glong       *items_written,   
832                 GError     **error)
833 {
834   gunichar *result = NULL;
835   gint n_chars, i;
836   const gchar *in;
837   
838   in = str;
839   n_chars = 0;
840   while ((len < 0 || str + len - in > 0) && *in)
841     {
842       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
843       if (wc & 0x80000000)
844         {
845           if (wc == (gunichar)-2)
846             {
847               if (items_read)
848                 break;
849               else
850                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
851                                      _("Partial character sequence at end of input"));
852             }
853           else
854             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
855                                  _("Invalid byte sequence in conversion input"));
856
857           goto err_out;
858         }
859
860       n_chars++;
861
862       in = g_utf8_next_char (in);
863     }
864
865   result = try_malloc_n (n_chars + 1, sizeof (gunichar), error);
866   if (result == NULL)
867       goto err_out;
868
869   in = str;
870   for (i=0; i < n_chars; i++)
871     {
872       result[i] = g_utf8_get_char (in);
873       in = g_utf8_next_char (in);
874     }
875   result[i] = 0;
876
877   if (items_written)
878     *items_written = n_chars;
879
880  err_out:
881   if (items_read)
882     *items_read = in - str;
883
884   return result;
885 }
886
887 /**
888  * g_ucs4_to_utf8:
889  * @str: a UCS-4 encoded string
890  * @len: the maximum length (number of characters) of @str to use. 
891  *     If @len < 0, then the string is nul-terminated.
892  * @items_read: (out caller-allocates) (optional): location to store number of
893  *     characters read, or %NULL.
894  * @items_written: (out caller-allocates) (optional): location to store number
895  *     of bytes written or %NULL. The value here stored does not include the
896  *     trailing 0 byte.
897  * @error: location to store the error occurring, or %NULL to ignore
898  *         errors. Any of the errors in #GConvertError other than
899  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
900  *
901  * Convert a string from a 32-bit fixed width representation as UCS-4.
902  * to UTF-8. The result will be terminated with a 0 byte.
903  * 
904  * Returns: a pointer to a newly allocated UTF-8 string.
905  *     This value must be freed with g_free(). If an error occurs,
906  *     %NULL will be returned and @error set. In that case, @items_read
907  *     will be set to the position of the first invalid input character.
908  */
909 gchar *
910 g_ucs4_to_utf8 (const gunichar *str,
911                 glong           len,              
912                 glong          *items_read,       
913                 glong          *items_written,    
914                 GError        **error)
915 {
916   gint result_length;
917   gchar *result = NULL;
918   gchar *p;
919   gint i;
920
921   result_length = 0;
922   for (i = 0; len < 0 || i < len ; i++)
923     {
924       if (!str[i])
925         break;
926
927       if (str[i] >= 0x80000000)
928         {
929           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
930                                _("Character out of range for UTF-8"));
931           goto err_out;
932         }
933       
934       result_length += UTF8_LENGTH (str[i]);
935     }
936
937   result = try_malloc_n (result_length + 1, 1, error);
938   if (result == NULL)
939       goto err_out;
940
941   p = result;
942
943   i = 0;
944   while (p < result + result_length)
945     p += g_unichar_to_utf8 (str[i++], p);
946   
947   *p = '\0';
948
949   if (items_written)
950     *items_written = p - result;
951
952  err_out:
953   if (items_read)
954     *items_read = i;
955
956   return result;
957 }
958
959 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
960
961 /**
962  * g_utf16_to_utf8:
963  * @str: a UTF-16 encoded string
964  * @len: the maximum length (number of #gunichar2) of @str to use. 
965  *     If @len < 0, then the string is nul-terminated.
966  * @items_read: (out caller-allocates) (optional): location to store number of
967  *     words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
968  *     be returned in case @str contains a trailing partial character. If
969  *     an error occurs then the index of the invalid input is stored here.
970  * @items_written: (out caller-allocates) (optional): location to store number
971  *     of bytes written, or %NULL. The value stored here does not include the
972  *     trailing 0 byte.
973  * @error: location to store the error occurring, or %NULL to ignore
974  *     errors. Any of the errors in #GConvertError other than
975  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
976  *
977  * Convert a string from UTF-16 to UTF-8. The result will be
978  * terminated with a 0 byte.
979  *
980  * Note that the input is expected to be already in native endianness,
981  * an initial byte-order-mark character is not handled specially.
982  * g_convert() can be used to convert a byte buffer of UTF-16 data of
983  * ambiguous endianess.
984  *
985  * Further note that this function does not validate the result
986  * string; it may e.g. include embedded NUL characters. The only
987  * validation done by this function is to ensure that the input can
988  * be correctly interpreted as UTF-16, i.e. it doesn't contain
989  * things unpaired surrogates.
990  *
991  * Returns: a pointer to a newly allocated UTF-8 string.
992  *     This value must be freed with g_free(). If an error occurs,
993  *     %NULL will be returned and @error set.
994  **/
995 gchar *
996 g_utf16_to_utf8 (const gunichar2  *str,
997                  glong             len,
998                  glong            *items_read,
999                  glong            *items_written,
1000                  GError          **error)
1001 {
1002   /* This function and g_utf16_to_ucs4 are almost exactly identical -
1003    * The lines that differ are marked.
1004    */
1005   const gunichar2 *in;
1006   gchar *out;
1007   gchar *result = NULL;
1008   gint n_bytes;
1009   gunichar high_surrogate;
1010
1011   g_return_val_if_fail (str != NULL, NULL);
1012
1013   n_bytes = 0;
1014   in = str;
1015   high_surrogate = 0;
1016   while ((len < 0 || in - str < len) && *in)
1017     {
1018       gunichar2 c = *in;
1019       gunichar wc;
1020
1021       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1022         {
1023           if (high_surrogate)
1024             {
1025               wc = SURROGATE_VALUE (high_surrogate, c);
1026               high_surrogate = 0;
1027             }
1028           else
1029             {
1030               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1031                                    _("Invalid sequence in conversion input"));
1032               goto err_out;
1033             }
1034         }
1035       else
1036         {
1037           if (high_surrogate)
1038             {
1039               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1040                                    _("Invalid sequence in conversion input"));
1041               goto err_out;
1042             }
1043
1044           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1045             {
1046               high_surrogate = c;
1047               goto next1;
1048             }
1049           else
1050             wc = c;
1051         }
1052
1053       /********** DIFFERENT for UTF8/UCS4 **********/
1054       n_bytes += UTF8_LENGTH (wc);
1055
1056     next1:
1057       in++;
1058     }
1059
1060   if (high_surrogate && !items_read)
1061     {
1062       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1063                            _("Partial character sequence at end of input"));
1064       goto err_out;
1065     }
1066   
1067   /* At this point, everything is valid, and we just need to convert
1068    */
1069   /********** DIFFERENT for UTF8/UCS4 **********/
1070   result = try_malloc_n (n_bytes + 1, 1, error);
1071   if (result == NULL)
1072       goto err_out;
1073
1074   high_surrogate = 0;
1075   out = result;
1076   in = str;
1077   while (out < result + n_bytes)
1078     {
1079       gunichar2 c = *in;
1080       gunichar wc;
1081
1082       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1083         {
1084           wc = SURROGATE_VALUE (high_surrogate, c);
1085           high_surrogate = 0;
1086         }
1087       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1088         {
1089           high_surrogate = c;
1090           goto next2;
1091         }
1092       else
1093         wc = c;
1094
1095       /********** DIFFERENT for UTF8/UCS4 **********/
1096       out += g_unichar_to_utf8 (wc, out);
1097
1098     next2:
1099       in++;
1100     }
1101   
1102   /********** DIFFERENT for UTF8/UCS4 **********/
1103   *out = '\0';
1104
1105   if (items_written)
1106     /********** DIFFERENT for UTF8/UCS4 **********/
1107     *items_written = out - result;
1108
1109  err_out:
1110   if (items_read)
1111     *items_read = in - str;
1112
1113   return result;
1114 }
1115
1116 /**
1117  * g_utf16_to_ucs4:
1118  * @str: a UTF-16 encoded string
1119  * @len: the maximum length (number of #gunichar2) of @str to use. 
1120  *     If @len < 0, then the string is nul-terminated.
1121  * @items_read: (out caller-allocates) (optional): location to store number of
1122  *     words read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1123  *     be returned in case @str contains a trailing partial character. If
1124  *     an error occurs then the index of the invalid input is stored here.
1125  * @items_written: (out caller-allocates) (optional): location to store number
1126  *     of characters written, or %NULL. The value stored here does not include
1127  *     the trailing 0 character.
1128  * @error: location to store the error occurring, or %NULL to ignore
1129  *     errors. Any of the errors in #GConvertError other than
1130  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1131  *
1132  * Convert a string from UTF-16 to UCS-4. The result will be
1133  * nul-terminated.
1134  * 
1135  * Returns: a pointer to a newly allocated UCS-4 string.
1136  *     This value must be freed with g_free(). If an error occurs,
1137  *     %NULL will be returned and @error set.
1138  */
1139 gunichar *
1140 g_utf16_to_ucs4 (const gunichar2  *str,
1141                  glong             len,              
1142                  glong            *items_read,       
1143                  glong            *items_written,    
1144                  GError          **error)
1145 {
1146   const gunichar2 *in;
1147   gchar *out;
1148   gchar *result = NULL;
1149   gint n_bytes;
1150   gunichar high_surrogate;
1151
1152   g_return_val_if_fail (str != NULL, NULL);
1153
1154   n_bytes = 0;
1155   in = str;
1156   high_surrogate = 0;
1157   while ((len < 0 || in - str < len) && *in)
1158     {
1159       gunichar2 c = *in;
1160
1161       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1162         {
1163           if (high_surrogate)
1164             {
1165               high_surrogate = 0;
1166             }
1167           else
1168             {
1169               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1170                                    _("Invalid sequence in conversion input"));
1171               goto err_out;
1172             }
1173         }
1174       else
1175         {
1176           if (high_surrogate)
1177             {
1178               g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1179                                    _("Invalid sequence in conversion input"));
1180               goto err_out;
1181             }
1182
1183           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1184             {
1185               high_surrogate = c;
1186               goto next1;
1187             }
1188         }
1189
1190       /********** DIFFERENT for UTF8/UCS4 **********/
1191       n_bytes += sizeof (gunichar);
1192
1193     next1:
1194       in++;
1195     }
1196
1197   if (high_surrogate && !items_read)
1198     {
1199       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1200                            _("Partial character sequence at end of input"));
1201       goto err_out;
1202     }
1203   
1204   /* At this point, everything is valid, and we just need to convert
1205    */
1206   /********** DIFFERENT for UTF8/UCS4 **********/
1207   result = try_malloc_n (n_bytes + 4, 1, error);
1208   if (result == NULL)
1209       goto err_out;
1210
1211   high_surrogate = 0;
1212   out = result;
1213   in = str;
1214   while (out < result + n_bytes)
1215     {
1216       gunichar2 c = *in;
1217       gunichar wc;
1218
1219       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1220         {
1221           wc = SURROGATE_VALUE (high_surrogate, c);
1222           high_surrogate = 0;
1223         }
1224       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1225         {
1226           high_surrogate = c;
1227           goto next2;
1228         }
1229       else
1230         wc = c;
1231
1232       /********** DIFFERENT for UTF8/UCS4 **********/
1233       *(gunichar *)out = wc;
1234       out += sizeof (gunichar);
1235
1236     next2:
1237       in++;
1238     }
1239
1240   /********** DIFFERENT for UTF8/UCS4 **********/
1241   *(gunichar *)out = 0;
1242
1243   if (items_written)
1244     /********** DIFFERENT for UTF8/UCS4 **********/
1245     *items_written = (out - result) / sizeof (gunichar);
1246
1247  err_out:
1248   if (items_read)
1249     *items_read = in - str;
1250
1251   return (gunichar *)result;
1252 }
1253
1254 /**
1255  * g_utf8_to_utf16:
1256  * @str: a UTF-8 encoded string
1257  * @len: the maximum length (number of bytes) of @str to use.
1258  *     If @len < 0, then the string is nul-terminated.
1259  * @items_read: (out caller-allocates) (optional): location to store number of
1260  *     bytes read, or %NULL. If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will
1261  *     be returned in case @str contains a trailing partial character. If
1262  *     an error occurs then the index of the invalid input is stored here.
1263  * @items_written: (out caller-allocates) (optional): location to store number
1264  *     of #gunichar2 written, or %NULL. The value stored here does not include
1265  *     the trailing 0.
1266  * @error: location to store the error occurring, or %NULL to ignore
1267  *     errors. Any of the errors in #GConvertError other than
1268  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1269  *
1270  * Convert a string from UTF-8 to UTF-16. A 0 character will be
1271  * added to the result after the converted text.
1272  *
1273  * Returns: a pointer to a newly allocated UTF-16 string.
1274  *     This value must be freed with g_free(). If an error occurs,
1275  *     %NULL will be returned and @error set.
1276  */
1277 gunichar2 *
1278 g_utf8_to_utf16 (const gchar *str,
1279                  glong        len,
1280                  glong       *items_read,
1281                  glong       *items_written,
1282                  GError     **error)
1283 {
1284   gunichar2 *result = NULL;
1285   gint n16;
1286   const gchar *in;
1287   gint i;
1288
1289   g_return_val_if_fail (str != NULL, NULL);
1290
1291   in = str;
1292   n16 = 0;
1293   while ((len < 0 || str + len - in > 0) && *in)
1294     {
1295       gunichar wc = g_utf8_get_char_extended (in, len < 0 ? 6 : str + len - in);
1296       if (wc & 0x80000000)
1297         {
1298           if (wc == (gunichar)-2)
1299             {
1300               if (items_read)
1301                 break;
1302               else
1303                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1304                                      _("Partial character sequence at end of input"));
1305             }
1306           else
1307             g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1308                                  _("Invalid byte sequence in conversion input"));
1309
1310           goto err_out;
1311         }
1312
1313       if (wc < 0xd800)
1314         n16 += 1;
1315       else if (wc < 0xe000)
1316         {
1317           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1318                                _("Invalid sequence in conversion input"));
1319
1320           goto err_out;
1321         }
1322       else if (wc < 0x10000)
1323         n16 += 1;
1324       else if (wc < 0x110000)
1325         n16 += 2;
1326       else
1327         {
1328           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1329                                _("Character out of range for UTF-16"));
1330
1331           goto err_out;
1332         }
1333       
1334       in = g_utf8_next_char (in);
1335     }
1336
1337   result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1338   if (result == NULL)
1339       goto err_out;
1340
1341   in = str;
1342   for (i = 0; i < n16;)
1343     {
1344       gunichar wc = g_utf8_get_char (in);
1345
1346       if (wc < 0x10000)
1347         {
1348           result[i++] = wc;
1349         }
1350       else
1351         {
1352           result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1353           result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1354         }
1355       
1356       in = g_utf8_next_char (in);
1357     }
1358
1359   result[i] = 0;
1360
1361   if (items_written)
1362     *items_written = n16;
1363
1364  err_out:
1365   if (items_read)
1366     *items_read = in - str;
1367   
1368   return result;
1369 }
1370
1371 /**
1372  * g_ucs4_to_utf16:
1373  * @str: a UCS-4 encoded string
1374  * @len: the maximum length (number of characters) of @str to use. 
1375  *     If @len < 0, then the string is nul-terminated.
1376  * @items_read: (out caller-allocates) (optional): location to store number of
1377  *     bytes read, or %NULL. If an error occurs then the index of the invalid
1378  *     input is stored here.
1379  * @items_written: (out caller-allocates) (optional): location to store number
1380  *     of #gunichar2  written, or %NULL. The value stored here does not include
1381  *     the trailing 0.
1382  * @error: location to store the error occurring, or %NULL to ignore
1383  *     errors. Any of the errors in #GConvertError other than
1384  *     %G_CONVERT_ERROR_NO_CONVERSION may occur.
1385  *
1386  * Convert a string from UCS-4 to UTF-16. A 0 character will be
1387  * added to the result after the converted text.
1388  * 
1389  * Returns: a pointer to a newly allocated UTF-16 string.
1390  *     This value must be freed with g_free(). If an error occurs,
1391  *     %NULL will be returned and @error set.
1392  */
1393 gunichar2 *
1394 g_ucs4_to_utf16 (const gunichar  *str,
1395                  glong            len,              
1396                  glong           *items_read,       
1397                  glong           *items_written,    
1398                  GError         **error)
1399 {
1400   gunichar2 *result = NULL;
1401   gint n16;
1402   gint i, j;
1403
1404   n16 = 0;
1405   i = 0;
1406   while ((len < 0 || i < len) && str[i])
1407     {
1408       gunichar wc = str[i];
1409
1410       if (wc < 0xd800)
1411         n16 += 1;
1412       else if (wc < 0xe000)
1413         {
1414           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1415                                _("Invalid sequence in conversion input"));
1416
1417           goto err_out;
1418         }
1419       else if (wc < 0x10000)
1420         n16 += 1;
1421       else if (wc < 0x110000)
1422         n16 += 2;
1423       else
1424         {
1425           g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1426                                _("Character out of range for UTF-16"));
1427
1428           goto err_out;
1429         }
1430
1431       i++;
1432     }
1433
1434   result = try_malloc_n (n16 + 1, sizeof (gunichar2), error);
1435   if (result == NULL)
1436       goto err_out;
1437
1438   for (i = 0, j = 0; j < n16; i++)
1439     {
1440       gunichar wc = str[i];
1441
1442       if (wc < 0x10000)
1443         {
1444           result[j++] = wc;
1445         }
1446       else
1447         {
1448           result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1449           result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1450         }
1451     }
1452   result[j] = 0;
1453
1454   if (items_written)
1455     *items_written = n16;
1456   
1457  err_out:
1458   if (items_read)
1459     *items_read = i;
1460   
1461   return result;
1462 }
1463
1464 #define VALIDATE_BYTE(mask, expect)                      \
1465   G_STMT_START {                                         \
1466     if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect))) \
1467       goto error;                                        \
1468   } G_STMT_END
1469
1470 /* see IETF RFC 3629 Section 4 */
1471
1472 static const gchar *
1473 fast_validate (const char *str)
1474
1475 {
1476   const gchar *p;
1477
1478   for (p = str; *p; p++)
1479     {
1480       if (*(guchar *)p < 128)
1481         /* done */;
1482       else 
1483         {
1484           const gchar *last;
1485
1486           last = p;
1487           if (*(guchar *)p < 0xe0) /* 110xxxxx */
1488             {
1489               if (G_UNLIKELY (*(guchar *)p < 0xc2))
1490                 goto error;
1491             }
1492           else
1493             {
1494               if (*(guchar *)p < 0xf0) /* 1110xxxx */
1495                 {
1496                   switch (*(guchar *)p++ & 0x0f)
1497                     {
1498                     case 0:
1499                       VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1500                       break;
1501                     case 0x0d:
1502                       VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1503                       break;
1504                     default:
1505                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1506                     }
1507                 }
1508               else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1509                 {
1510                   switch (*(guchar *)p++ & 0x07)
1511                     {
1512                     case 0:
1513                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1514                       if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1515                         goto error;
1516                       break;
1517                     case 4:
1518                       VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1519                       break;
1520                     default:
1521                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1522                     }
1523                   p++;
1524                   VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1525                 }
1526               else
1527                 goto error;
1528             }
1529
1530           p++;
1531           VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1532
1533           continue;
1534
1535         error:
1536           return last;
1537         }
1538     }
1539
1540   return p;
1541 }
1542
1543 static const gchar *
1544 fast_validate_len (const char *str,
1545                    gssize      max_len)
1546
1547 {
1548   const gchar *p;
1549
1550   g_assert (max_len >= 0);
1551
1552   for (p = str; ((p - str) < max_len) && *p; p++)
1553     {
1554       if (*(guchar *)p < 128)
1555         /* done */;
1556       else 
1557         {
1558           const gchar *last;
1559
1560           last = p;
1561           if (*(guchar *)p < 0xe0) /* 110xxxxx */
1562             {
1563               if (G_UNLIKELY (max_len - (p - str) < 2))
1564                 goto error;
1565               
1566               if (G_UNLIKELY (*(guchar *)p < 0xc2))
1567                 goto error;
1568             }
1569           else
1570             {
1571               if (*(guchar *)p < 0xf0) /* 1110xxxx */
1572                 {
1573                   if (G_UNLIKELY (max_len - (p - str) < 3))
1574                     goto error;
1575
1576                   switch (*(guchar *)p++ & 0x0f)
1577                     {
1578                     case 0:
1579                       VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
1580                       break;
1581                     case 0x0d:
1582                       VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
1583                       break;
1584                     default:
1585                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1586                     }
1587                 }
1588               else if (*(guchar *)p < 0xf5) /* 11110xxx excluding out-of-range */
1589                 {
1590                   if (G_UNLIKELY (max_len - (p - str) < 4))
1591                     goto error;
1592
1593                   switch (*(guchar *)p++ & 0x07)
1594                     {
1595                     case 0:
1596                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1597                       if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
1598                         goto error;
1599                       break;
1600                     case 4:
1601                       VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
1602                       break;
1603                     default:
1604                       VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1605                     }
1606                   p++;
1607                   VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1608                 }
1609               else
1610                 goto error;
1611             }
1612
1613           p++;
1614           VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
1615
1616           continue;
1617
1618         error:
1619           return last;
1620         }
1621     }
1622
1623   return p;
1624 }
1625
1626 /**
1627  * g_utf8_validate:
1628  * @str: (array length=max_len) (element-type guint8): a pointer to character data
1629  * @max_len: max bytes to validate, or -1 to go until NUL
1630  * @end: (allow-none) (out) (transfer none): return location for end of valid data
1631  * 
1632  * Validates UTF-8 encoded text. @str is the text to validate;
1633  * if @str is nul-terminated, then @max_len can be -1, otherwise
1634  * @max_len should be the number of bytes to validate.
1635  * If @end is non-%NULL, then the end of the valid range
1636  * will be stored there (i.e. the start of the first invalid 
1637  * character if some bytes were invalid, or the end of the text 
1638  * being validated otherwise).
1639  *
1640  * Note that g_utf8_validate() returns %FALSE if @max_len is 
1641  * positive and any of the @max_len bytes are nul.
1642  *
1643  * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1644  * routines require valid UTF-8 as input; so data read from a file
1645  * or the network should be checked with g_utf8_validate() before
1646  * doing anything else with it.
1647  * 
1648  * Returns: %TRUE if the text was valid UTF-8
1649  */
1650 gboolean
1651 g_utf8_validate (const char   *str,
1652                  gssize        max_len,    
1653                  const gchar **end)
1654
1655 {
1656   const gchar *p;
1657
1658   if (max_len < 0)
1659     p = fast_validate (str);
1660   else
1661     p = fast_validate_len (str, max_len);
1662
1663   if (end)
1664     *end = p;
1665
1666   if ((max_len >= 0 && p != str + max_len) ||
1667       (max_len < 0 && *p != '\0'))
1668     return FALSE;
1669   else
1670     return TRUE;
1671 }
1672
1673 /**
1674  * g_unichar_validate:
1675  * @ch: a Unicode character
1676  * 
1677  * Checks whether @ch is a valid Unicode character. Some possible
1678  * integer values of @ch will not be valid. 0 is considered a valid
1679  * character, though it's normally a string terminator.
1680  * 
1681  * Returns: %TRUE if @ch is a valid Unicode character
1682  **/
1683 gboolean
1684 g_unichar_validate (gunichar ch)
1685 {
1686   return UNICODE_VALID (ch);
1687 }
1688
1689 /**
1690  * g_utf8_strreverse:
1691  * @str: a UTF-8 encoded string
1692  * @len: the maximum length of @str to use, in bytes. If @len < 0,
1693  *     then the string is nul-terminated.
1694  *
1695  * Reverses a UTF-8 string. @str must be valid UTF-8 encoded text. 
1696  * (Use g_utf8_validate() on all text before trying to use UTF-8 
1697  * utility functions with it.)
1698  *
1699  * This function is intended for programmatic uses of reversed strings.
1700  * It pays no attention to decomposed characters, combining marks, byte 
1701  * order marks, directional indicators (LRM, LRO, etc) and similar 
1702  * characters which might need special handling when reversing a string 
1703  * for display purposes.
1704  *
1705  * Note that unlike g_strreverse(), this function returns
1706  * newly-allocated memory, which should be freed with g_free() when
1707  * no longer needed. 
1708  *
1709  * Returns: a newly-allocated string which is the reverse of @str
1710  *
1711  * Since: 2.2
1712  */
1713 gchar *
1714 g_utf8_strreverse (const gchar *str,
1715                    gssize       len)
1716 {
1717   gchar *r, *result;
1718   const gchar *p;
1719
1720   if (len < 0)
1721     len = strlen (str);
1722
1723   result = g_new (gchar, len + 1);
1724   r = result + len;
1725   p = str;
1726   while (r > result)
1727     {
1728       gchar *m, skip = g_utf8_skip[*(guchar*) p];
1729       r -= skip;
1730       for (m = r; skip; skip--)
1731         *m++ = *p++;
1732     }
1733   result[len] = 0;
1734
1735   return result;
1736 }
1737
1738
1739 gchar *
1740 _g_utf8_make_valid (const gchar *name)
1741 {
1742   GString *string;
1743   const gchar *remainder, *invalid;
1744   gint remaining_bytes, valid_bytes;
1745
1746   g_return_val_if_fail (name != NULL, NULL);
1747
1748   string = NULL;
1749   remainder = name;
1750   remaining_bytes = strlen (name);
1751
1752   while (remaining_bytes != 0) 
1753     {
1754       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1755         break;
1756       valid_bytes = invalid - remainder;
1757     
1758       if (string == NULL) 
1759         string = g_string_sized_new (remaining_bytes);
1760
1761       g_string_append_len (string, remainder, valid_bytes);
1762       /* append U+FFFD REPLACEMENT CHARACTER */
1763       g_string_append (string, "\357\277\275");
1764       
1765       remaining_bytes -= valid_bytes + 1;
1766       remainder = invalid + 1;
1767     }
1768   
1769   if (string == NULL)
1770     return g_strdup (name);
1771   
1772   g_string_append (string, remainder);
1773
1774   g_assert (g_utf8_validate (string->str, -1, NULL));
1775   
1776   return g_string_free (string, FALSE);
1777 }