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 gsize *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,
186 gsize *bytes_written,
192 g_return_val_if_fail (str != NULL, NULL);
193 g_return_val_if_fail (to_codeset != NULL, NULL);
194 g_return_val_if_fail (from_codeset != NULL, NULL);
196 cd = open_converter (to_codeset, from_codeset, error);
198 if (cd == (GIConv) -1)
209 res = g_convert_with_iconv (str, len, cd,
210 bytes_read, bytes_written,
219 * g_convert_with_iconv:
220 * @str: the string to convert
221 * @len: the length of the string
222 * @converter: conversion descriptor from g_iconv_open()
223 * @bytes_read: location to store the number of bytes in the
224 * input string that were successfully converted, or %NULL.
225 * Even if the conversion was succesful, this may be
226 * less than len if there were partial characters
227 * at the end of the input. If the error
228 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
229 * stored will the byte fofset after the last valid
231 * @bytes_written: the stored in the output buffer (not including the
233 * @error: location to store the error occuring, or %NULL to ignore
234 * errors. Any of the errors in #GConvertError may occur.
236 * Convert a string from one character set to another.
238 * Return value: If the conversion was successful, a newly allocated
239 * NUL-terminated string, which must be freed with
240 * g_free. Otherwise %NULL and @error will be set.
243 g_convert_with_iconv (const gchar *str,
247 gsize *bytes_written,
253 gsize inbytes_remaining;
254 gsize outbytes_remaining;
257 gboolean have_error = FALSE;
259 g_return_val_if_fail (str != NULL, NULL);
260 g_return_val_if_fail (converter != (GIConv) -1, NULL);
266 inbytes_remaining = len;
267 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
269 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
270 outp = dest = g_malloc (outbuf_size);
274 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
276 if (err == (size_t) -1)
281 /* Incomplete text, do not report an error */
285 size_t used = outp - dest;
288 dest = g_realloc (dest, outbuf_size);
291 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
296 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
297 _("Invalid byte sequence in conversion input"));
301 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
302 _("Error during conversion: %s"),
312 *bytes_read = p - str;
315 if ((p - str) != len)
319 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
320 _("Partial character sequence at end of input"));
327 *bytes_written = outp - dest; /* Doesn't include '\0' */
339 * g_convert_with_fallback:
340 * @str: the string to convert
341 * @len: the length of the string
342 * @to_codeset: name of character set into which to convert @str
343 * @from_codeset: character set of @str.
344 * @fallback: UTF-8 string to use in place of character not
345 * present in the target encoding. (This must be
346 * in the target encoding), if %NULL, characters
347 * not in the target encoding will be represented
348 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
349 * @bytes_read: location to store the number of bytes in the
350 * input string that were successfully converted, or %NULL.
351 * Even if the conversion was succesful, this may be
352 * less than len if there were partial characters
353 * at the end of the input.
354 * @bytes_written: the stored in the output buffer (not including the
356 * @error: location to store the error occuring, or %NULL to ignore
357 * errors. Any of the errors in #GConvertError may occur.
359 * Convert a string from one character set to another, possibly
360 * including fallback sequences for characters not representable
361 * in the output. Note that it is not guaranteed that the specification
362 * for the fallback sequences in @fallback will be honored. Some
363 * systems may do a approximate conversion from @from_codeset
364 * to @to_codeset in their iconv() functions, in which case GLib
365 * will simply return that approximate conversion.
367 * Return value: If the conversion was successful, a newly allocated
368 * NUL-terminated string, which must be freed with
369 * g_free. Otherwise %NULL and @error will be set.
372 g_convert_with_fallback (const gchar *str,
374 const gchar *to_codeset,
375 const gchar *from_codeset,
378 gsize *bytes_written,
384 const gchar *insert_str = NULL;
386 gsize inbytes_remaining;
387 const gchar *save_p = NULL;
388 gsize save_inbytes = 0;
389 gsize outbytes_remaining;
393 gboolean have_error = FALSE;
394 gboolean done = FALSE;
396 GError *local_error = NULL;
398 g_return_val_if_fail (str != NULL, NULL);
399 g_return_val_if_fail (to_codeset != NULL, NULL);
400 g_return_val_if_fail (from_codeset != NULL, NULL);
405 /* Try an exact conversion; we only proceed if this fails
406 * due to an illegal sequence in the input string.
408 dest = g_convert (str, len, to_codeset, from_codeset,
409 bytes_read, bytes_written, &local_error);
413 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
415 g_propagate_error (error, local_error);
419 g_error_free (local_error);
423 /* No go; to proceed, we need a converter from "UTF-8" to
424 * to_codeset, and the string as UTF-8.
426 cd = open_converter (to_codeset, "UTF-8", error);
427 if (cd == (GIConv) -1)
438 utf8 = g_convert (str, len, "UTF-8", from_codeset,
439 bytes_read, &inbytes_remaining, error);
443 /* Now the heart of the code. We loop through the UTF-8 string, and
444 * whenever we hit an offending character, we form fallback, convert
445 * the fallback to the target codeset, and then go back to
446 * converting the original string after finishing with the fallback.
448 * The variables save_p and save_inbytes store the input state
449 * for the original string while we are converting the fallback
453 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
454 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
455 outp = dest = g_malloc (outbuf_size);
457 while (!done && !have_error)
459 size_t inbytes_tmp = inbytes_remaining;
460 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
461 inbytes_remaining = inbytes_tmp;
463 if (err == (size_t) -1)
468 g_assert_not_reached();
472 size_t used = outp - dest;
475 dest = g_realloc (dest, outbuf_size);
478 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
485 /* Error converting fallback string - fatal
487 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
488 _("Cannot convert fallback '%s' to codeset '%s'"),
489 insert_str, to_codeset);
497 gunichar ch = g_utf8_get_char (p);
498 insert_str = g_strdup_printf ("\\x{%0*X}",
499 (ch < 0x10000) ? 4 : 6,
503 insert_str = fallback;
505 save_p = g_utf8_next_char (p);
506 save_inbytes = inbytes_remaining - (save_p - p);
508 inbytes_remaining = strlen (p);
512 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
513 _("Error during conversion: %s"),
524 g_free ((gchar *)insert_str);
526 inbytes_remaining = save_inbytes;
541 *bytes_written = outp - str; /* Doesn't include '\0' */
547 if (save_p && !fallback)
548 g_free ((gchar *)insert_str);
563 strdup_len (const gchar *string,
565 gsize *bytes_written,
572 real_len = strlen (string);
577 while (real_len < len && string[real_len])
582 *bytes_read = real_len;
584 *bytes_written = real_len;
586 return g_strndup (string, real_len);
591 * @opsysstring: a string in the encoding of the current locale
592 * @len: the length of the string, or -1 if the string is
594 * @bytes_read: location to store the number of bytes in the
595 * input string that were successfully converted, or %NULL.
596 * Even if the conversion was succesful, this may be
597 * less than len if there were partial characters
598 * at the end of the input. If the error
599 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
600 * stored will the byte fofset after the last valid
602 * @bytes_written: the stored in the output buffer (not including the
604 * @error: location to store the error occuring, or %NULL to ignore
605 * errors. Any of the errors in #GConvertError may occur.
607 * Converts a string which is in the encoding used for strings by
608 * the C runtime (usually the same as that used by the operating
609 * system) in the current locale into a UTF-8 string.
611 * Return value: The converted string, or %NULL on an error.
614 g_locale_to_utf8 (const gchar *opsysstring,
617 gsize *bytes_written,
620 #ifdef G_PLATFORM_WIN32
622 gint i, clen, total_len, wclen, first;
628 len = strlen (opsysstring);
630 wcs = g_new (wchar_t, len);
631 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
635 for (i = 0; i < wclen; i++)
643 else if (wc < 0x10000)
645 else if (wc < 0x200000)
647 else if (wc < 0x4000000)
653 result = g_malloc (total_len + 1);
657 for (i = 0; i < wclen; i++)
671 else if (wc < 0x10000)
676 else if (wc < 0x200000)
681 else if (wc < 0x4000000)
695 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
696 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
697 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
698 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
699 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
700 case 1: bp[0] = wc | first;
712 *bytes_written = total_len;
716 #else /* !G_PLATFORM_WIN32 */
720 if (g_get_charset (&charset))
721 return strdup_len (opsysstring, len, bytes_read, bytes_written);
723 return g_convert (opsysstring, len,
724 "UTF-8", charset, bytes_read, bytes_written, error);
726 #endif /* !G_PLATFORM_WIN32 */
730 * g_locale_from_utf8:
731 * @utf8string: a UTF-8 encoded string
732 * @len: the length of the string, or -1 if the string is
734 * @bytes_read: location to store the number of bytes in the
735 * input string that were successfully converted, or %NULL.
736 * Even if the conversion was succesful, this may be
737 * less than len if there were partial characters
738 * at the end of the input. If the error
739 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
740 * stored will the byte fofset after the last valid
742 * @bytes_written: the stored in the output buffer (not including the
744 * @error: location to store the error occuring, or %NULL to ignore
745 * errors. Any of the errors in #GConvertError may occur.
747 * Converts a string from UTF-8 to the encoding used for strings by
748 * the C runtime (usually the same as that used by the operating
749 * system) in the current locale.
751 * Return value: The converted string, or %NULL on an error.
754 g_locale_from_utf8 (const gchar *utf8string,
757 gsize *bytes_written,
760 #ifdef G_PLATFORM_WIN32
762 gint i, mask, clen, mblen;
769 len = strlen (utf8string);
771 /* First convert to wide chars */
772 cp = (guchar *) utf8string;
775 wcs = g_new (wchar_t, len + 1);
787 else if ((c & 0xe0) == 0xc0)
792 else if ((c & 0xf0) == 0xe0)
797 else if ((c & 0xf8) == 0xf0)
802 else if ((c & 0xfc) == 0xf8)
807 else if ((c & 0xfc) == 0xfc)
824 *wcp = (cp[0] & mask);
825 for (i = 1; i < clen; i++)
827 if ((cp[i] & 0xc0) != 0x80)
833 *wcp |= (cp[i] & 0x3f);
846 /* n is the number of wide chars constructed */
848 /* Convert to a string in the current ANSI codepage */
850 result = g_new (gchar, 3 * n + 1);
851 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
858 *bytes_written = mblen;
862 #else /* !G_PLATFORM_WIN32 */
864 const gchar *charset;
866 if (g_get_charset (&charset))
867 return strdup_len (utf8string, len, bytes_read, bytes_written);
869 return g_convert (utf8string, len,
870 charset, "UTF-8", bytes_read, bytes_written, error);
872 #endif /* !G_PLATFORM_WIN32 */
876 * g_filename_to_utf8:
877 * @opsysstring: a string in the encoding for filenames
878 * @len: the length of the string, or -1 if the string is
880 * @bytes_read: location to store the number of bytes in the
881 * input string that were successfully converted, or %NULL.
882 * Even if the conversion was succesful, this may be
883 * less than len if there were partial characters
884 * at the end of the input. If the error
885 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
886 * stored will the byte fofset after the last valid
888 * @bytes_written: the stored in the output buffer (not including the
890 * @error: location to store the error occuring, or %NULL to ignore
891 * errors. Any of the errors in #GConvertError may occur.
893 * Converts a string which is in the encoding used for filenames
894 * into a UTF-8 string.
896 * Return value: The converted string, or %NULL on an error.
899 g_filename_to_utf8 (const gchar *opsysstring,
902 gsize *bytes_written,
905 #ifdef G_PLATFORM_WIN32
906 return g_locale_to_utf8 (opsysstring, len,
907 bytes_read, bytes_written,
909 #else /* !G_PLATFORM_WIN32 */
910 if (getenv ("G_BROKEN_FILENAMES"))
911 return g_locale_to_utf8 (opsysstring, len,
912 bytes_read, bytes_written,
915 return strdup_len (opsysstring, len, bytes_read, bytes_written);
916 #endif /* !G_PLATFORM_WIN32 */
920 * g_filename_from_utf8:
921 * @utf8string: a UTF-8 encoded string
922 * @len: the length of the string, or -1 if the string is
924 * @bytes_read: location to store the number of bytes in the
925 * input string that were successfully converted, or %NULL.
926 * Even if the conversion was succesful, this may be
927 * less than len if there were partial characters
928 * at the end of the input. If the error
929 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
930 * stored will the byte fofset after the last valid
932 * @bytes_written: the stored in the output buffer (not including the
934 * @error: location to store the error occuring, or %NULL to ignore
935 * errors. Any of the errors in #GConvertError may occur.
937 * Converts a string from UTF-8 to the encoding used for filenames.
939 * Return value: The converted string, or %NULL on an error.
942 g_filename_from_utf8 (const gchar *utf8string,
945 gsize *bytes_written,
948 #ifdef G_PLATFORM_WIN32
949 return g_locale_from_utf8 (utf8string, len,
950 bytes_read, bytes_written,
952 #else /* !G_PLATFORM_WIN32 */
953 if (getenv ("G_BROKEN_FILENAMES"))
954 return g_locale_from_utf8 (utf8string, len,
955 bytes_read, bytes_written,
958 return strdup_len (utf8string, len, bytes_read, bytes_written);
959 #endif /* !G_PLATFORM_WIN32 */