]> git.sesse.net Git - vlc/blob - src/text/unicode.c
utf8_vasprintf(): avoid useless strdup if UTF-8 is assumed
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33
34 #include <assert.h>
35
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <sys/types.h>
40 #ifdef UNDER_CE
41 #  include <tchar.h>
42 #endif
43 #include <errno.h>
44
45 #if defined (__APPLE__) || defined (HAVE_MAEMO)
46 /* Define this if the OS always use UTF-8 internally */
47 # define ASSUME_UTF8 1
48 #endif
49
50 #if defined (ASSUME_UTF8)
51 /* Cool */
52
53 #elif defined (WIN32) || defined (UNDER_CE)
54 # define USE_MB2MB 1
55
56 static char *locale_dup (const char *string, bool from)
57 {
58     char *out;
59     int len;
60
61     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
62                                    0, string, -1, NULL, 0);
63     wchar_t *wide = malloc (len * sizeof (wchar_t));
64     if (wide == NULL)
65         return NULL;
66
67     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
68     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
69                                    NULL, 0, NULL, NULL);
70     out = malloc (len);
71     if (out != NULL)
72         WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
73                              NULL, NULL);
74     free (wide);
75     return out;
76 }
77
78 #elif defined (HAVE_ICONV)
79 # define USE_ICONV 1
80
81 static char *locale_dup (const char *string, bool from)
82 {
83     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : "",
84                                      from ? "" : "UTF-8");
85     if (hd == (vlc_iconv_t)(-1))
86         return NULL; /* Uho! */
87
88     const char *iptr = string;
89     size_t inb = strlen (string);
90     size_t outb = inb * 6 + 1;
91     char output[outb], *optr = output;
92
93     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
94     {
95         *optr++ = '?';
96         outb--;
97         iptr++;
98         inb--;
99         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
100     }
101     *optr = '\0';
102     vlc_iconv_close (hd);
103
104     assert (inb == 0);
105     assert (*iptr == '\0');
106     assert (*optr == '\0');
107     assert (strlen (output) == (size_t)(optr - output));
108     return strdup (output);
109 }
110
111 #else
112 # error No UTF8 charset conversion implemented on this platform!
113 #endif
114
115
116 /**
117  * Releases (if needed) a localized or uniformized string.
118  * @param str non-NULL return value from FromLocale() or ToLocale().
119  */
120 void LocaleFree (const char *str)
121 {
122 #ifdef ASSUME_UTF8
123     (void) str;
124 #else
125     free ((char *)str);
126 #endif
127 }
128
129
130 /**
131  * Converts a string from the system locale character encoding to UTF-8.
132  *
133  * @param locale nul-terminated string to convert
134  *
135  * @return a nul-terminated UTF-8 string, or NULL in case of error.
136  * To avoid memory leak, you have to pass the result to LocaleFree()
137  * when it is no longer needed.
138  */
139 char *FromLocale (const char *locale)
140 {
141 #ifdef ASSUME_UTF8
142     return (char *)locale;
143 #else
144     return locale ? locale_dup (locale, true) : NULL;
145 #endif
146 }
147
148 /**
149  * converts a string from the system locale character encoding to utf-8,
150  * the result is always allocated on the heap.
151  *
152  * @param locale nul-terminated string to convert
153  *
154  * @return a nul-terminated utf-8 string, or null in case of error.
155  * The result must be freed using free() - as with the strdup() function.
156  */
157 char *FromLocaleDup (const char *locale)
158 {
159 #ifdef ASSUME_UTF8
160     return strdup (locale);
161 #else
162     return locale_dup (locale, true);
163 #endif
164 }
165
166
167 /**
168  * ToLocale: converts an UTF-8 string to local system encoding.
169  *
170  * @param utf8 nul-terminated string to be converted
171  *
172  * @return a nul-terminated string, or NULL in case of error.
173  * To avoid memory leak, you have to pass the result to LocaleFree()
174  * when it is no longer needed.
175  */
176 char *ToLocale (const char *utf8)
177 {
178 #ifdef ASSUME_UTF8
179     return (char *)utf8;
180 #else
181     return utf8 ? locale_fast (utf8, false) : NULL
182 #endif
183 }
184
185
186 /**
187  * converts a string from UTF-8 to the system locale character encoding,
188  * the result is always allocated on the heap.
189  *
190  * @param utf8 nul-terminated string to convert
191  *
192  * @return a nul-terminated string, or null in case of error.
193  * The result must be freed using free() - as with the strdup() function.
194  */
195 char *ToLocaleDup (const char *utf8)
196 {
197 #ifdef ASSUME_UTF8
198     return strdup (utf8);
199 #else
200     return locale_dup (utf8, false);
201 #endif
202 }
203
204 /**
205  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
206  * appropriate conversion to local encoding.
207  */
208 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
209 {
210     char *utf8;
211     int res = vasprintf( &utf8, fmt, ap );
212     if( res == -1 )
213         return -1;
214
215 #ifdef ASSUME_UTF8
216     *str = utf8;
217 #else
218     *str = ToLocaleDup( utf8 );
219     free( utf8 );
220 #endif
221     return res;
222 }
223
224 /**
225  * Formats an UTF-8 string as vfprintf(), then print it, with
226  * appropriate conversion to local encoding.
227  */
228 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
229 {
230     char *str;
231     int res = utf8_vasprintf( &str, fmt, ap );
232     if( res == -1 )
233         return -1;
234
235     fputs( str, stream );
236     free( str );
237     return res;
238 }
239
240 /**
241  * Formats an UTF-8 string as fprintf(), then print it, with
242  * appropriate conversion to local encoding.
243  */
244 int utf8_fprintf( FILE *stream, const char *fmt, ... )
245 {
246     va_list ap;
247     int res;
248
249     va_start( ap, fmt );
250     res = utf8_vfprintf( stream, fmt, ap );
251     va_end( ap );
252     return res;
253 }
254
255
256 static char *CheckUTF8( char *str, char rep )
257 {
258     uint8_t *ptr = (uint8_t *)str;
259     assert (str != NULL);
260
261     for (;;)
262     {
263         uint8_t c = ptr[0];
264
265         if (c == '\0')
266             break;
267
268         if (c > 0xF4)
269             goto error;
270
271         int charlen = clz8 (c ^ 0xFF);
272         switch (charlen)
273         {
274             case 0: // 7-bit ASCII character -> OK
275                 ptr++;
276                 continue;
277
278             case 1: // continuation byte -> error
279                 goto error;
280         }
281
282         assert (charlen >= 2 && charlen <= 4);
283
284         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
285         for (int i = 1; i < charlen; i++)
286         {
287             assert (cp < (1 << 26));
288             c = ptr[i];
289
290             if ((c >> 6) != 2) // not a continuation byte
291                 goto error;
292
293             cp = (cp << 6) | (ptr[i] & 0x3f);
294         }
295
296         switch (charlen)
297         {
298             case 4:
299                 if (cp > 0x10FFFF) // beyond Unicode
300                     goto error;
301             case 3:
302                 if (cp >= 0xD800 && cp < 0xC000) // UTF-16 surrogate
303                     goto error;
304             case 2:
305                 if (cp < 128) // ASCII overlong
306                     goto error;
307                 if (cp < (1u << (5 * charlen - 3))) // overlong
308                     goto error;
309         }
310         ptr += charlen;
311         continue;
312
313     error:
314         if (rep == 0)
315             return NULL;
316         *ptr++ = rep;
317         str = NULL;
318     }
319
320     return str;
321 }
322
323 /**
324  * Replaces invalid/overlong UTF-8 sequences with question marks.
325  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
326  * so we don't try that, even though it would be less disruptive.
327  *
328  * @return str if it was valid UTF-8, NULL if not.
329  */
330 char *EnsureUTF8( char *str )
331 {
332     return CheckUTF8( str, '?' );
333 }
334
335
336 /**
337  * Checks whether a string is a valid UTF-8 byte sequence.
338  *
339  * @param str nul-terminated string to be checked
340  *
341  * @return str if it was valid UTF-8, NULL if not.
342  */
343 const char *IsUTF8( const char *str )
344 {
345     return CheckUTF8( (char *)str, 0 );
346 }
347
348 /**
349  * Converts a string from the given character encoding to utf-8.
350  *
351  * @return a nul-terminated utf-8 string, or null in case of error.
352  * The result must be freed using free().
353  */
354 char *FromCharset(const char *charset, const void *data, size_t data_size)
355 {
356     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
357     if (handle == (vlc_iconv_t)(-1))
358         return NULL;
359
360     char *out = NULL;
361     for(unsigned mul = 4; mul < 8; mul++ )
362     {
363         size_t in_size = data_size;
364         const char *in = data;
365         size_t out_max = mul * data_size;
366         char *tmp = out = malloc (1 + out_max);
367         if (!out)
368             break;
369
370         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
371             *tmp = '\0';
372             break;
373         }
374         free(out);
375         out = NULL;
376
377         if (errno != E2BIG)
378             break;
379     }
380     vlc_iconv_close(handle);
381     return out;
382 }
383