glib/gutf8.c, glib/gunibreak.c, glib/gunicollate.c,
[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, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include <config.h>
23
24 #include <stdlib.h>
25 #ifdef HAVE_CODESET
26 #include <langinfo.h>
27 #endif
28 #include <string.h>
29
30 #include "glib.h"
31
32 #ifdef G_PLATFORM_WIN32
33 #include <stdio.h>
34 #define STRICT
35 #include <windows.h>
36 #undef STRICT
37 #endif
38
39 #include "glibintl.h"
40
41 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
42   if (Char < 128)                                                             \
43     {                                                                         \
44       Len = 1;                                                                \
45       Mask = 0x7f;                                                            \
46     }                                                                         \
47   else if ((Char & 0xe0) == 0xc0)                                             \
48     {                                                                         \
49       Len = 2;                                                                \
50       Mask = 0x1f;                                                            \
51     }                                                                         \
52   else if ((Char & 0xf0) == 0xe0)                                             \
53     {                                                                         \
54       Len = 3;                                                                \
55       Mask = 0x0f;                                                            \
56     }                                                                         \
57   else if ((Char & 0xf8) == 0xf0)                                             \
58     {                                                                         \
59       Len = 4;                                                                \
60       Mask = 0x07;                                                            \
61     }                                                                         \
62   else if ((Char & 0xfc) == 0xf8)                                             \
63     {                                                                         \
64       Len = 5;                                                                \
65       Mask = 0x03;                                                            \
66     }                                                                         \
67   else if ((Char & 0xfe) == 0xfc)                                             \
68     {                                                                         \
69       Len = 6;                                                                \
70       Mask = 0x01;                                                            \
71     }                                                                         \
72   else                                                                        \
73     Len = -1;
74
75 #define UTF8_LENGTH(Char)              \
76   ((Char) < 0x80 ? 1 :                 \
77    ((Char) < 0x800 ? 2 :               \
78     ((Char) < 0x10000 ? 3 :            \
79      ((Char) < 0x200000 ? 4 :          \
80       ((Char) < 0x4000000 ? 5 : 6)))))
81    
82
83 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
84   (Result) = (Chars)[0] & (Mask);                                             \
85   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
86     {                                                                         \
87       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
88         {                                                                     \
89           (Result) = -1;                                                      \
90           break;                                                              \
91         }                                                                     \
92       (Result) <<= 6;                                                         \
93       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
94     }
95
96 #define UNICODE_VALID(Char)                   \
97     ((Char) < 0x110000 &&                     \
98      ((Char) < 0xD800 || (Char) >= 0xE000) && \
99      (Char) != 0xFFFE && (Char) != 0xFFFF)
100    
101      
102 static const gchar utf8_skip_data[256] = {
103   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,
104   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,
105   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,
106   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,
107   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,
108   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,
109   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,
110   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,0,0
111 };
112
113 const gchar * const g_utf8_skip = utf8_skip_data;
114
115 /**
116  * g_utf8_find_prev_char:
117  * @str: pointer to the beginning of a UTF-8 encoded string
118  * @p: pointer to some position within @str
119  * 
120  * Given a position @p with a UTF-8 encoded string @str, find the start
121  * of the previous UTF-8 character starting before @p. Returns %NULL if no
122  * UTF-8 characters are present in @p before @str.
123  *
124  * @p does not have to be at the beginning of a UTF-8 character. No check
125  * is made to see if the character found is actually valid other than
126  * it starts with an appropriate byte.
127  *
128  * Return value: a pointer to the found character or %NULL.
129  **/
130 gchar *
131 g_utf8_find_prev_char (const char *str,
132                        const char *p)
133 {
134   for (--p; p >= str; --p)
135     {
136       if ((*p & 0xc0) != 0x80)
137         return (gchar *)p;
138     }
139   return NULL;
140 }
141
142 /**
143  * g_utf8_find_next_char:
144  * @p: a pointer to a position within a UTF-8 encoded string
145  * @end: a pointer to the end of the string, or %NULL to indicate
146  *        that the string is nul-terminated, in which case
147  *        the returned value will be 
148  *
149  * Finds the start of the next UTF-8 character in the string after @p.
150  *
151  * @p does not have to be at the beginning of a UTF-8 character. No check
152  * is made to see if the character found is actually valid other than
153  * it starts with an appropriate byte.
154  * 
155  * Return value: a pointer to the found character or %NULL
156  **/
157 gchar *
158 g_utf8_find_next_char (const gchar *p,
159                        const gchar *end)
160 {
161   if (*p)
162     {
163       if (end)
164         for (++p; p < end && (*p & 0xc0) == 0x80; ++p)
165           ;
166       else
167         for (++p; (*p & 0xc0) == 0x80; ++p)
168           ;
169     }
170   return (p == end) ? NULL : (gchar *)p;
171 }
172
173 /**
174  * g_utf8_prev_char:
175  * @p: a pointer to a position within a UTF-8 encoded string
176  *
177  * Finds the previous UTF-8 character in the string before @p.
178  *
179  * @p does not have to be at the beginning of a UTF-8 character. No check
180  * is made to see if the character found is actually valid other than
181  * it starts with an appropriate byte. If @p might be the first
182  * character of the string, you must use g_utf8_find_prev_char() instead.
183  * 
184  * Return value: a pointer to the found character.
185  **/
186 gchar *
187 g_utf8_prev_char (const gchar *p)
188 {
189   while (TRUE)
190     {
191       p--;
192       if ((*p & 0xc0) != 0x80)
193         return (gchar *)p;
194     }
195 }
196
197 /**
198  * g_utf8_strlen:
199  * @p: pointer to the start of a UTF-8 encoded string.
200  * @max: the maximum number of bytes to examine. If @max
201  *       is less than 0, then the string is assumed to be
202  *       nul-terminated.
203  * 
204  * Returns the length of the string in characters.
205  *
206  * Return value: the length of the string in characters
207  **/
208 glong
209 g_utf8_strlen (const gchar *p,
210                gssize       max)
211 {
212   glong len = 0;
213   const gchar *start = p;
214
215   if (max < 0)
216     {
217       while (*p)
218         {
219           p = g_utf8_next_char (p);
220           ++len;
221         }
222     }
223   else
224     {
225       if (max == 0 || !*p)
226         return 0;
227       
228       p = g_utf8_next_char (p);          
229
230       while (p - start < max && *p)
231         {
232           ++len;
233           p = g_utf8_next_char (p);          
234         }
235
236       /* only do the last len increment if we got a complete
237        * char (don't count partial chars)
238        */
239       if (p - start == max)
240         ++len;
241     }
242
243   return len;
244 }
245
246 /**
247  * g_utf8_get_char:
248  * @p: a pointer to Unicode character encoded as UTF-8
249  * 
250  * Converts a sequence of bytes encoded as UTF-8 to a Unicode character.
251  * If @p does not point to a valid UTF-8 encoded character, results are
252  * undefined. If you are not sure that the bytes are complete
253  * valid Unicode characters, you should use g_utf8_get_char_validated()
254  * instead.
255  * 
256  * Return value: the resulting character
257  **/
258 gunichar
259 g_utf8_get_char (const gchar *p)
260 {
261   int i, mask = 0, len;
262   gunichar result;
263   unsigned char c = (unsigned char) *p;
264
265   UTF8_COMPUTE (c, mask, len);
266   if (len == -1)
267     return (gunichar)-1;
268   UTF8_GET (result, p, i, mask, len);
269
270   return result;
271 }
272
273 /**
274  * g_utf8_offset_to_pointer:
275  * @str: a UTF-8 encoded string
276  * @offset: a character offset within @str
277  * 
278  * Converts from an integer character offset to a pointer to a position
279  * within the string.
280  * 
281  * Return value: the resulting pointer
282  **/
283 gchar *
284 g_utf8_offset_to_pointer  (const gchar *str,
285                            glong        offset)    
286 {
287   const gchar *s = str;
288   while (offset--)
289     s = g_utf8_next_char (s);
290   
291   return (gchar *)s;
292 }
293
294 /**
295  * g_utf8_pointer_to_offset:
296  * @str: a UTF-8 encoded string
297  * @pos: a pointer to a position within @str
298  * 
299  * Converts from a pointer to position within a string to a integer
300  * character offset.
301  * 
302  * Return value: the resulting character offset
303  **/
304 glong    
305 g_utf8_pointer_to_offset (const gchar *str,
306                           const gchar *pos)
307 {
308   const gchar *s = str;
309   glong offset = 0;    
310   
311   while (s < pos)
312     {
313       s = g_utf8_next_char (s);
314       offset++;
315     }
316
317   return offset;
318 }
319
320
321 /**
322  * g_utf8_strncpy:
323  * @dest: buffer to fill with characters from @src
324  * @src: UTF-8 encoded string
325  * @n: character count
326  * 
327  * Like the standard C <function>strncpy()</function> function, but 
328  * copies a given number of characters instead of a given number of 
329  * bytes. The @src string must be valid UTF-8 encoded text. 
330  * (Use g_utf8_validate() on all text before trying to use UTF-8 
331  * utility functions with it.)
332  * 
333  * Return value: @dest
334  **/
335 gchar *
336 g_utf8_strncpy (gchar       *dest,
337                 const gchar *src,
338                 gsize        n)
339 {
340   const gchar *s = src;
341   while (n && *s)
342     {
343       s = g_utf8_next_char(s);
344       n--;
345     }
346   strncpy(dest, src, s - src);
347   dest[s - src] = 0;
348   return dest;
349 }
350
351 static gboolean
352 g_utf8_get_charset_internal (char **a)
353 {
354   char *charset = getenv("CHARSET");
355
356   if (charset && a && ! *a)
357     *a = charset;
358
359   if (charset && strstr (charset, "UTF-8"))
360       return TRUE;
361
362 #ifdef HAVE_CODESET
363   charset = nl_langinfo(CODESET);
364   if (charset)
365     {
366       if (a && ! *a)
367         *a = charset;
368       if (strcmp (charset, "UTF-8") == 0)
369         return TRUE;
370     }
371 #endif
372   
373 #if 0 /* #ifdef _NL_CTYPE_CODESET_NAME */
374   charset = nl_langinfo (_NL_CTYPE_CODESET_NAME);
375   if (charset)
376     {
377       if (a && ! *a)
378         *a = charset;
379       if (strcmp (charset, "UTF-8") == 0)
380         return TRUE;
381     }
382 #endif
383
384 #ifdef G_PLATFORM_WIN32
385   if (a && ! *a)
386     {
387       static char codepage[10];
388       
389       sprintf (codepage, "CP%d", GetACP ());
390       *a = codepage;
391       /* What about codepage 1200? Is that UTF-8? */
392       return FALSE;
393     }
394 #else
395   if (a && ! *a) 
396     *a = "US-ASCII";
397 #endif
398
399   /* Assume this for compatibility at present.  */
400   return FALSE;
401 }
402
403 static int utf8_locale_cache = -1;
404 static char *utf8_charset_cache = NULL;
405
406 /**
407  * g_get_charset:
408  * @charset: return location for character set name
409  * 
410  * Obtains the character set for the current locale; you might use
411  * this character set as an argument to g_convert(), to convert from
412  * the current locale's encoding to some other encoding. (Frequently
413  * g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts,
414  * though.)
415  *
416  * The return value is %TRUE if the locale's encoding is UTF-8, in that
417  * case you can perhaps avoid calling g_convert().
418  *
419  * The string returned in @charset is not allocated, and should not be
420  * freed.
421  * 
422  * Return value: %TRUE if the returned charset is UTF-8
423  **/
424 gboolean
425 g_get_charset (G_CONST_RETURN char **charset) 
426 {
427   if (utf8_locale_cache != -1)
428     {
429       if (charset)
430         *charset = utf8_charset_cache;
431       return utf8_locale_cache;
432     }
433   utf8_locale_cache = g_utf8_get_charset_internal (&utf8_charset_cache);
434   if (charset) 
435     *charset = utf8_charset_cache;
436   return utf8_locale_cache;
437 }
438
439 /* unicode_strchr */
440
441 /**
442  * g_unichar_to_utf8:
443  * @c: a ISO10646 character code
444  * @outbuf: output buffer, must have at least 6 bytes of space.
445  *       If %NULL, the length will be computed and returned
446  *       and nothing will be written to @outbuf.
447  * 
448  * Converts a single character to UTF-8.
449  * 
450  * Return value: number of bytes written
451  **/
452 int
453 g_unichar_to_utf8 (gunichar c,
454                    gchar   *outbuf)
455 {
456   guint len = 0;    
457   int first;
458   int i;
459
460   if (c < 0x80)
461     {
462       first = 0;
463       len = 1;
464     }
465   else if (c < 0x800)
466     {
467       first = 0xc0;
468       len = 2;
469     }
470   else if (c < 0x10000)
471     {
472       first = 0xe0;
473       len = 3;
474     }
475    else if (c < 0x200000)
476     {
477       first = 0xf0;
478       len = 4;
479     }
480   else if (c < 0x4000000)
481     {
482       first = 0xf8;
483       len = 5;
484     }
485   else
486     {
487       first = 0xfc;
488       len = 6;
489     }
490
491   if (outbuf)
492     {
493       for (i = len - 1; i > 0; --i)
494         {
495           outbuf[i] = (c & 0x3f) | 0x80;
496           c >>= 6;
497         }
498       outbuf[0] = c | first;
499     }
500
501   return len;
502 }
503
504 /**
505  * g_utf8_strchr:
506  * @p: a nul-terminated UTF-8 encoded string
507  * @len: the maximum length of @p
508  * @c: a ISO10646 character
509  * 
510  * Finds the leftmost occurrence of the given ISO10646 character
511  * in a UTF-8 encoded string, while limiting the search to @len bytes.
512  * If @len is -1, allow unbounded search.
513  * 
514  * Return value: %NULL if the string does not contain the character, 
515  *   otherwise, a pointer to the start of the leftmost occurrence of 
516  *   the character in the string.
517  **/
518 gchar *
519 g_utf8_strchr (const char *p,
520                gssize      len,
521                gunichar    c)
522 {
523   gchar ch[10];
524
525   gint charlen = g_unichar_to_utf8 (c, ch);
526   ch[charlen] = '\0';
527   
528   return g_strstr_len (p, len, ch);
529 }
530
531
532 /**
533  * g_utf8_strrchr:
534  * @p: a nul-terminated UTF-8 encoded string
535  * @len: the maximum length of @p
536  * @c: a ISO10646 character
537  * 
538  * Find the rightmost occurrence of the given ISO10646 character
539  * in a UTF-8 encoded string, while limiting the search to @len bytes.
540  * If @len is -1, allow unbounded search.
541  * 
542  * Return value: %NULL if the string does not contain the character, 
543  *   otherwise, a pointer to the start of the rightmost occurrence of the 
544  *   character in the string.
545  **/
546 gchar *
547 g_utf8_strrchr (const char *p,
548                 gssize      len,
549                 gunichar    c)
550 {
551   gchar ch[10];
552
553   gint charlen = g_unichar_to_utf8 (c, ch);
554   ch[charlen] = '\0';
555   
556   return g_strrstr_len (p, len, ch);
557 }
558
559
560 /* Like g_utf8_get_char, but take a maximum length
561  * and return (gunichar)-2 on incomplete trailing character
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 wc = (guchar) *p;
569
570   if (wc < 0x80)
571     {
572       return wc;
573     }
574   else if (wc < 0xc0)
575     {
576       return (gunichar)-1;
577     }
578   else if (wc < 0xe0)
579     {
580       len = 2;
581       wc &= 0x1f;
582     }
583   else if (wc < 0xf0)
584     {
585       len = 3;
586       wc &= 0x0f;
587     }
588   else if (wc < 0xf8)
589     {
590       len = 4;
591       wc &= 0x07;
592     }
593   else if (wc < 0xfc)
594     {
595       len = 5;
596       wc &= 0x03;
597     }
598   else if (wc < 0xfe)
599     {
600       len = 6;
601       wc &= 0x01;
602     }
603   else
604     {
605       return (gunichar)-1;
606     }
607   
608   if (max_len >= 0 && len > max_len)
609     {
610       for (i = 1; i < max_len; i++)
611         {
612           if ((((guchar *)p)[i] & 0xc0) != 0x80)
613             return (gunichar)-1;
614         }
615       return (gunichar)-2;
616     }
617
618   for (i = 1; i < len; ++i)
619     {
620       gunichar ch = ((guchar *)p)[i];
621       
622       if ((ch & 0xc0) != 0x80)
623         {
624           if (ch)
625             return (gunichar)-1;
626           else
627             return (gunichar)-2;
628         }
629
630       wc <<= 6;
631       wc |= (ch & 0x3f);
632     }
633
634   if (UTF8_LENGTH(wc) != len)
635     return (gunichar)-1;
636   
637   return wc;
638 }
639
640 /**
641  * g_utf8_get_char_validated:
642  * @p: a pointer to Unicode character encoded as UTF-8
643  * @max_len: the maximum number of bytes to read, or -1, for no maximum.
644  * 
645  * Convert a sequence of bytes encoded as UTF-8 to a Unicode character.
646  * This function checks for incomplete characters, for invalid characters
647  * such as characters that are out of the range of Unicode, and for
648  * overlong encodings of valid characters.
649  * 
650  * Return value: the resulting character. If @p points to a partial
651  *    sequence at the end of a string that could begin a valid character,
652  *    returns (gunichar)-2; otherwise, if @p does not point to a valid
653  *    UTF-8 encoded Unicode character, returns (gunichar)-1.
654  **/
655 gunichar
656 g_utf8_get_char_validated (const  gchar *p,
657                            gssize max_len)
658 {
659   gunichar result = g_utf8_get_char_extended (p, max_len);
660
661   if (result & 0x80000000)
662     return result;
663   else if (!UNICODE_VALID (result))
664     return (gunichar)-1;
665   else
666     return result;
667 }
668
669 /**
670  * g_utf8_to_ucs4_fast:
671  * @str: a UTF-8 encoded string
672  * @len: the maximum length of @str to use. If @len < 0, then
673  *       the string is nul-terminated.
674  * @items_written: location to store the number of characters in the
675  *                 result, or %NULL.
676  *
677  * Convert a string from UTF-8 to a 32-bit fixed width
678  * representation as UCS-4, assuming valid UTF-8 input.
679  * This function is roughly twice as fast as g_utf8_to_ucs4()
680  * but does no error checking on the input.
681  * 
682  * Return value: a pointer to a newly allocated UCS-4 string.
683  *               This value must be freed with g_free().
684  **/
685 gunichar *
686 g_utf8_to_ucs4_fast (const gchar *str,
687                      glong        len,              
688                      glong       *items_written)    
689 {
690   gint j, charlen;
691   gunichar *result;
692   gint n_chars, i;
693   const gchar *p;
694
695   g_return_val_if_fail (str != NULL, NULL);
696
697   p = str;
698   n_chars = 0;
699   if (len < 0)
700     {
701       while (*p)
702         {
703           p = g_utf8_next_char (p);
704           ++n_chars;
705         }
706     }
707   else
708     {
709       while (p < str + len && *p)
710         {
711           p = g_utf8_next_char (p);
712           ++n_chars;
713         }
714     }
715   
716   result = g_new (gunichar, n_chars + 1);
717   
718   p = str;
719   for (i=0; i < n_chars; i++)
720     {
721       gunichar wc = ((unsigned char *)p)[0];
722
723       if (wc < 0x80)
724         {
725           result[i] = wc;
726           p++;
727         }
728       else
729         { 
730           if (wc < 0xe0)
731             {
732               charlen = 2;
733               wc &= 0x1f;
734             }
735           else if (wc < 0xf0)
736             {
737               charlen = 3;
738               wc &= 0x0f;
739             }
740           else if (wc < 0xf8)
741             {
742               charlen = 4;
743               wc &= 0x07;
744             }
745           else if (wc < 0xfc)
746             {
747               charlen = 5;
748               wc &= 0x03;
749             }
750           else
751             {
752               charlen = 6;
753               wc &= 0x01;
754             }
755
756           for (j = 1; j < charlen; j++)
757             {
758               wc <<= 6;
759               wc |= ((unsigned char *)p)[j] & 0x3f;
760             }
761
762           result[i] = wc;
763           p += charlen;
764         }
765     }
766   result[i] = 0;
767
768   if (items_written)
769     *items_written = i;
770
771   return result;
772 }
773
774 /**
775  * g_utf8_to_ucs4:
776  * @str: a UTF-8 encoded string
777  * @len: the maximum length of @str to use. If @len < 0, then
778  *       the string is nul-terminated.
779  * @items_read: location to store number of bytes read, or %NULL.
780  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
781  *              returned in case @str contains a trailing partial
782  *              character. If an error occurs then the index of the
783  *              invalid input is stored here.
784  * @items_written: location to store number of characters written or %NULL.
785  *                 The value here stored does not include the trailing 0
786  *                 character. 
787  * @error: location to store the error occuring, or %NULL to ignore
788  *         errors. Any of the errors in #GConvertError other than
789  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
790  *
791  * Convert a string from UTF-8 to a 32-bit fixed width
792  * representation as UCS-4. A trailing 0 will be added to the
793  * string after the converted text.
794  * 
795  * Return value: a pointer to a newly allocated UCS-4 string.
796  *               This value must be freed with g_free(). If an
797  *               error occurs, %NULL will be returned and
798  *               @error set.
799  **/
800 gunichar *
801 g_utf8_to_ucs4 (const gchar *str,
802                 glong        len,             
803                 glong       *items_read,      
804                 glong       *items_written,   
805                 GError     **error)
806 {
807   gunichar *result = NULL;
808   gint n_chars, i;
809   const gchar *in;
810   
811   in = str;
812   n_chars = 0;
813   while ((len < 0 || str + len - in > 0) && *in)
814     {
815       gunichar wc = g_utf8_get_char_extended (in, str + len - in);
816       if (wc & 0x80000000)
817         {
818           if (wc == (gunichar)-2)
819             {
820               if (items_read)
821                 break;
822               else
823                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
824                              _("Partial character sequence at end of input"));
825             }
826           else
827             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
828                          _("Invalid byte sequence in conversion input"));
829
830           goto err_out;
831         }
832
833       n_chars++;
834
835       in = g_utf8_next_char (in);
836     }
837
838   result = g_new (gunichar, n_chars + 1);
839   
840   in = str;
841   for (i=0; i < n_chars; i++)
842     {
843       result[i] = g_utf8_get_char (in);
844       in = g_utf8_next_char (in);
845     }
846   result[i] = 0;
847
848   if (items_written)
849     *items_written = n_chars;
850
851  err_out:
852   if (items_read)
853     *items_read = in - str;
854
855   return result;
856 }
857
858 /**
859  * g_ucs4_to_utf8:
860  * @str: a UCS-4 encoded string
861  * @len: the maximum length of @str to use. If @len < 0, then
862  *       the string is terminated with a 0 character.
863  * @items_read: location to store number of characters read read, or %NULL.
864  * @items_written: location to store number of bytes written or %NULL.
865  *                 The value here stored does not include the trailing 0
866  *                 byte. 
867  * @error: location to store the error occuring, or %NULL to ignore
868  *         errors. Any of the errors in #GConvertError other than
869  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
870  *
871  * Convert a string from a 32-bit fixed width representation as UCS-4.
872  * to UTF-8. The result will be terminated with a 0 byte.
873  * 
874  * Return value: a pointer to a newly allocated UTF-8 string.
875  *               This value must be freed with g_free(). If an
876  *               error occurs, %NULL will be returned and
877  *               @error set.
878  **/
879 gchar *
880 g_ucs4_to_utf8 (const gunichar *str,
881                 glong           len,              
882                 glong          *items_read,       
883                 glong          *items_written,    
884                 GError        **error)
885 {
886   gint result_length;
887   gchar *result = NULL;
888   gchar *p;
889   gint i;
890
891   result_length = 0;
892   for (i = 0; len < 0 || i < len ; i++)
893     {
894       if (!str[i])
895         break;
896
897       if (str[i] >= 0x80000000)
898         {
899           if (items_read)
900             *items_read = i;
901           
902           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
903                        _("Character out of range for UTF-8"));
904           goto err_out;
905         }
906       
907       result_length += UTF8_LENGTH (str[i]);
908     }
909
910   result = g_malloc (result_length + 1);
911   p = result;
912
913   i = 0;
914   while (p < result + result_length)
915     p += g_unichar_to_utf8 (str[i++], p);
916   
917   *p = '\0';
918
919   if (items_written)
920     *items_written = p - result;
921
922  err_out:
923   if (items_read)
924     *items_read = i;
925
926   return result;
927 }
928
929 #define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)
930
931 /**
932  * g_utf16_to_utf8:
933  * @str: a UTF-16 encoded string
934  * @len: the maximum length of @str to use. If @len < 0, then
935  *       the string is terminated with a 0 character.
936  * @items_read: location to store number of words read, or %NULL.
937  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
938  *              returned in case @str contains a trailing partial
939  *              character. If an error occurs then the index of the
940  *              invalid input is stored here.
941  * @items_written: location to store number of bytes written, or %NULL.
942  *                 The value stored here does not include the trailing
943  *                 0 byte.
944  * @error: location to store the error occuring, or %NULL to ignore
945  *         errors. Any of the errors in #GConvertError other than
946  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
947  *
948  * Convert a string from UTF-16 to UTF-8. The result will be
949  * terminated with a 0 byte.
950  * 
951  * Return value: a pointer to a newly allocated UTF-8 string.
952  *               This value must be freed with g_free(). If an
953  *               error occurs, %NULL will be returned and
954  *               @error set.
955  **/
956 gchar *
957 g_utf16_to_utf8 (const gunichar2  *str,
958                  glong             len,              
959                  glong            *items_read,       
960                  glong            *items_written,    
961                  GError          **error)
962 {
963   /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
964    * are marked.
965    */
966   const gunichar2 *in;
967   gchar *out;
968   gchar *result = NULL;
969   gint n_bytes;
970   gunichar high_surrogate;
971
972   g_return_val_if_fail (str != 0, NULL);
973
974   n_bytes = 0;
975   in = str;
976   high_surrogate = 0;
977   while ((len < 0 || in - str < len) && *in)
978     {
979       gunichar2 c = *in;
980       gunichar wc;
981
982       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
983         {
984           if (high_surrogate)
985             {
986               wc = SURROGATE_VALUE (high_surrogate, c);
987               high_surrogate = 0;
988             }
989           else
990             {
991               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
992                            _("Invalid sequence in conversion input"));
993               goto err_out;
994             }
995         }
996       else
997         {
998           if (high_surrogate)
999             {
1000               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1001                            _("Invalid sequence in conversion input"));
1002               goto err_out;
1003             }
1004
1005           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1006             {
1007               high_surrogate = c;
1008               goto next1;
1009             }
1010           else
1011             wc = c;
1012         }
1013
1014       /********** DIFFERENT for UTF8/UCS4 **********/
1015       n_bytes += UTF8_LENGTH (wc);
1016
1017     next1:
1018       in++;
1019     }
1020
1021   if (high_surrogate && !items_read)
1022     {
1023       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1024                    _("Partial character sequence at end of input"));
1025       goto err_out;
1026     }
1027   
1028   /* At this point, everything is valid, and we just need to convert
1029    */
1030   /********** DIFFERENT for UTF8/UCS4 **********/
1031   result = g_malloc (n_bytes + 1);
1032   
1033   high_surrogate = 0;
1034   out = result;
1035   in = str;
1036   while (out < result + n_bytes)
1037     {
1038       gunichar2 c = *in;
1039       gunichar wc;
1040
1041       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1042         {
1043           wc = SURROGATE_VALUE (high_surrogate, c);
1044           high_surrogate = 0;
1045         }
1046       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1047         {
1048           high_surrogate = c;
1049           goto next2;
1050         }
1051       else
1052         wc = c;
1053
1054       /********** DIFFERENT for UTF8/UCS4 **********/
1055       out += g_unichar_to_utf8 (wc, out);
1056
1057     next2:
1058       in++;
1059     }
1060   
1061   /********** DIFFERENT for UTF8/UCS4 **********/
1062   *out = '\0';
1063
1064   if (items_written)
1065     /********** DIFFERENT for UTF8/UCS4 **********/
1066     *items_written = out - result;
1067
1068  err_out:
1069   if (items_read)
1070     *items_read = in - str;
1071
1072   return result;
1073 }
1074
1075 /**
1076  * g_utf16_to_ucs4:
1077  * @str: a UTF-16 encoded string
1078  * @len: the maximum length of @str to use. If @len < 0, then
1079  *       the string is terminated with a 0 character.
1080  * @items_read: location to store number of words read, or %NULL.
1081  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1082  *              returned in case @str contains a trailing partial
1083  *              character. If an error occurs then the index of the
1084  *              invalid input is stored here.
1085  * @items_written: location to store number of characters written, or %NULL.
1086  *                 The value stored here does not include the trailing
1087  *                 0 character.
1088  * @error: location to store the error occuring, or %NULL to ignore
1089  *         errors. Any of the errors in #GConvertError other than
1090  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1091  *
1092  * Convert a string from UTF-16 to UCS-4. The result will be
1093  * terminated with a 0 character.
1094  * 
1095  * Return value: a pointer to a newly allocated UCS-4 string.
1096  *               This value must be freed with g_free(). If an
1097  *               error occurs, %NULL will be returned and
1098  *               @error set.
1099  **/
1100 gunichar *
1101 g_utf16_to_ucs4 (const gunichar2  *str,
1102                  glong             len,              
1103                  glong            *items_read,       
1104                  glong            *items_written,    
1105                  GError          **error)
1106 {
1107   const gunichar2 *in;
1108   gchar *out;
1109   gchar *result = NULL;
1110   gint n_bytes;
1111   gunichar high_surrogate;
1112
1113   g_return_val_if_fail (str != 0, NULL);
1114
1115   n_bytes = 0;
1116   in = str;
1117   high_surrogate = 0;
1118   while ((len < 0 || in - str < len) && *in)
1119     {
1120       gunichar2 c = *in;
1121       gunichar wc;
1122
1123       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1124         {
1125           if (high_surrogate)
1126             {
1127               wc = SURROGATE_VALUE (high_surrogate, c);
1128               high_surrogate = 0;
1129             }
1130           else
1131             {
1132               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1133                            _("Invalid sequence in conversion input"));
1134               goto err_out;
1135             }
1136         }
1137       else
1138         {
1139           if (high_surrogate)
1140             {
1141               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1142                            _("Invalid sequence in conversion input"));
1143               goto err_out;
1144             }
1145
1146           if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1147             {
1148               high_surrogate = c;
1149               goto next1;
1150             }
1151           else
1152             wc = c;
1153         }
1154
1155       /********** DIFFERENT for UTF8/UCS4 **********/
1156       n_bytes += sizeof (gunichar);
1157
1158     next1:
1159       in++;
1160     }
1161
1162   if (high_surrogate && !items_read)
1163     {
1164       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1165                    _("Partial character sequence at end of input"));
1166       goto err_out;
1167     }
1168   
1169   /* At this point, everything is valid, and we just need to convert
1170    */
1171   /********** DIFFERENT for UTF8/UCS4 **********/
1172   result = g_malloc (n_bytes + 4);
1173   
1174   high_surrogate = 0;
1175   out = result;
1176   in = str;
1177   while (out < result + n_bytes)
1178     {
1179       gunichar2 c = *in;
1180       gunichar wc;
1181
1182       if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
1183         {
1184           wc = SURROGATE_VALUE (high_surrogate, c);
1185           high_surrogate = 0;
1186         }
1187       else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
1188         {
1189           high_surrogate = c;
1190           goto next2;
1191         }
1192       else
1193         wc = c;
1194
1195       /********** DIFFERENT for UTF8/UCS4 **********/
1196       *(gunichar *)out = wc;
1197       out += sizeof (gunichar);
1198
1199     next2:
1200       in++;
1201     }
1202
1203   /********** DIFFERENT for UTF8/UCS4 **********/
1204   *(gunichar *)out = 0;
1205
1206   if (items_written)
1207     /********** DIFFERENT for UTF8/UCS4 **********/
1208     *items_written = (out - result) / sizeof (gunichar);
1209
1210  err_out:
1211   if (items_read)
1212     *items_read = in - str;
1213
1214   return (gunichar *)result;
1215 }
1216
1217 /**
1218  * g_utf8_to_utf16:
1219  * @str: a UTF-8 encoded string
1220  * @len: the maximum length of @str to use. If @len < 0, then
1221  *       the string is nul-terminated.
1222  
1223  * @items_read: location to store number of bytes read, or %NULL.
1224  *              If %NULL, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
1225  *              returned in case @str contains a trailing partial
1226  *              character. If an error occurs then the index of the
1227  *              invalid input is stored here.
1228  * @items_written: location to store number of words written, or %NULL.
1229  *                 The value stored here does not include the trailing
1230  *                 0 word.
1231  * @error: location to store the error occuring, or %NULL to ignore
1232  *         errors. Any of the errors in #GConvertError other than
1233  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1234  *
1235  * Convert a string from UTF-8 to UTF-16. A 0 word will be
1236  * added to the result after the converted text.
1237  * 
1238  * Return value: a pointer to a newly allocated UTF-16 string.
1239  *               This value must be freed with g_free(). If an
1240  *               error occurs, %NULL will be returned and
1241  *               @error set.
1242  **/
1243 gunichar2 *
1244 g_utf8_to_utf16 (const gchar *str,
1245                  glong        len,              
1246                  glong       *items_read,       
1247                  glong       *items_written,    
1248                  GError     **error)
1249 {
1250   gunichar2 *result = NULL;
1251   gint n16;
1252   const gchar *in;
1253   gint i;
1254
1255   g_return_val_if_fail (str != NULL, NULL);
1256
1257   in = str;
1258   n16 = 0;
1259   while ((len < 0 || str + len - in > 0) && *in)
1260     {
1261       gunichar wc = g_utf8_get_char_extended (in, str + len - in);
1262       if (wc & 0x80000000)
1263         {
1264           if (wc == (gunichar)-2)
1265             {
1266               if (items_read)
1267                 break;
1268               else
1269                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
1270                              _("Partial character sequence at end of input"));
1271             }
1272           else
1273             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1274                          _("Invalid byte sequence in conversion input"));
1275
1276           goto err_out;
1277         }
1278
1279       if (wc < 0xd800)
1280         n16 += 1;
1281       else if (wc < 0xe000)
1282         {
1283           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1284                        _("Invalid sequence in conversion input"));
1285
1286           goto err_out;
1287         }
1288       else if (wc < 0x10000)
1289         n16 += 1;
1290       else if (wc < 0x110000)
1291         n16 += 2;
1292       else
1293         {
1294           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1295                        _("Character out of range for UTF-16"));
1296
1297           goto err_out;
1298         }
1299       
1300       in = g_utf8_next_char (in);
1301     }
1302
1303   result = g_new (gunichar2, n16 + 1);
1304   
1305   in = str;
1306   for (i = 0; i < n16;)
1307     {
1308       gunichar wc = g_utf8_get_char (in);
1309
1310       if (wc < 0x10000)
1311         {
1312           result[i++] = wc;
1313         }
1314       else
1315         {
1316           result[i++] = (wc - 0x10000) / 0x400 + 0xd800;
1317           result[i++] = (wc - 0x10000) % 0x400 + 0xdc00;
1318         }
1319       
1320       in = g_utf8_next_char (in);
1321     }
1322
1323   result[i] = 0;
1324
1325   if (items_written)
1326     *items_written = n16;
1327
1328  err_out:
1329   if (items_read)
1330     *items_read = in - str;
1331   
1332   return result;
1333 }
1334
1335 /**
1336  * g_ucs4_to_utf16:
1337  * @str: a UCS-4 encoded string
1338  * @len: the maximum length of @str to use. If @len < 0, then
1339  *       the string is terminated with a 0 character.
1340  * @items_read: location to store number of bytes read, or %NULL.
1341  *              If an error occurs then the index of the invalid input
1342  *              is stored here.
1343  * @items_written: location to store number of words written, or %NULL.
1344  *                 The value stored here does not include the trailing
1345  *                 0 word.
1346  * @error: location to store the error occuring, or %NULL to ignore
1347  *         errors. Any of the errors in #GConvertError other than
1348  *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
1349  *
1350  * Convert a string from UCS-4 to UTF-16. A 0 word will be
1351  * added to the result after the converted text.
1352  * 
1353  * Return value: a pointer to a newly allocated UTF-16 string.
1354  *               This value must be freed with g_free(). If an
1355  *               error occurs, %NULL will be returned and
1356  *               @error set.
1357  **/
1358 gunichar2 *
1359 g_ucs4_to_utf16 (const gunichar  *str,
1360                  glong            len,              
1361                  glong           *items_read,       
1362                  glong           *items_written,    
1363                  GError         **error)
1364 {
1365   gunichar2 *result = NULL;
1366   gint n16;
1367   gint i, j;
1368
1369   n16 = 0;
1370   i = 0;
1371   while ((len < 0 || i < len) && str[i])
1372     {
1373       gunichar wc = str[i];
1374
1375       if (wc < 0xd800)
1376         n16 += 1;
1377       else if (wc < 0xe000)
1378         {
1379           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1380                        _("Invalid sequence in conversion input"));
1381
1382           goto err_out;
1383         }
1384       else if (wc < 0x10000)
1385         n16 += 1;
1386       else if (wc < 0x110000)
1387         n16 += 2;
1388       else
1389         {
1390           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1391                        _("Character out of range for UTF-16"));
1392
1393           goto err_out;
1394         }
1395
1396       i++;
1397     }
1398   
1399   result = g_new (gunichar2, n16 + 1);
1400   
1401   for (i = 0, j = 0; j < n16; i++)
1402     {
1403       gunichar wc = str[i];
1404
1405       if (wc < 0x10000)
1406         {
1407           result[j++] = wc;
1408         }
1409       else
1410         {
1411           result[j++] = (wc - 0x10000) / 0x400 + 0xd800;
1412           result[j++] = (wc - 0x10000) % 0x400 + 0xdc00;
1413         }
1414     }
1415   result[j] = 0;
1416
1417   if (items_written)
1418     *items_written = n16;
1419   
1420  err_out:
1421   if (items_read)
1422     *items_read = i;
1423   
1424   return result;
1425 }
1426
1427 /**
1428  * g_utf8_validate:
1429  * @str: a pointer to character data
1430  * @max_len: max bytes to validate, or -1 to go until nul
1431  * @end: return location for end of valid data
1432  * 
1433  * Validates UTF-8 encoded text. @str is the text to validate;
1434  * if @str is nul-terminated, then @max_len can be -1, otherwise
1435  * @max_len should be the number of bytes to validate.
1436  * If @end is non-%NULL, then the end of the valid range
1437  * will be stored there (i.e. the address of the first invalid byte
1438  * if some bytes were invalid, or the end of the text being validated
1439  * otherwise).
1440  *
1441  * Returns %TRUE if all of @str was valid. Many GLib and GTK+
1442  * routines <emphasis>require</emphasis> valid UTF-8 as input;
1443  * so data read from a file or the network should be checked
1444  * with g_utf8_validate() before doing anything else with it.
1445  * 
1446  * Return value: %TRUE if the text was valid UTF-8
1447  **/
1448 gboolean
1449 g_utf8_validate (const gchar  *str,
1450                  gssize        max_len,    
1451                  const gchar **end)
1452 {
1453
1454   const gchar *p;
1455
1456   g_return_val_if_fail (str != NULL, FALSE);
1457   
1458   if (end)
1459     *end = str;
1460   
1461   p = str;
1462   
1463   while ((max_len < 0 || (p - str) < max_len) && *p)
1464     {
1465       int i, mask = 0, len;
1466       gunichar result;
1467       unsigned char c = (unsigned char) *p;
1468       
1469       UTF8_COMPUTE (c, mask, len);
1470
1471       if (len == -1)
1472         break;
1473
1474       /* check that the expected number of bytes exists in str */
1475       if (max_len >= 0 &&
1476           ((max_len - (p - str)) < len))
1477         break;
1478         
1479       UTF8_GET (result, p, i, mask, len);
1480
1481       if (UTF8_LENGTH (result) != len) /* Check for overlong UTF-8 */
1482         break;
1483
1484       if (result == (gunichar)-1)
1485         break;
1486
1487       if (!UNICODE_VALID (result))
1488         break;
1489       
1490       p += len;
1491     }
1492
1493   if (end)
1494     *end = p;
1495
1496   /* See that we covered the entire length if a length was
1497    * passed in, or that we ended on a nul if not
1498    */
1499   if (max_len >= 0 &&
1500       p != (str + max_len))
1501     return FALSE;
1502   else if (max_len < 0 &&
1503            *p != '\0')
1504     return FALSE;
1505   else
1506     return TRUE;
1507 }
1508
1509 /**
1510  * g_unichar_validate:
1511  * @ch: a Unicode character
1512  * 
1513  * Checks whether @ch is a valid Unicode character. Some possible
1514  * integer values of @ch will not be valid. 0 is considered a valid
1515  * character, though it's normally a string terminator.
1516  * 
1517  * Return value: %TRUE if @ch is a valid Unicode character
1518  **/
1519 gboolean
1520 g_unichar_validate (gunichar ch)
1521 {
1522   return UNICODE_VALID (ch);
1523 }