1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2008 Rémi Denis-Courmont
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
39 #include <sys/types.h>
44 #if defined (__APPLE__) || defined (HAVE_MAEMO)
45 /* Define this if the OS always use UTF-8 internally */
46 # define ASSUME_UTF8 1
49 #if defined (ASSUME_UTF8)
51 #elif defined (WIN32) || defined (UNDER_CE)
53 #elif defined (HAVE_ICONV)
56 # error No UTF8 charset conversion implemented on this platform!
59 #if defined (USE_ICONV)
60 # include <langinfo.h>
61 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
63 static void find_charset_once (void)
65 strlcpy (charset, nl_langinfo (CODESET), sizeof (charset));
66 if (!strcasecmp (charset, "ASCII")
67 || !strcasecmp (charset, "ANSI_X3.4-1968"))
68 strcpy (charset, "UTF-8"); /* superset... */
71 static int find_charset (void)
73 static pthread_once_t once = PTHREAD_ONCE_INIT;
74 pthread_once (&once, find_charset_once);
75 return !strcasecmp (charset, "UTF-8");
80 static char *locale_fast (const char *string, bool from)
85 #if defined (USE_ICONV)
87 return (char *)string;
89 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
90 from ? charset : "UTF-8");
91 if (hd == (vlc_iconv_t)(-1))
92 return NULL; /* Uho! */
94 const char *iptr = string;
95 size_t inb = strlen (string);
96 size_t outb = inb * 6 + 1;
97 char output[outb], *optr = output;
99 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
105 vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
108 vlc_iconv_close (hd);
111 assert (*iptr == '\0');
112 assert (*optr == '\0');
113 assert (strlen (output) == (size_t)(optr - output));
114 return strdup (output);
115 #elif defined (USE_MB2MB)
119 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
120 0, string, -1, NULL, 0);
121 wchar_t *wide = malloc (len * sizeof (wchar_t));
125 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
126 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
127 NULL, 0, NULL, NULL);
130 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
136 return (char *)string;
141 static inline char *locale_dup (const char *string, bool from)
145 #if defined (USE_ICONV)
147 return strdup (string);
148 return locale_fast (string, from);
149 #elif defined (USE_MB2MB)
150 return locale_fast (string, from);
153 return strdup (string);
158 * Releases (if needed) a localized or uniformized string.
159 * @param str non-NULL return value from FromLocale() or ToLocale().
161 void LocaleFree (const char *str)
163 #if defined (USE_ICONV)
164 if (!find_charset ())
166 #elif defined (USE_MB2MB)
175 * Converts a string from the system locale character encoding to UTF-8.
177 * @param locale nul-terminated string to convert
179 * @return a nul-terminated UTF-8 string, or NULL in case of error.
180 * To avoid memory leak, you have to pass the result to LocaleFree()
181 * when it is no longer needed.
183 char *FromLocale (const char *locale)
185 return locale_fast (locale, true);
189 * converts a string from the system locale character encoding to utf-8,
190 * the result is always allocated on the heap.
192 * @param locale nul-terminated string to convert
194 * @return a nul-terminated utf-8 string, or null in case of error.
195 * The result must be freed using free() - as with the strdup() function.
197 char *FromLocaleDup (const char *locale)
199 return locale_dup (locale, true);
204 * ToLocale: converts an UTF-8 string to local system encoding.
206 * @param utf8 nul-terminated string to be converted
208 * @return a nul-terminated string, or NULL in case of error.
209 * To avoid memory leak, you have to pass the result to LocaleFree()
210 * when it is no longer needed.
212 char *ToLocale (const char *utf8)
214 return locale_fast (utf8, false);
219 * converts a string from UTF-8 to the system locale character encoding,
220 * the result is always allocated on the heap.
222 * @param utf8 nul-terminated string to convert
224 * @return a nul-terminated string, or null in case of error.
225 * The result must be freed using free() - as with the strdup() function.
227 char *ToLocaleDup (const char *utf8)
229 return locale_dup (utf8, false);
233 * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
234 * appropriate conversion to local encoding.
236 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
239 int res = vasprintf( &utf8, fmt, ap );
243 *str = ToLocaleDup( utf8 );
249 * Formats an UTF-8 string as vfprintf(), then print it, with
250 * appropriate conversion to local encoding.
252 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
255 int res = utf8_vasprintf( &str, fmt, ap );
259 fputs( str, stream );
265 * Formats an UTF-8 string as fprintf(), then print it, with
266 * appropriate conversion to local encoding.
268 int utf8_fprintf( FILE *stream, const char *fmt, ... )
274 res = utf8_vfprintf( stream, fmt, ap );
280 static char *CheckUTF8( char *str, char rep )
282 uint8_t *ptr = (uint8_t *)str;
283 assert (str != NULL);
293 for (int i = 0; i < 7; i++)
294 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
302 case 0: // 7-bit ASCII character -> OK
306 case -1: // 1111111x -> error
307 case 1: // continuation byte -> error
311 assert (charlen >= 2);
313 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
314 for (int i = 1; i < charlen; i++)
316 assert (cp < (1 << 26));
319 if ((c == '\0') // unexpected end of string
320 || ((c >> 6) != 2)) // not a continuation byte
323 cp = (cp << 6) | (ptr[i] & 0x3f);
326 if (cp < 128) // overlong (special case for ASCII)
328 if (cp < (1u << (5 * charlen - 3))) // overlong
345 * Replaces invalid/overlong UTF-8 sequences with question marks.
346 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
347 * so we don't try that, even though it would be less disruptive.
349 * @return str if it was valid UTF-8, NULL if not.
351 char *EnsureUTF8( char *str )
353 return CheckUTF8( str, '?' );
358 * Checks whether a string is a valid UTF-8 byte sequence.
360 * @param str nul-terminated string to be checked
362 * @return str if it was valid UTF-8, NULL if not.
364 const char *IsUTF8( const char *str )
366 return CheckUTF8( (char *)str, 0 );