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