1 /* GLIB - Library of useful routines for C programming
3 * gconvert.c: Convert between character sets using iconv
4 * Copyright Red Hat Inc., 2000
5 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
31 #ifdef G_PLATFORM_WIN32
40 g_convert_error_quark()
44 quark = g_quark_from_static_string ("g_convert_error");
49 #if defined(USE_LIBICONV) && !defined (_LIBICONV_H)
50 #error libiconv in use but included iconv.h not from libiconv
52 #if !defined(USE_LIBICONV) && defined (_LIBICONV_H)
53 #error libiconv not in use but included iconv.h is from libiconv
58 * @to_codeset: destination codeset
59 * @from_codeset: source codeset
61 * Same as the standard UNIX routine iconv_open(), but
62 * may be implemented via libiconv on UNIX flavors that lack
63 * a native implementation.
65 * GLib provides g_convert() and g_locale_to_utf8() which are likely
66 * more convenient than the raw iconv wrappers.
68 * Return value: a "conversion descriptor"
71 g_iconv_open (const gchar *to_codeset,
72 const gchar *from_codeset)
74 iconv_t cd = iconv_open (to_codeset, from_codeset);
81 * @converter: conversion descriptor from g_iconv_open()
82 * @inbuf: bytes to convert
83 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
84 * @outbuf: converted output bytes
85 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
87 * Same as the standard UNIX routine iconv(), but
88 * may be implemented via libiconv on UNIX flavors that lack
89 * a native implementation.
91 * GLib provides g_convert() and g_locale_to_utf8() which are likely
92 * more convenient than the raw iconv wrappers.
94 * Return value: count of non-reversible conversions, or -1 on error
97 g_iconv (GIConv converter,
101 size_t *outbytes_left)
103 iconv_t cd = (iconv_t)converter;
105 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
110 * @converter: a conversion descriptor from g_iconv_open()
112 * Same as the standard UNIX routine iconv_close(), but
113 * may be implemented via libiconv on UNIX flavors that lack
114 * a native implementation. Should be called to clean up
115 * the conversion descriptor from iconv_open() when
116 * you are done converting things.
118 * GLib provides g_convert() and g_locale_to_utf8() which are likely
119 * more convenient than the raw iconv wrappers.
121 * Return value: -1 on error, 0 on success
124 g_iconv_close (GIConv converter)
126 iconv_t cd = (iconv_t)converter;
128 return iconv_close (cd);
132 open_converter (const gchar *to_codeset,
133 const gchar *from_codeset,
136 GIConv cd = g_iconv_open (to_codeset, from_codeset);
138 if (cd == (iconv_t) -1)
140 /* Something went wrong. */
142 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
143 _("Conversion from character set `%s' to `%s' is not supported"),
144 from_codeset, to_codeset);
146 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
147 _("Could not open converter from `%s' to `%s': %s"),
148 from_codeset, to_codeset, strerror (errno));
157 * @str: the string to convert
158 * @len: the length of the string
159 * @to_codeset: name of character set into which to convert @str
160 * @from_codeset: character set of @str.
161 * @bytes_read: location to store the number of bytes in the
162 * input string that were successfully converted, or %NULL.
163 * Even if the conversion was succesful, this may be
164 * less than len if there were partial characters
165 * at the end of the input. If the error
166 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
167 * stored will the byte fofset after the last valid
169 * @bytes_written: the stored in the output buffer (not including the
171 * @error: location to store the error occuring, or %NULL to ignore
172 * errors. Any of the errors in #GConvertError may occur.
174 * Convert a string from one character set to another.
176 * Return value: If the conversion was successful, a newly allocated
177 * NUL-terminated string, which must be freed with
178 * g_free. Otherwise %NULL and @error will be set.
181 g_convert (const gchar *str,
183 const gchar *to_codeset,
184 const gchar *from_codeset,
192 size_t inbytes_remaining;
193 size_t outbytes_remaining;
197 gboolean have_error = FALSE;
199 g_return_val_if_fail (str != NULL, NULL);
200 g_return_val_if_fail (to_codeset != NULL, NULL);
201 g_return_val_if_fail (from_codeset != NULL, NULL);
203 cd = open_converter (to_codeset, from_codeset, error);
205 if (cd == (GIConv) -1)
220 inbytes_remaining = len;
222 /* Due to a GLIBC bug, round outbuf_size up to a multiple of 4 */
223 /* + 1 for nul in case len == 1 */
224 outbuf_size = ((len + 3) & ~3) + 1;
226 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
227 outp = dest = g_malloc (outbuf_size);
231 err = g_iconv (cd, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
233 if (err == (size_t) -1)
238 /* Incomplete text, do not report an error */
242 size_t used = outp - dest;
244 /* glibc's iconv can return E2BIG even if there is space
245 * remaining if an internal buffer is exhausted. The
246 * folllowing is a heuristic to catch this. The 16 is
249 if (used + 16 > outbuf_size)
251 outbuf_size = (outbuf_size - 1) * 2 + 1;
252 dest = g_realloc (dest, outbuf_size);
255 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
261 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
262 _("Invalid byte sequence in conversion input"));
266 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
267 _("Error during conversion: %s"),
279 *bytes_read = p - str;
282 if ((p - str) != len)
286 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
287 _("Partial character sequence at end of input"));
294 *bytes_written = outp - dest; /* Doesn't include '\0' */
306 * g_convert_with_fallback:
307 * @str: the string to convert
308 * @len: the length of the string
309 * @to_codeset: name of character set into which to convert @str
310 * @from_codeset: character set of @str.
311 * @fallback: UTF-8 string to use in place of character not
312 * present in the target encoding. (This must be
313 * in the target encoding), if %NULL, characters
314 * not in the target encoding will be represented
315 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
316 * @bytes_read: location to store the number of bytes in the
317 * input string that were successfully converted, or %NULL.
318 * Even if the conversion was succesful, this may be
319 * less than len if there were partial characters
320 * at the end of the input. If the error
321 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
322 * stored will the byte fofset after the last valid
324 * @bytes_written: the stored in the output buffer (not including the
326 * @error: location to store the error occuring, or %NULL to ignore
327 * errors. Any of the errors in #GConvertError may occur.
329 * Convert a string from one character set to another, possibly
330 * including fallback sequences for characters not representable
331 * in the output. Note that it is not guaranteed that the specification
332 * for the fallback sequences in @fallback will be honored. Some
333 * systems may do a approximate conversion from @from_codeset
334 * to @to_codeset in their iconv() functions, in which case GLib
335 * will simply return that approximate conversion.
337 * Return value: If the conversion was successful, a newly allocated
338 * NUL-terminated string, which must be freed with
339 * g_free. Otherwise %NULL and @error will be set.
342 g_convert_with_fallback (const gchar *str,
344 const gchar *to_codeset,
345 const gchar *from_codeset,
354 const gchar *insert_str = NULL;
356 int inbytes_remaining;
357 const gchar *save_p = NULL;
358 size_t save_inbytes = 0;
359 size_t outbytes_remaining;
363 gboolean have_error = FALSE;
364 gboolean done = FALSE;
366 GError *local_error = NULL;
368 g_return_val_if_fail (str != NULL, NULL);
369 g_return_val_if_fail (to_codeset != NULL, NULL);
370 g_return_val_if_fail (from_codeset != NULL, NULL);
375 /* Try an exact conversion; we only proceed if this fails
376 * due to an illegal sequence in the input string.
378 dest = g_convert (str, len, to_codeset, from_codeset,
379 bytes_read, bytes_written, &local_error);
383 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
385 g_propagate_error (error, local_error);
389 g_error_free (local_error);
393 /* No go; to proceed, we need a converter from "UTF-8" to
394 * to_codeset, and the string as UTF-8.
396 cd = open_converter (to_codeset, "UTF-8", error);
397 if (cd == (GIConv) -1)
408 utf8 = g_convert (str, len, "UTF-8", from_codeset,
409 bytes_read, &inbytes_remaining, error);
413 /* Now the heart of the code. We loop through the UTF-8 string, and
414 * whenever we hit an offending character, we form fallback, convert
415 * the fallback to the target codeset, and then go back to
416 * converting the original string after finishing with the fallback.
418 * The variables save_p and save_inbytes store the input state
419 * for the original string while we are converting the fallback
422 /* Due to a GLIBC bug, round outbuf_size up to a multiple of 4 */
423 /* + 1 for nul in case len == 1 */
424 outbuf_size = ((len + 3) & ~3) + 1;
425 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
426 outp = dest = g_malloc (outbuf_size);
428 while (!done && !have_error)
430 size_t inbytes_tmp = inbytes_remaining;
431 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
432 inbytes_remaining = inbytes_tmp;
434 if (err == (size_t) -1)
439 g_assert_not_reached();
443 size_t used = outp - dest;
445 /* glibc's iconv can return E2BIG even if there is space
446 * remaining if an internal buffer is exhausted. The
447 * folllowing is a heuristic to catch this. The 16 is
450 if (used + 16 > outbuf_size)
452 outbuf_size = (outbuf_size - 1) * 2 + 1;
453 dest = g_realloc (dest, outbuf_size);
456 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
464 /* Error converting fallback string - fatal
466 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
467 _("Cannot convert fallback '%s' to codeset '%s'"),
468 insert_str, to_codeset);
476 gunichar ch = g_utf8_get_char (p);
477 insert_str = g_strdup_printf ("\\x{%0*X}",
478 (ch < 0x10000) ? 4 : 6,
482 insert_str = fallback;
484 save_p = g_utf8_next_char (p);
485 save_inbytes = inbytes_remaining - (save_p - p);
487 inbytes_remaining = strlen (p);
491 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
492 _("Error during conversion: %s"),
503 g_free ((gchar *)insert_str);
505 inbytes_remaining = save_inbytes;
520 *bytes_written = outp - str; /* Doesn't include '\0' */
526 if (save_p && !fallback)
527 g_free ((gchar *)insert_str);
543 * @opsysstring: a string in the encoding of the current locale
544 * @len: the length of the string, or -1 if the string is
546 * @bytes_read: location to store the number of bytes in the
547 * input string that were successfully converted, or %NULL.
548 * Even if the conversion was succesful, this may be
549 * less than len if there were partial characters
550 * at the end of the input. If the error
551 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
552 * stored will the byte fofset after the last valid
554 * @bytes_written: the stored in the output buffer (not including the
556 * @error: location to store the error occuring, or %NULL to ignore
557 * errors. Any of the errors in #GConvertError may occur.
559 * Converts a string which is in the encoding used for strings by
560 * the C runtime (usually the same as that used by the operating
561 * system) in the current locale into a UTF-8 string.
563 * Return value: The converted string, or %NULL on an error.
566 g_locale_to_utf8 (const gchar *opsysstring,
572 #ifdef G_PLATFORM_WIN32
574 gint i, clen, total_len, wclen, first;
580 len = strlen (opsysstring);
582 wcs = g_new (wchar_t, len);
583 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
587 for (i = 0; i < wclen; i++)
595 else if (wc < 0x10000)
597 else if (wc < 0x200000)
599 else if (wc < 0x4000000)
605 result = g_malloc (total_len + 1);
609 for (i = 0; i < wclen; i++)
623 else if (wc < 0x10000)
628 else if (wc < 0x200000)
633 else if (wc < 0x4000000)
647 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
648 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
649 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
650 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
651 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
652 case 1: bp[0] = wc | first;
664 *bytes_written = total_len;
668 #else /* !G_PLATFORM_WIN32 */
672 if (g_get_charset (&charset))
673 return g_strdup (opsysstring);
675 str = g_convert (opsysstring, len,
676 "UTF-8", charset, bytes_read, bytes_written, error);
679 #endif /* !G_PLATFORM_WIN32 */
683 * g_locale_from_utf8:
684 * @utf8string: a UTF-8 encoded string
685 * @len: the length of the string, or -1 if the string is
687 * @bytes_read: location to store the number of bytes in the
688 * input string that were successfully converted, or %NULL.
689 * Even if the conversion was succesful, this may be
690 * less than len if there were partial characters
691 * at the end of the input. If the error
692 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
693 * stored will the byte fofset after the last valid
695 * @bytes_written: the stored in the output buffer (not including the
697 * @error: location to store the error occuring, or %NULL to ignore
698 * errors. Any of the errors in #GConvertError may occur.
700 * Converts a string from UTF-8 to the encoding used for strings by
701 * the C runtime (usually the same as that used by the operating
702 * system) in the current locale.
704 * Return value: The converted string, or %NULL on an error.
707 g_locale_from_utf8 (const gchar *utf8string,
713 #ifdef G_PLATFORM_WIN32
715 gint i, mask, clen, mblen;
722 len = strlen (utf8string);
724 /* First convert to wide chars */
725 cp = (guchar *) utf8string;
728 wcs = g_new (wchar_t, len + 1);
740 else if ((c & 0xe0) == 0xc0)
745 else if ((c & 0xf0) == 0xe0)
750 else if ((c & 0xf8) == 0xf0)
755 else if ((c & 0xfc) == 0xf8)
760 else if ((c & 0xfc) == 0xfc)
777 *wcp = (cp[0] & mask);
778 for (i = 1; i < clen; i++)
780 if ((cp[i] & 0xc0) != 0x80)
786 *wcp |= (cp[i] & 0x3f);
799 /* n is the number of wide chars constructed */
801 /* Convert to a string in the current ANSI codepage */
803 result = g_new (gchar, 3 * n + 1);
804 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
811 *bytes_written = mblen;
815 #else /* !G_PLATFORM_WIN32 */
817 gchar *charset, *str;
819 if (g_get_charset (&charset))
820 return g_strdup (utf8string);
822 str = g_convert (utf8string, strlen (utf8string),
823 charset, "UTF-8", bytes_read, bytes_written, error);
827 #endif /* !G_PLATFORM_WIN32 */
831 * g_filename_to_utf8:
832 * @opsysstring: a string in the encoding for filenames
833 * @len: the length of the string, or -1 if the string is
835 * @bytes_read: location to store the number of bytes in the
836 * input string that were successfully converted, or %NULL.
837 * Even if the conversion was succesful, this may be
838 * less than len if there were partial characters
839 * at the end of the input. If the error
840 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
841 * stored will the byte fofset after the last valid
843 * @bytes_written: the stored in the output buffer (not including the
845 * @error: location to store the error occuring, or %NULL to ignore
846 * errors. Any of the errors in #GConvertError may occur.
848 * Converts a string which is in the encoding used for filenames
849 * into a UTF-8 string.
851 * Return value: The converted string, or %NULL on an error.
854 g_filename_to_utf8 (const gchar *opsysstring,
860 #ifdef G_PLATFORM_WIN32
861 return g_locale_to_utf8 (opsysstring, len,
862 bytes_read, bytes_written,
864 #else /* !G_PLATFORM_WIN32 */
865 if (getenv ("G_BROKEN_FILENAMES"))
866 return g_locale_to_utf8 (opsysstring, len,
867 bytes_read, bytes_written,
870 if (bytes_read || bytes_written)
872 gint len = strlen (opsysstring);
877 *bytes_written = len;
881 return g_strdup (opsysstring);
883 return g_strndup (opsysstring, len);
884 #endif /* !G_PLATFORM_WIN32 */
888 * g_filename_from_utf8:
889 * @utf8string: a UTF-8 encoded string
890 * @len: the length of the string, or -1 if the string is
892 * @bytes_read: location to store the number of bytes in the
893 * input string that were successfully converted, or %NULL.
894 * Even if the conversion was succesful, this may be
895 * less than len if there were partial characters
896 * at the end of the input. If the error
897 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
898 * stored will the byte fofset after the last valid
900 * @bytes_written: the stored in the output buffer (not including the
902 * @error: location to store the error occuring, or %NULL to ignore
903 * errors. Any of the errors in #GConvertError may occur.
905 * Converts a string from UTF-8 to the encoding used for filenames.
907 * Return value: The converted string, or %NULL on an error.
910 g_filename_from_utf8 (const gchar *utf8string,
916 #ifdef G_PLATFORM_WIN32
917 return g_locale_from_utf8 (utf8string, len,
918 bytes_read, bytes_written,
920 #else /* !G_PLATFORM_WIN32 */
921 if (getenv ("G_BROKEN_FILENAMES"))
922 return g_locale_from_utf8 (utf8string, len,
923 bytes_read, bytes_written,
926 if (bytes_read || bytes_written)
928 gint len = strlen (utf8string);
933 *bytes_written = len;
937 return g_strdup (utf8string);
939 return g_strndup (utf8string, len);
940 #endif /* !G_PLATFORM_WIN32 */