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