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