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