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