]> git.sesse.net Git - vlc/blob - src/misc/unicode.c
Add some more debug (this is easier than compiling at home).
[vlc] / src / misc / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * UTF16toUTF8() adapted from Perl 5 (also GPL'd)
10  * Copyright (C) 1998-2002, Larry Wall
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <vlc/vlc.h>
31 #include "charset.h"
32
33 #include <assert.h>
34
35 #include <stdio.h>
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #ifdef HAVE_DIRENT_H
41 #  include <dirent.h>
42 #endif
43 #ifdef UNDER_CE
44 #  include <tchar.h>
45 #endif
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49
50 #ifndef HAVE_LSTAT
51 # define lstat( a, b ) stat(a, b)
52 #endif
53
54 #ifdef __APPLE__
55 /* Define this if the OS always use UTF-8 internally */
56 # define ASSUME_UTF8 1
57 #endif
58
59 #ifndef ASSUME_UTF8
60 # if defined (HAVE_ICONV)
61 /* libiconv is more powerful than Win32 API (it has translit) */
62 #  define USE_ICONV 1
63 # elif defined (WIN32) || defined (UNDER_CE)
64 #  define USE_MB2MB 1
65 # else
66 #  error No UTF8 charset conversion implemented on this platform!
67 # endif
68 #endif
69
70 #ifdef USE_ICONV
71 static struct {
72     vlc_iconv_t hd;
73     vlc_mutex_t lock;
74 } from_locale, to_locale;
75 #endif
76
77 void LocaleInit( vlc_object_t *p_this )
78 {
79 #ifdef USE_ICONV
80     char *psz_charset;
81
82     if( vlc_current_charset( &psz_charset ) )
83         /* UTF-8 */
84         from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
85     else
86     {
87         /* not UTF-8 */
88         char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
89         const char *psz_conv;
90
91         /*
92          * Still allow non-ASCII characters when the locale is not set.
93          * Western Europeans are being favored for historical reasons.
94          */
95         if( strcmp( psz_charset, "ASCII" ) )
96         {
97             sprintf( psz_buf, "%s//translit", psz_charset );
98             psz_conv = psz_buf;
99         }
100         else
101             psz_conv = "ISO-8859-1//translit";
102
103         vlc_mutex_init( p_this, &from_locale.lock );
104         vlc_mutex_init( p_this, &to_locale.lock );
105         from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
106         to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
107     }
108
109     free( psz_charset );
110
111     assert( (from_locale.hd == (vlc_iconv_t)(-1))
112             == (to_locale.hd == (vlc_iconv_t)(-1)) );
113 #else
114     (void)p_this;
115 #endif
116 }
117
118 void LocaleDeinit( void )
119 {
120 #ifdef USE_ICONV
121     if( to_locale.hd != (vlc_iconv_t)(-1) )
122     {
123         vlc_iconv_close( to_locale.hd );
124         vlc_mutex_destroy( &to_locale.lock );
125     }
126
127     if( from_locale.hd != (vlc_iconv_t)(-1) )
128     {
129         vlc_iconv_close( from_locale.hd );
130         vlc_mutex_destroy( &from_locale.lock );
131     }
132 #endif
133 }
134
135 #ifdef USE_MB2MB
136 static char *MB2MB( const char *string, UINT fromCP, UINT toCP )
137 {
138     char *out;
139     wchar_t *wide;
140     int len;
141
142     len = MultiByteToWideChar( fromCP, 0, string, -1, NULL, 0 );
143     assert( len > 0 );
144     wide = (wchar_t *)malloc (len * sizeof (wchar_t));
145     if( wide == NULL )
146         return NULL;
147
148     MultiByteToWideChar( fromCP, 0, string, -1, wide, len );
149     len = WideCharToMultiByte( toCP, 0, wide, -1, NULL, 0, NULL, NULL );
150     assert( len > 0 );
151     out = malloc( len );
152
153     WideCharToMultiByte( toCP, 0, wide, -1, out, len, NULL, NULL );
154     free( wide );
155     return out;
156 }
157 #endif
158
159 /**
160  * FromLocale: converts a locale string to UTF-8
161  *
162  * @param locale nul-terminated string to be converted
163  *
164  * @return a nul-terminated UTF-8 string, or NULL in case of error.
165  * To avoid memory leak, you have to pass the result to LocaleFree()
166  * when it is no longer needed.
167  */
168 char *FromLocale( const char *locale )
169 {
170     if( locale == NULL )
171         return NULL;
172
173 #ifndef USE_MB2MB
174 # ifdef USE_ICONV
175     if( from_locale.hd != (vlc_iconv_t)(-1) )
176     {
177         const char *iptr = locale;
178         size_t inb = strlen( locale );
179         size_t outb = inb * 6 + 1;
180         char output[outb], *optr = output;
181
182         vlc_mutex_lock( &from_locale.lock );
183         vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
184
185         while( vlc_iconv( from_locale.hd, &iptr, &inb, &optr, &outb )
186                == (size_t)-1 )
187         {
188             *optr++ = '?';
189             outb--;
190             iptr++;
191             inb--;
192             vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
193         }
194         vlc_mutex_unlock( &from_locale.lock );
195         *optr = '\0';
196
197         assert (inb == 0);
198         assert (*iptr == '\0');
199         assert (*optr == '\0');
200         assert (strlen( output ) == (size_t)(optr - output));
201         return strdup( output );
202     }
203 # endif /* USE_ICONV */
204     return (char *)locale;
205 #else /* MB2MB */
206     return MB2MB( locale, CP_ACP, CP_UTF8 );
207 #endif
208 }
209
210 char *FromLocaleDup( const char *locale )
211 {
212 #if defined (ASSUME_UTF8)
213     return strdup( locale );
214 #else
215 # ifdef USE_ICONV
216     if (from_locale.hd == (vlc_iconv_t)(-1))
217         return strdup( locale );
218 # endif
219     return FromLocale( locale );
220 #endif
221 }
222
223
224 /**
225  * ToLocale: converts a UTF-8 string to local system encoding.
226  *
227  * @param utf8 nul-terminated string to be converted
228  *
229  * @return a nul-terminated string, or NULL in case of error.
230  * To avoid memory leak, you have to pass the result to LocaleFree()
231  * when it is no longer needed.
232  */
233 char *ToLocale( const char *utf8 )
234 {
235     if( utf8 == NULL )
236         return NULL;
237
238 #ifndef USE_MB2MB
239 # ifdef USE_ICONV
240     if( to_locale.hd != (vlc_iconv_t)(-1) )
241     {
242         const char *iptr = utf8;
243         size_t inb = strlen( utf8 );
244         /* FIXME: I'm not sure about the value for the multiplication
245         * (for western people, multiplication is not needed) */
246         size_t outb = inb * 2 + 1;
247
248         char output[outb], *optr = output;
249
250         vlc_mutex_lock( &to_locale.lock );
251         vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
252
253         while( vlc_iconv( to_locale.hd, &iptr, &inb, &optr, &outb )
254                == (size_t)-1 )
255         {
256             *optr++ = '?'; /* should not happen, and yes, it sucks */
257             outb--;
258             iptr++;
259             inb--;
260             vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
261         }
262         vlc_mutex_unlock( &to_locale.lock );
263         *optr = '\0';
264
265         assert (inb == 0);
266         assert (*iptr == '\0');
267         assert (*optr == '\0');
268         assert (strlen( output ) == (size_t)(optr - output));
269         return strdup( output );
270     }
271 # endif /* USE_ICONV */
272     return (char *)utf8;
273 #else /* MB2MB */
274     return MB2MB( utf8, CP_UTF8, CP_ACP );
275 #endif
276 }
277
278 char *ToLocaleDup( const char *utf8 )
279 {
280 #if defined (ASSUME_UTF8)
281     return strdup( utf8 );
282 #else
283 # ifdef USE_ICONV
284     if (to_locale.hd == (vlc_iconv_t)(-1))
285         return strdup( utf8 );
286 # endif
287     return ToLocale( utf8 );
288 #endif
289 }
290
291 void LocaleFree( const char *str )
292 {
293 #ifdef USE_ICONV
294     if( to_locale.hd == (vlc_iconv_t)(-1) )
295         return;
296 #endif
297
298 #ifndef ASSUME_UTF8
299     if( str != NULL )
300         free( (char *)str );
301 #endif
302 }
303
304 /**
305  * utf8_fopen: Calls fopen() after conversion of file name to OS locale
306  */
307 FILE *utf8_fopen( const char *filename, const char *mode )
308 {
309 #if !(defined (WIN32) || defined (UNDER_CE))
310     const char *local_name = ToLocale( filename );
311
312     if( local_name != NULL )
313     {
314         FILE *stream = fopen( local_name, mode );
315         LocaleFree( local_name );
316         return stream;
317     }
318     else
319         errno = ENOENT;
320     return NULL;
321 #else
322     wchar_t wpath[MAX_PATH + 1];
323     size_t len = strlen( mode ) + 1;
324     wchar_t wmode[len];
325
326     if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH )
327      || !MultiByteToWideChar( CP_ACP, 0, mode, len, wmode, len ) )
328     {
329         errno = ENOENT;
330         return NULL;
331     }
332     wpath[MAX_PATH] = L'\0';
333
334     /* retrieve OS version */
335     if( GetVersion() < 0x80000000 )
336     {
337         /* for Windows NT and above */
338         /*
339          * fopen() cannot open files with non-“ANSI” characters on Windows.
340          * We use _wfopen() instead. Same thing for mkdir() and stat().
341          */
342         return _wfopen( wpath, wmode );
343     }
344     else
345     {
346         /* for Windows Me/98/95 */
347         /* we use GetShortFileNameW to get the DOS 8.3 version of the file we need to open */
348         char spath[MAX_PATH + 1];
349         if( GetShortPathNameW( wpath, spath, MAX_PATH ) )
350         {
351             fprintf( stderr, "A fopen path: %s -> %s\n", wpath, spath );
352             wfprintf( stderr, "W fopen path: %s -> %s\n", wpath, spath );
353             return fopen( spath, wmode );
354         }
355         fprintf( stderr, "GetShortPathName for %s failed\n", wpath );
356         errno = ENOENT;
357         return NULL;
358     }
359 #endif
360 }
361
362 /**
363  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
364  */
365 int utf8_mkdir( const char *dirname )
366 {
367 #if defined (UNDER_CE) || defined (WIN32)
368     wchar_t wname[MAX_PATH + 1];
369     char mod[MAX_PATH + 1];
370     int i;
371
372     /* Convert '/' into '\' */
373     for( i = 0; *dirname; i++ )
374     {
375         if( i == MAX_PATH )
376             return -1; /* overflow */
377
378         if( *dirname == '/' )
379             mod[i] = '\\';
380         else
381             mod[i] = *dirname;
382         dirname++;
383
384     }
385     mod[i] = 0;
386
387     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
388     {
389         errno = ENOENT;
390         return -1;
391     }
392     wname[MAX_PATH] = L'\0';
393
394     if( CreateDirectoryW( wname, NULL ) == 0 )
395     {
396         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
397             errno = EEXIST;
398         else
399             errno = ENOENT;
400         return -1;
401     }
402     return 0;
403 #else
404     char *locname = ToLocale( dirname );
405     int res;
406
407     if( locname == NULL )
408     {
409         errno = ENOENT;
410         return -1;
411     }
412     res = mkdir( locname, 0755 );
413
414     LocaleFree( locname );
415     return res;
416 #endif
417 }
418
419
420 void *utf8_opendir( const char *dirname )
421 {
422     const char *local_name = ToLocale( dirname );
423
424     if( local_name != NULL )
425     {
426         DIR *dir = vlc_opendir_wrapper( local_name );
427         LocaleFree( local_name );
428         return dir;
429     }
430     else
431         errno = ENOENT;
432     return NULL;
433 }
434
435 const char *utf8_readdir( void *dir )
436 {
437     struct dirent *ent;
438
439     ent = vlc_readdir_wrapper( (DIR *)dir );
440     if( ent == NULL )
441         return NULL;
442
443     return FromLocale( ent->d_name );
444 }
445
446 static int dummy_select( const char *str )
447 {
448     (void)str;
449     return 1;
450 }
451
452 int utf8_scandir( const char *dirname, char ***namelist,
453                   int (*select)( const char * ),
454                   int (*compar)( const char **, const char ** ) )
455 {
456     DIR *dir = utf8_opendir( dirname );
457
458     if( select == NULL )
459         select = dummy_select;
460
461     if( dir == NULL )
462         return -1;
463     else
464     {
465         char **tab = NULL;
466         const char *entry;
467         unsigned num = 0;
468
469         while( ( entry = utf8_readdir( dir ) ) != NULL )
470         {
471             char **newtab;
472             char *utf_entry = strdup( entry );
473             LocaleFree( entry );
474             if( utf_entry == NULL )
475                 goto error;
476
477             if( !select( utf_entry ) )
478             {
479                 free( utf_entry );
480                 continue;
481             }
482
483             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
484             if( newtab == NULL )
485             {
486                 free( utf_entry );
487                 goto error;
488             }
489             tab = newtab;
490             tab[num++] = utf_entry;
491         }
492         vlc_closedir_wrapper( dir );
493
494         if( compar != NULL )
495             qsort( tab, num, sizeof( tab[0] ),
496                    (int (*)( const void *, const void *))compar );
497
498         *namelist = tab;
499         return num;
500
501     error:{
502         unsigned i;
503
504         for( i = 0; i < num; i++ )
505             free( tab[i] );
506         if( tab != NULL )
507             free( tab );
508         return -1;}
509     }
510 }
511
512
513 static int utf8_statEx( const char *filename, void *buf,
514                         vlc_bool_t deref )
515 {
516 #if !(defined (WIN32) || defined (UNDER_CE))
517 # ifdef HAVE_SYS_STAT_H
518     const char *local_name = ToLocale( filename );
519
520     if( local_name != NULL )
521     {
522         int res = deref ? stat( local_name, (struct stat *)buf )
523                        : lstat( local_name, (struct stat *)buf );
524         LocaleFree( local_name );
525         return res;
526     }
527     errno = ENOENT;
528 # endif
529     return -1;
530 #else
531     wchar_t wpath[MAX_PATH + 1];
532
533     if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
534     {
535         errno = ENOENT;
536         return -1;
537     }
538     wpath[MAX_PATH] = L'\0';
539
540     /* retrieve Windows OS version */
541     if( GetVersion() < 0x80000000 )
542     {
543         /* for Windows NT and above */
544         return _wstati64( wpath, (struct _stati64 *)buf );
545     }
546     else
547     {
548         /* for Windows Me/98/95 */
549         /* we use GetShortFileNameW to get the DOS 8.3 version */
550         char spath[MAX_PATH + 1];
551         if( GetShortPathNameW( wpath, spath, MAX_PATH ) )
552         {
553             fprintf( stderr, "stati path: %s -> %s\n", wpath, spath );
554             return _stati64( spath, (struct _stati64 *)buf );
555         }
556         fprintf( stderr, "GetShortPathName for %s failed\n", wpath );
557         errno = ENOENT;
558         return -1;
559     }
560 #endif
561 }
562
563
564 int utf8_stat( const char *filename, void *buf)
565 {
566     return utf8_statEx( filename, buf, VLC_TRUE );
567 }
568
569 int utf8_lstat( const char *filename, void *buf)
570 {
571     return utf8_statEx( filename, buf, VLC_FALSE );
572 }
573
574 /**
575  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
576  */
577 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
578 {
579     char *utf8;
580     int res = vasprintf( &utf8, fmt, ap );
581     if( res == -1 )
582         return -1;
583
584     *str = ToLocaleDup( utf8 );
585     free( utf8 );
586     return res;
587 }
588
589 static int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
590 {
591     char *str;
592     int res = utf8_vasprintf( &str, fmt, ap );
593     if( res == -1 )
594         return -1;
595
596     fputs( str, stream );
597     free( str );
598     return res;
599 }
600
601 int utf8_fprintf( FILE *stream, const char *fmt, ... )
602 {
603     va_list ap;
604     int res;
605
606     va_start( ap, fmt );
607     res = utf8_vfprintf( stream, fmt, ap );
608     va_end( ap );
609     return res;
610 }
611
612
613 static char *CheckUTF8( char *str, char rep )
614 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF)) 
615 {
616     unsigned char *ptr, c;
617
618     ptr = (unsigned char *)str;
619     while( (c = *ptr) != '\0' )
620     {
621         /* US-ASCII, 1 byte */
622         if( c <= 0x7F )
623             ptr++; /* OK */
624         else
625         /* 2 bytes */
626         if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
627         {
628             c = ptr[1];
629             if( isutf8cont( c ) )
630                 ptr += 2; /* OK */
631             else
632                 goto error;
633         }
634         else
635         /* 3 bytes */
636         if( c == 0xE0 )
637         {
638             c = ptr[1];
639             if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
640             {
641                 c = ptr[2];
642                 if( isutf8cont( c ) )
643                     ptr += 3; /* OK */
644                 else
645                     goto error;
646             }
647             else
648                 goto error;
649         }
650         else
651         if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
652          || ( c == 0xEE ) || ( c == 0xEF ) )
653         {
654             c = ptr[1];
655             if( isutf8cont( c ) )
656             {
657                 c = ptr[2];
658                 if( isutf8cont( c ) )
659                     ptr += 3; /* OK */
660                 else
661                     goto error;
662             }
663             else
664                 goto error;
665         }
666         else
667         if( c == 0xED )
668         {
669             c = ptr[1];
670             if( ( c >= 0x80 ) && ( c <= 0x9F ) )
671             {
672                 c = ptr[2];
673                 if( isutf8cont( c ) )
674                     ptr += 3; /* OK */
675                 else
676                     goto error;
677             }
678             else
679                 goto error;
680         }
681         else
682         /* 4 bytes */
683         if( c == 0xF0 )
684         {
685             c = ptr[1];
686             if( ( c >= 0x90 ) && ( c <= 0xBF ) )
687             {
688                 c = ptr[2];
689                 if( isutf8cont( c ) )
690                 {
691                     c = ptr[3];
692                     if( isutf8cont( c ) )
693                         ptr += 4; /* OK */
694                     else
695                         goto error;
696                 }
697                 else
698                     goto error;
699             }
700             else
701                 goto error;
702         }
703         else
704         if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
705         {
706             c = ptr[1];
707             if( isutf8cont( c ) )
708             {
709                 c = ptr[2];
710                 if( isutf8cont( c ) )
711                 {
712                     c = ptr[3];
713                     if( isutf8cont( c ) )
714                         ptr += 4; /* OK */
715                     goto error;
716                 }
717                 else
718                     goto error;
719             }
720             else
721                 goto error;
722         }
723         else
724         if( c == 0xF4 )
725         {
726             c = ptr[1];
727             if( ( c >= 0x80 ) && ( c <= 0x8F ) )
728             {
729                 c = ptr[2];
730                 if( isutf8cont( c ) )
731                 {
732                     c = ptr[3];
733                     if( isutf8cont( c ) )
734                         ptr += 4; /* OK */
735                     else
736                         goto error;
737                 }
738                 else
739                     goto error;
740             }
741             else
742                 goto error;
743         }
744         else
745             goto error;
746
747         continue;
748
749 error:
750         if( rep == 0 )
751             return NULL;
752         *ptr++ = '?';
753         str = NULL;
754     }
755
756     return str;
757 }
758
759 /**
760  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
761  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
762  * so we don't try that, even though it would be less disruptive.
763  *
764  * @return str if it was valid UTF-8, NULL if not.
765  */
766 char *EnsureUTF8( char *str )
767 {
768     return CheckUTF8( str, '?' );
769 }
770
771
772 /**
773  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
774  *
775  * @param str nul-terminated string to be checked
776  *
777  * @return str if it was valid UTF-8, NULL if not.
778  */
779 const char *IsUTF8( const char *str )
780 {
781     return CheckUTF8( (char *)str, 0 );
782 }
783
784
785 /**
786  * UTF32toUTF8(): converts an array from UTF-32 (host byte order)
787  * to UTF-8.
788  *
789  * @param src the UTF-32 table to be converted
790  * @param len the number of code points to be converted from src
791  * (ie. the number of uint32_t in the table pointed to by src)
792  * @param newlen an optional pointer. If not NULL, *newlen will
793  * contain the total number of bytes written.
794  *
795  * @return the result of the conversion (must be free'd())
796  * or NULL on error (in that case, *newlen is undefined).
797  */
798 static char *
799 UTF32toUTF8( const uint32_t *src, size_t len, size_t *newlen )
800 {
801     char *res, *out;
802
803     /* allocate memory */
804     out = res = (char *)malloc( 6 * len );
805     if( res == NULL )
806         return NULL;
807
808     while( len > 0 )
809     {
810         uint32_t uv = *src++;
811         len--;
812
813         if( uv < 0x80 )
814         {
815             *out++ = uv;
816             continue;
817         }
818         else
819         if( uv < 0x800 )
820         {
821             *out++ = (( uv >>  6)         | 0xc0);
822             *out++ = (( uv        & 0x3f) | 0x80);
823             continue;
824         }
825         else
826         if( uv < 0x10000 )
827         {
828             *out++ = (( uv >> 12)         | 0xe0);
829             *out++ = (((uv >>  6) & 0x3f) | 0x80);
830             *out++ = (( uv        & 0x3f) | 0x80);
831             continue;
832         }
833         else
834         if( uv < 0x110000 )
835         {
836             *out++ = (( uv >> 18)         | 0xf0);
837             *out++ = (((uv >> 12) & 0x3f) | 0x80);
838             *out++ = (((uv >>  6) & 0x3f) | 0x80);
839             *out++ = (( uv        & 0x3f) | 0x80);
840             continue;
841         }
842         else
843         {
844             free( res );
845             return NULL;
846         }
847     }
848     len = out - res;
849     res = realloc( res, len );
850     if( newlen != NULL )
851         *newlen = len;
852     return res;
853 }
854
855 /**
856  * FromUTF32(): converts an UTF-32 string to UTF-8.
857  *
858  * @param src UTF-32 bytes sequence, aligned on a 32-bits boundary.
859  *
860  * @return the result of the conversion (must be free()'d),
861  * or NULL in case of error.
862  */
863 char *FromUTF32( const uint32_t *src )
864 {
865     const uint32_t *in;
866     size_t len;
867
868     /* determine the size of the string */
869     for( len = 1, in = src; *in; len++ )
870         in++;
871
872     return UTF32toUTF8( src, len, NULL );
873 }
874
875 /**
876  * UTF16toUTF8: converts UTF-16 (host byte order) to UTF-8
877  *
878  * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary
879  * @param len number of uint16_t to convert
880  */
881 static char *
882 UTF16toUTF8( const uint16_t *in, size_t len, size_t *newlen )
883 {
884     char *res, *out;
885
886     /* allocate memory */
887     out = res = (char *)malloc( 3 * len );
888     if( res == NULL )
889         return NULL;
890
891     while( len > 0 )
892     {
893         uint32_t uv = *in;
894
895         in++;
896         len--;
897
898         if( uv < 0x80 )
899         {
900             *out++ = uv;
901             continue;
902         }
903         if( uv < 0x800 )
904         {
905             *out++ = (( uv >>  6)         | 0xc0);
906             *out++ = (( uv        & 0x3f) | 0x80);
907             continue;
908         }
909         if( (uv >= 0xd800) && (uv < 0xdbff) )
910         {   /* surrogates */
911             uint16_t low = GetWBE( in );
912             in++;
913             len--;
914
915             if( (low < 0xdc00) || (low >= 0xdfff) )
916             {
917                 *out++ = '?'; /* Malformed surrogate */
918                 continue;
919             }
920             else
921                 uv = ((uv - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
922         }
923         if( uv < 0x10000 )
924         {
925             *out++ = (( uv >> 12)         | 0xe0);
926             *out++ = (((uv >>  6) & 0x3f) | 0x80);
927             *out++ = (( uv        & 0x3f) | 0x80);
928             continue;
929         }
930         else
931         {
932             *out++ = (( uv >> 18)         | 0xf0);
933             *out++ = (((uv >> 12) & 0x3f) | 0x80);
934             *out++ = (((uv >>  6) & 0x3f) | 0x80);
935             *out++ = (( uv        & 0x3f) | 0x80);
936             continue;
937         }
938     }
939     len = out - res;
940     res = realloc( res, len );
941     if( newlen != NULL )
942         *newlen = len;
943     return res;
944 }
945
946
947 /**
948  * FromUTF16(): converts an UTF-16 string to UTF-8.
949  *
950  * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary.
951  *
952  * @return the result of the conversion (must be free()'d),
953  * or NULL in case of error.
954  */
955 char *FromUTF16( const uint16_t *src )
956 {
957     const uint16_t *in;
958     size_t len;
959
960     /* determine the size of the string */
961     for( len = 1, in = src; *in; len++ )
962         in++;
963
964     return UTF16toUTF8( src, len, NULL );
965 }