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