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.
38 g_convert_error_quark()
42 quark = g_quark_from_static_string ("g_convert_error");
47 #if defined(USE_LIBICONV) && !defined (_LIBICONV_H)
48 #error libiconv in use but included iconv.h not from libiconv
50 #if !defined(USE_LIBICONV) && defined (_LIBICONV_H)
51 #error libiconv not in use but included iconv.h is from libiconv
55 g_iconv_open (const gchar *to_codeset,
56 const gchar *from_codeset)
58 iconv_t cd = iconv_open (to_codeset, from_codeset);
64 g_iconv (GIConv converter,
68 size_t *outbytes_left)
70 iconv_t cd = (iconv_t)converter;
72 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
76 g_iconv_close (GIConv converter)
78 iconv_t cd = (iconv_t)converter;
80 return iconv_close (cd);
84 open_converter (const gchar *to_codeset,
85 const gchar *from_codeset,
88 GIConv cd = g_iconv_open (to_codeset, from_codeset);
90 if (cd == (iconv_t) -1)
92 /* Something went wrong. */
94 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
95 _("Conversion from character set `%s' to `%s' is not supported"),
96 from_codeset, to_codeset);
98 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
99 _("Could not open converter from `%s' to `%s': %s"),
100 from_codeset, to_codeset, strerror (errno));
109 * @str: the string to convert
110 * @len: the length of the string
111 * @to_codeset: name of character set into which to convert @str
112 * @from_codeset: character set of @str.
113 * @bytes_read: location to store the number of bytes in the
114 * input string that were successfully converted, or %NULL.
115 * Even if the conversion was succesful, this may be
116 * less than len if there were partial characters
117 * at the end of the input. If the error
118 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
119 * stored will the byte fofset after the last valid
121 * @bytes_written: the stored in the output buffer (not including the
123 * @error: location to store the error occuring, or %NULL to ignore
124 * errors. Any of the errors in #GConvertError may occur.
126 * Convert a string from one character set to another.
128 * Return value: If the conversion was successful, a newly allocated
129 * NUL-terminated string, which must be freed with
130 * g_free. Otherwise %NULL and @error will be set.
133 g_convert (const gchar *str,
135 const gchar *to_codeset,
136 const gchar *from_codeset,
144 size_t inbytes_remaining;
145 size_t outbytes_remaining;
149 gboolean have_error = FALSE;
151 g_return_val_if_fail (str != NULL, NULL);
152 g_return_val_if_fail (to_codeset != NULL, NULL);
153 g_return_val_if_fail (from_codeset != NULL, NULL);
155 cd = open_converter (to_codeset, from_codeset, error);
157 if (cd == (GIConv) -1)
172 inbytes_remaining = len;
174 /* Due to a GLIBC bug, round outbuf_size up to a multiple of 4 */
175 /* + 1 for nul in case len == 1 */
176 outbuf_size = ((len + 3) & ~3) + 1;
178 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
179 outp = dest = g_malloc (outbuf_size);
183 err = g_iconv (cd, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
185 if (err == (size_t) -1)
190 /* Incomplete text, do not report an error */
194 size_t used = outp - dest;
196 /* glibc's iconv can return E2BIG even if there is space
197 * remaining if an internal buffer is exhausted. The
198 * folllowing is a heuristic to catch this. The 16 is
201 if (used + 16 > outbuf_size)
203 outbuf_size = (outbuf_size - 1) * 2 + 1;
204 dest = g_realloc (dest, outbuf_size);
207 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
213 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
214 _("Invalid byte sequence in conversion input"));
218 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
219 _("Error during conversion: %s"),
231 *bytes_read = p - str;
234 if ((p - str) != len)
236 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
237 _("Partial character sequence at end of input"));
243 *bytes_written = outp - dest; /* Doesn't include '\0' */
255 * g_convert_with_fallback:
256 * @str: the string to convert
257 * @len: the length of the string
258 * @to_codeset: name of character set into which to convert @str
259 * @from_codeset: character set of @str.
260 * @fallback: UTF-8 string to use in place of character not
261 * present in the target encoding. (This must be
262 * in the target encoding), if %NULL, characters
263 * not in the target encoding will be represented
264 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
265 * @bytes_read: location to store the number of bytes in the
266 * input string that were successfully converted, or %NULL.
267 * Even if the conversion was succesful, this may be
268 * less than len if there were partial characters
269 * at the end of the input. If the error
270 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
271 * stored will the byte fofset after the last valid
273 * @bytes_written: the stored in the output buffer (not including the
275 * @error: location to store the error occuring, or %NULL to ignore
276 * errors. Any of the errors in #GConvertError may occur.
278 * Convert a string from one character set to another, possibly
279 * including fallback sequences for characters not representable
280 * in the output. Note that it is not guaranteed that the specification
281 * for the fallback sequences in @fallback will be honored. Some
282 * systems may do a approximate conversion from @from_codeset
283 * to @to_codeset in their iconv() functions, in which case GLib
284 * will simply return that approximate conversion.
286 * Return value: If the conversion was successful, a newly allocated
287 * NUL-terminated string, which must be freed with
288 * g_free. Otherwise %NULL and @error will be set.
291 g_convert_with_fallback (const gchar *str,
293 const gchar *to_codeset,
294 const gchar *from_codeset,
303 const gchar *insert_str = NULL;
305 int inbytes_remaining;
306 const gchar *save_p = NULL;
307 size_t save_inbytes = 0;
308 size_t outbytes_remaining;
312 gboolean have_error = FALSE;
313 gboolean done = FALSE;
315 GError *local_error = NULL;
317 g_return_val_if_fail (str != NULL, NULL);
318 g_return_val_if_fail (to_codeset != NULL, NULL);
319 g_return_val_if_fail (from_codeset != NULL, NULL);
324 /* Try an exact conversion; we only proceed if this fails
325 * due to an illegal sequence in the input string.
327 dest = g_convert (str, len, to_codeset, from_codeset,
328 bytes_read, bytes_written, &local_error);
332 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
334 g_propagate_error (error, local_error);
338 g_error_free (local_error);
340 /* No go; to proceed, we need a converter from "UTF-8" to
341 * to_codeset, and the string as UTF-8.
343 cd = open_converter (to_codeset, "UTF-8", error);
344 if (cd == (GIConv) -1)
355 utf8 = g_convert (str, len, "UTF-8", from_codeset,
356 bytes_read, &inbytes_remaining, error);
360 /* Now the heart of the code. We loop through the UTF-8 string, and
361 * whenever we hit an offending character, we form fallback, convert
362 * the fallback to the target codeset, and then go back to
363 * converting the original string after finishing with the fallback.
365 * The variables save_p and save_inbytes store the input state
366 * for the original string while we are converting the fallback
369 /* Due to a GLIBC bug, round outbuf_size up to a multiple of 4 */
370 /* + 1 for nul in case len == 1 */
371 outbuf_size = ((len + 3) & ~3) + 1;
372 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
373 outp = dest = g_malloc (outbuf_size);
375 while (!done && !have_error)
377 size_t inbytes_tmp = inbytes_remaining;
378 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
379 inbytes_remaining = inbytes_tmp;
381 if (err == (size_t) -1)
386 g_assert_not_reached();
390 size_t used = outp - dest;
392 /* glibc's iconv can return E2BIG even if there is space
393 * remaining if an internal buffer is exhausted. The
394 * folllowing is a heuristic to catch this. The 16 is
397 if (used + 16 > outbuf_size)
399 outbuf_size = (outbuf_size - 1) * 2 + 1;
400 dest = g_realloc (dest, outbuf_size);
403 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
411 /* Error converting fallback string - fatal
413 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
414 _("Cannot convert fallback '%s' to codeset '%s'"),
415 insert_str, to_codeset);
423 gunichar ch = g_utf8_get_char (p);
424 insert_str = g_strdup_printf ("\\x{%0*X}",
425 (ch < 0x10000) ? 4 : 6,
429 insert_str = fallback;
431 save_p = g_utf8_next_char (p);
432 save_inbytes = inbytes_remaining - (save_p - p);
434 inbytes_remaining = strlen (p);
438 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
439 _("Error during conversion: %s"),
450 g_free ((gchar *)insert_str);
452 inbytes_remaining = save_inbytes;
467 *bytes_written = outp - str; /* Doesn't include '\0' */
473 if (save_p && !fallback)
474 g_free ((gchar *)insert_str);
490 * @opsysstring: a string in the encoding of the current locale
491 * @len: the length of the string, or -1 if the string is
493 * @bytes_read: location to store the number of bytes in the
494 * input string that were successfully converted, or %NULL.
495 * Even if the conversion was succesful, this may be
496 * less than len if there were partial characters
497 * at the end of the input. If the error
498 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
499 * stored will the byte fofset after the last valid
501 * @bytes_written: the stored in the output buffer (not including the
503 * @error: location to store the error occuring, or %NULL to ignore
504 * errors. Any of the errors in #GConvertError may occur.
506 * Converts a string which is in the encoding used for strings by
507 * the C runtime (usually the same as that used by the operating
508 * system) in the current locale into a UTF-8 string.
510 * Return value: The converted string, or %NULL on an error.
513 g_locale_to_utf8 (const gchar *opsysstring,
521 gint i, clen, total_len, wclen, first;
527 len = strlen (opsysstring);
529 wcs = g_new (wchar_t, len);
530 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
534 for (i = 0; i < wclen; i++)
542 else if (wc < 0x10000)
544 else if (wc < 0x200000)
546 else if (wc < 0x4000000)
552 result = g_malloc (total_len + 1);
556 for (i = 0; i < wclen; i++)
570 else if (wc < 0x10000)
575 else if (wc < 0x200000)
580 else if (wc < 0x4000000)
594 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
595 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
596 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
597 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
598 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
599 case 1: bp[0] = wc | first;
611 *bytes_written = total_len;
619 if (g_get_charset (&charset))
620 return g_strdup (opsysstring);
622 str = g_convert (opsysstring, len,
623 "UTF-8", charset, bytes_read, bytes_written, error);
630 * g_locale_from_utf8:
631 * @utf8string: a UTF-8 encoded string
632 * @len: the length of the string, or -1 if the string is
634 * @bytes_read: location to store the number of bytes in the
635 * input string that were successfully converted, or %NULL.
636 * Even if the conversion was succesful, this may be
637 * less than len if there were partial characters
638 * at the end of the input. If the error
639 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
640 * stored will the byte fofset after the last valid
642 * @bytes_written: the stored in the output buffer (not including the
644 * @error: location to store the error occuring, or %NULL to ignore
645 * errors. Any of the errors in #GConvertError may occur.
647 * Converts a string from UTF-8 to the encoding used for strings by
648 * the C runtime (usually the same as that used by the operating
649 * system) in the current locale.
651 * Return value: The converted string, or %NULL on an error.
654 g_locale_from_utf8 (const gchar *utf8string,
662 gint i, mask, clen, mblen;
669 len = strlen (utf8string);
671 /* First convert to wide chars */
672 cp = (guchar *) utf8string;
675 wcs = g_new (wchar_t, len + 1);
687 else if ((c & 0xe0) == 0xc0)
692 else if ((c & 0xf0) == 0xe0)
697 else if ((c & 0xf8) == 0xf0)
702 else if ((c & 0xfc) == 0xf8)
707 else if ((c & 0xfc) == 0xfc)
724 *wcp = (cp[0] & mask);
725 for (i = 1; i < clen; i++)
727 if ((cp[i] & 0xc0) != 0x80)
733 *wcp |= (cp[i] & 0x3f);
746 /* n is the number of wide chars constructed */
748 /* Convert to a string in the current ANSI codepage */
750 result = g_new (gchar, 3 * n + 1);
751 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
758 *bytes_written = mblen;
764 gchar *charset, *str;
766 if (g_get_charset (&charset))
767 return g_strdup (utf8string);
769 str = g_convert (utf8string, strlen (utf8string),
770 charset, "UTF-8", bytes_read, bytes_written, error);
778 * g_filename_to_utf8:
779 * @opsysstring: a string in the encoding for filenames
780 * @len: the length of the string, or -1 if the string is
782 * @bytes_read: location to store the number of bytes in the
783 * input string that were successfully converted, or %NULL.
784 * Even if the conversion was succesful, this may be
785 * less than len if there were partial characters
786 * at the end of the input. If the error
787 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
788 * stored will the byte fofset after the last valid
790 * @bytes_written: the stored in the output buffer (not including the
792 * @error: location to store the error occuring, or %NULL to ignore
793 * errors. Any of the errors in #GConvertError may occur.
795 * Converts a string which is in the encoding used for filenames
796 * into a UTF-8 string.
798 * Return value: The converted string, or %NULL on an error.
801 g_filename_to_utf8 (const gchar *opsysstring,
808 return g_locale_to_utf8 (opsysstring, len,
809 bytes_read, bytes_written,
812 if (getenv ("G_BROKEN_FILENAMES"))
813 return g_locale_to_utf8 (opsysstring, len,
814 bytes_read, bytes_written,
817 if (bytes_read || bytes_written)
819 gint len = strlen (opsysstring);
824 *bytes_written = len;
828 return g_strdup (opsysstring);
830 return g_strndup (opsysstring, len);
835 * g_filename_from_utf8:
836 * @utf8string: a UTF-8 encoded string
837 * @len: the length of the string, or -1 if the string is
839 * @bytes_read: location to store the number of bytes in the
840 * input string that were successfully converted, or %NULL.
841 * Even if the conversion was succesful, this may be
842 * less than len if there were partial characters
843 * at the end of the input. If the error
844 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
845 * stored will the byte fofset after the last valid
847 * @bytes_written: the stored in the output buffer (not including the
849 * @error: location to store the error occuring, or %NULL to ignore
850 * errors. Any of the errors in #GConvertError may occur.
852 * Converts a string from UTF-8 to the encoding used for filenames.
854 * Return value: The converted string, or %NULL on an error.
857 g_filename_from_utf8 (const gchar *utf8string,
864 return g_locale_from_utf8 (utf8string, len,
865 bytes_read, bytes_written,
868 if (getenv ("G_BROKEN_FILENAMES"))
869 return g_locale_from_utf8 (utf8string, len,
870 bytes_read, bytes_written,
873 if (bytes_read || bytes_written)
875 gint len = strlen (utf8string);
880 *bytes_written = len;
884 return g_strdup (utf8string);
886 return g_strndup (utf8string, len);