]> git.sesse.net Git - vlc/blob - src/misc/unicode.c
More cleanup
[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     if( len == 0 )
144         return NULL;
145
146     wchar_t wide[len];
147
148     MultiByteToWideChar( fromCP, 0, string, -1, wide, len );
149     len = WideCharToMultiByte( toCP, 0, wide, -1, NULL, 0, NULL, NULL );
150     if( len == 0 )
151         return NULL;
152     out = malloc( len );
153
154     WideCharToMultiByte( toCP, 0, wide, -1, out, len, NULL, NULL );
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     if( GetVersion() < 0x80000000 )
311     {
312         /* for Windows NT and above */
313         wchar_t wpath[MAX_PATH + 1];
314         size_t len = strlen( mode ) + 1;
315         wchar_t wmode[len];
316
317         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH )
318          || !MultiByteToWideChar( CP_ACP, 0, mode, len, wmode, len ) )
319         {
320             errno = ENOENT;
321             return NULL;
322         }
323         wpath[MAX_PATH] = L'\0';
324
325         /*
326          * fopen() cannot open files with non-“ANSI” characters on Windows.
327          * We use _wfopen() instead. Same thing for mkdir() and stat().
328          */
329         return _wfopen( wpath, wmode );
330     }
331 #endif
332     const char *local_name = ToLocale( filename );
333
334     if( local_name != NULL )
335     {
336         FILE *stream = fopen( local_name, mode );
337         LocaleFree( local_name );
338         return stream;
339     }
340     else
341         errno = ENOENT;
342
343     return NULL;
344 }
345
346 /**
347  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
348  */
349 int utf8_mkdir( const char *dirname )
350 {
351 #if defined (UNDER_CE) || defined (WIN32)
352     wchar_t wname[MAX_PATH + 1];
353     char mod[MAX_PATH + 1];
354     int i;
355
356     /* Convert '/' into '\' */
357     for( i = 0; *dirname; i++ )
358     {
359         if( i == MAX_PATH )
360             return -1; /* overflow */
361
362         if( *dirname == '/' )
363             mod[i] = '\\';
364         else
365             mod[i] = *dirname;
366         dirname++;
367
368     }
369     mod[i] = 0;
370
371     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
372     {
373         errno = ENOENT;
374         return -1;
375     }
376     wname[MAX_PATH] = L'\0';
377
378     if( CreateDirectoryW( wname, NULL ) == 0 )
379     {
380         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
381             errno = EEXIST;
382         else
383             errno = ENOENT;
384         return -1;
385     }
386     return 0;
387 #else
388     char *locname = ToLocale( dirname );
389     int res;
390
391     if( locname == NULL )
392     {
393         errno = ENOENT;
394         return -1;
395     }
396     res = mkdir( locname, 0755 );
397
398     LocaleFree( locname );
399     return res;
400 #endif
401 }
402
403
404 void *utf8_opendir( const char *dirname )
405 {
406     /* TODO: support for WinNT non-ACP filenames */
407     const char *local_name = ToLocale( dirname );
408
409     if( local_name != NULL )
410     {
411         DIR *dir = vlc_opendir_wrapper( local_name );
412         LocaleFree( local_name );
413         return dir;
414     }
415     else
416         errno = ENOENT;
417     return NULL;
418 }
419
420 const char *utf8_readdir( void *dir )
421 {
422     struct dirent *ent;
423
424     ent = vlc_readdir_wrapper( (DIR *)dir );
425     if( ent == NULL )
426         return NULL;
427
428     return FromLocale( ent->d_name );
429 }
430
431 static int dummy_select( const char *str )
432 {
433     (void)str;
434     return 1;
435 }
436
437 int utf8_scandir( const char *dirname, char ***namelist,
438                   int (*select)( const char * ),
439                   int (*compar)( const char **, const char ** ) )
440 {
441     DIR *dir = utf8_opendir( dirname );
442
443     if( select == NULL )
444         select = dummy_select;
445
446     if( dir == NULL )
447         return -1;
448     else
449     {
450         char **tab = NULL;
451         const char *entry;
452         unsigned num = 0;
453
454         while( ( entry = utf8_readdir( dir ) ) != NULL )
455         {
456             char **newtab;
457             char *utf_entry = strdup( entry );
458             LocaleFree( entry );
459             if( utf_entry == NULL )
460                 goto error;
461
462             if( !select( utf_entry ) )
463             {
464                 free( utf_entry );
465                 continue;
466             }
467
468             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
469             if( newtab == NULL )
470             {
471                 free( utf_entry );
472                 goto error;
473             }
474             tab = newtab;
475             tab[num++] = utf_entry;
476         }
477         vlc_closedir_wrapper( dir );
478
479         if( compar != NULL )
480             qsort( tab, num, sizeof( tab[0] ),
481                    (int (*)( const void *, const void *))compar );
482
483         *namelist = tab;
484         return num;
485
486     error:{
487         unsigned i;
488
489         for( i = 0; i < num; i++ )
490             free( tab[i] );
491         if( tab != NULL )
492             free( tab );
493         return -1;}
494     }
495 }
496
497
498 static int utf8_statEx( const char *filename, void *buf,
499                         vlc_bool_t deref )
500 {
501 #if defined (WIN32) || defined (UNDER_CE)
502     /* retrieve Windows OS version */
503     if( GetVersion() < 0x80000000 )
504     {
505         /* for Windows NT and above */
506         wchar_t wpath[MAX_PATH + 1];
507
508         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
509         {
510             errno = ENOENT;
511             return -1;
512         }
513         wpath[MAX_PATH] = L'\0';
514
515         return _wstati64( wpath, (struct _stati64 *)buf );
516     }
517 #endif
518 #ifdef HAVE_SYS_STAT_H
519     const char *local_name = ToLocale( filename );
520
521     if( local_name != NULL )
522     {
523         int res = deref ? stat( local_name, (struct stat *)buf )
524                        : lstat( local_name, (struct stat *)buf );
525         LocaleFree( local_name );
526         return res;
527     }
528     errno = ENOENT;
529 #endif
530     return -1;
531 }
532
533
534 int utf8_stat( const char *filename, void *buf)
535 {
536     return utf8_statEx( filename, buf, VLC_TRUE );
537 }
538
539 int utf8_lstat( const char *filename, void *buf)
540 {
541     return utf8_statEx( filename, buf, VLC_FALSE );
542 }
543
544 /**
545  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
546  */
547 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
548 {
549     char *utf8;
550     int res = vasprintf( &utf8, fmt, ap );
551     if( res == -1 )
552         return -1;
553
554     *str = ToLocaleDup( utf8 );
555     free( utf8 );
556     return res;
557 }
558
559 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
560 {
561     char *str;
562     int res = utf8_vasprintf( &str, fmt, ap );
563     if( res == -1 )
564         return -1;
565
566     fputs( str, stream );
567     free( str );
568     return res;
569 }
570
571 int utf8_fprintf( FILE *stream, const char *fmt, ... )
572 {
573     va_list ap;
574     int res;
575
576     va_start( ap, fmt );
577     res = utf8_vfprintf( stream, fmt, ap );
578     va_end( ap );
579     return res;
580 }
581
582
583 static char *CheckUTF8( char *str, char rep )
584 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF)) 
585 {
586     unsigned char *ptr, c;
587
588     assert (str != NULL);
589
590     ptr = (unsigned char *)str;
591     while( (c = *ptr) != '\0' )
592     {
593         /* US-ASCII, 1 byte */
594         if( c <= 0x7F )
595             ptr++; /* OK */
596         else
597         /* 2 bytes */
598         if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
599         {
600             c = ptr[1];
601             if( isutf8cont( c ) )
602                 ptr += 2; /* OK */
603             else
604                 goto error;
605         }
606         else
607         /* 3 bytes */
608         if( c == 0xE0 )
609         {
610             c = ptr[1];
611             if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
612             {
613                 c = ptr[2];
614                 if( isutf8cont( c ) )
615                     ptr += 3; /* OK */
616                 else
617                     goto error;
618             }
619             else
620                 goto error;
621         }
622         else
623         if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
624          || ( c == 0xEE ) || ( c == 0xEF ) )
625         {
626             c = ptr[1];
627             if( isutf8cont( c ) )
628             {
629                 c = ptr[2];
630                 if( isutf8cont( c ) )
631                     ptr += 3; /* OK */
632                 else
633                     goto error;
634             }
635             else
636                 goto error;
637         }
638         else
639         if( c == 0xED )
640         {
641             c = ptr[1];
642             if( ( c >= 0x80 ) && ( c <= 0x9F ) )
643             {
644                 c = ptr[2];
645                 if( isutf8cont( c ) )
646                     ptr += 3; /* OK */
647                 else
648                     goto error;
649             }
650             else
651                 goto error;
652         }
653         else
654         /* 4 bytes */
655         if( c == 0xF0 )
656         {
657             c = ptr[1];
658             if( ( c >= 0x90 ) && ( c <= 0xBF ) )
659             {
660                 c = ptr[2];
661                 if( isutf8cont( c ) )
662                 {
663                     c = ptr[3];
664                     if( isutf8cont( c ) )
665                         ptr += 4; /* OK */
666                     else
667                         goto error;
668                 }
669                 else
670                     goto error;
671             }
672             else
673                 goto error;
674         }
675         else
676         if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
677         {
678             c = ptr[1];
679             if( isutf8cont( c ) )
680             {
681                 c = ptr[2];
682                 if( isutf8cont( c ) )
683                 {
684                     c = ptr[3];
685                     if( isutf8cont( c ) )
686                         ptr += 4; /* OK */
687                     goto error;
688                 }
689                 else
690                     goto error;
691             }
692             else
693                 goto error;
694         }
695         else
696         if( c == 0xF4 )
697         {
698             c = ptr[1];
699             if( ( c >= 0x80 ) && ( c <= 0x8F ) )
700             {
701                 c = ptr[2];
702                 if( isutf8cont( c ) )
703                 {
704                     c = ptr[3];
705                     if( isutf8cont( c ) )
706                         ptr += 4; /* OK */
707                     else
708                         goto error;
709                 }
710                 else
711                     goto error;
712             }
713             else
714                 goto error;
715         }
716         else
717             goto error;
718
719         continue;
720
721 error:
722         if( rep == 0 )
723             return NULL;
724         *ptr++ = '?';
725         str = NULL;
726     }
727
728     return str;
729 }
730
731 /**
732  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
733  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
734  * so we don't try that, even though it would be less disruptive.
735  *
736  * @return str if it was valid UTF-8, NULL if not.
737  */
738 char *EnsureUTF8( char *str )
739 {
740     return CheckUTF8( str, '?' );
741 }
742
743
744 /**
745  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
746  *
747  * @param str nul-terminated string to be checked
748  *
749  * @return str if it was valid UTF-8, NULL if not.
750  */
751 const char *IsUTF8( const char *str )
752 {
753     return CheckUTF8( (char *)str, 0 );
754 }
755
756
757 /**
758  * UTF32toUTF8(): converts an array from UTF-32 (host byte order)
759  * to UTF-8.
760  *
761  * @param src the UTF-32 table to be converted
762  * @param len the number of code points to be converted from src
763  * (ie. the number of uint32_t in the table pointed to by src)
764  * @param newlen an optional pointer. If not NULL, *newlen will
765  * contain the total number of bytes written.
766  *
767  * @return the result of the conversion (must be free'd())
768  * or NULL on error (in that case, *newlen is undefined).
769  */
770 static char *
771 UTF32toUTF8( const uint32_t *src, size_t len, size_t *newlen )
772 {
773     char *res, *out;
774
775     /* allocate memory */
776     out = res = (char *)malloc( 6 * len );
777     if( res == NULL )
778         return NULL;
779
780     while( len > 0 )
781     {
782         uint32_t uv = *src++;
783         len--;
784
785         if( uv < 0x80 )
786         {
787             *out++ = uv;
788             continue;
789         }
790         else
791         if( uv < 0x800 )
792         {
793             *out++ = (( uv >>  6)         | 0xc0);
794             *out++ = (( uv        & 0x3f) | 0x80);
795             continue;
796         }
797         else
798         if( uv < 0x10000 )
799         {
800             *out++ = (( uv >> 12)         | 0xe0);
801             *out++ = (((uv >>  6) & 0x3f) | 0x80);
802             *out++ = (( uv        & 0x3f) | 0x80);
803             continue;
804         }
805         else
806         if( uv < 0x110000 )
807         {
808             *out++ = (( uv >> 18)         | 0xf0);
809             *out++ = (((uv >> 12) & 0x3f) | 0x80);
810             *out++ = (((uv >>  6) & 0x3f) | 0x80);
811             *out++ = (( uv        & 0x3f) | 0x80);
812             continue;
813         }
814         else
815         {
816             free( res );
817             return NULL;
818         }
819     }
820     len = out - res;
821     res = realloc( res, len );
822     if( newlen != NULL )
823         *newlen = len;
824     return res;
825 }
826
827 /**
828  * FromUTF32(): converts an UTF-32 string to UTF-8.
829  *
830  * @param src UTF-32 bytes sequence, aligned on a 32-bits boundary.
831  *
832  * @return the result of the conversion (must be free()'d),
833  * or NULL in case of error.
834  */
835 char *FromUTF32( const uint32_t *src )
836 {
837     const uint32_t *in;
838     size_t len;
839
840     /* determine the size of the string */
841     for( len = 1, in = src; *in; len++ )
842         in++;
843
844     return UTF32toUTF8( src, len, NULL );
845 }
846
847 /**
848  * UTF16toUTF8: converts UTF-16 (host byte order) to UTF-8
849  *
850  * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary
851  * @param len number of uint16_t to convert
852  */
853 static char *
854 UTF16toUTF8( const uint16_t *in, size_t len, size_t *newlen )
855 {
856     char *res, *out;
857
858     /* allocate memory */
859     out = res = (char *)malloc( 3 * len );
860     if( res == NULL )
861         return NULL;
862
863     while( len > 0 )
864     {
865         uint32_t uv = *in;
866
867         in++;
868         len--;
869
870         if( uv < 0x80 )
871         {
872             *out++ = uv;
873             continue;
874         }
875         if( uv < 0x800 )
876         {
877             *out++ = (( uv >>  6)         | 0xc0);
878             *out++ = (( uv        & 0x3f) | 0x80);
879             continue;
880         }
881         if( (uv >= 0xd800) && (uv < 0xdbff) )
882         {   /* surrogates */
883             uint16_t low = GetWBE( in );
884             in++;
885             len--;
886
887             if( (low < 0xdc00) || (low >= 0xdfff) )
888             {
889                 *out++ = '?'; /* Malformed surrogate */
890                 continue;
891             }
892             else
893                 uv = ((uv - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
894         }
895         if( uv < 0x10000 )
896         {
897             *out++ = (( uv >> 12)         | 0xe0);
898             *out++ = (((uv >>  6) & 0x3f) | 0x80);
899             *out++ = (( uv        & 0x3f) | 0x80);
900             continue;
901         }
902         else
903         {
904             *out++ = (( uv >> 18)         | 0xf0);
905             *out++ = (((uv >> 12) & 0x3f) | 0x80);
906             *out++ = (((uv >>  6) & 0x3f) | 0x80);
907             *out++ = (( uv        & 0x3f) | 0x80);
908             continue;
909         }
910     }
911     len = out - res;
912     res = realloc( res, len );
913     if( newlen != NULL )
914         *newlen = len;
915     return res;
916 }
917
918
919 /**
920  * FromUTF16(): converts an UTF-16 string to UTF-8.
921  *
922  * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary.
923  *
924  * @return the result of the conversion (must be free()'d),
925  * or NULL in case of error.
926  */
927 char *FromUTF16( const uint16_t *src )
928 {
929     const uint16_t *in;
930     size_t len;
931
932     /* determine the size of the string */
933     for( len = 1, in = src; *in; len++ )
934         in++;
935
936     return UTF16toUTF8( src, len, NULL );
937 }