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