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.
37 g_convert_error_quark()
41 quark = g_quark_from_static_string ("g_convert_error");
46 open_converter (const gchar *to_codeset,
47 const gchar *from_codeset,
50 iconv_t cd = iconv_open (to_codeset, from_codeset);
52 if (cd == (iconv_t) -1)
54 /* Something went wrong. */
56 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
57 _("Conversion from character set `%s' to `%s' is not supported"),
58 from_codeset, to_codeset);
60 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
61 _("Could not open converter from `%s' to `%s': %s"),
62 from_codeset, to_codeset, strerror (errno));
71 * @str: the string to convert
72 * @len: the length of the string
73 * @to_codeset: name of character set into which to convert @str
74 * @from_codeset: character set of @str.
75 * @bytes_read: location to store the number of bytes in the
76 * input string that were successfully converted, or %NULL.
77 * Even if the conversion was succesful, this may be
78 * less than len if there were partial characters
79 * at the end of the input. If the error
80 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
81 * stored will the byte fofset after the last valid
83 * @bytes_written: the stored in the output buffer (not including the
85 * @error: location to store the error occuring, or %NULL to ignore
86 * errors. Any of the errors in #GConvertError may occur.
88 * Convert a string from one character set to another.
90 * Return value: If the conversion was successful, a newly allocated
91 * NUL-terminated string, which must be freed with
92 * g_free. Otherwise %NULL and @error will be set.
95 g_convert (const gchar *str,
97 const gchar *to_codeset,
98 const gchar *from_codeset,
106 size_t inbytes_remaining;
107 size_t outbytes_remaining;
111 gboolean have_error = FALSE;
113 g_return_val_if_fail (str != NULL, NULL);
114 g_return_val_if_fail (to_codeset != NULL, NULL);
115 g_return_val_if_fail (from_codeset != NULL, NULL);
117 cd = open_converter (to_codeset, from_codeset, error);
119 if (cd == (iconv_t) -1)
134 inbytes_remaining = len;
135 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
136 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
137 outp = dest = g_malloc (outbuf_size);
141 err = iconv (cd, &p, &inbytes_remaining, &outp, &outbytes_remaining);
143 if (err == (size_t) -1)
148 /* Incomplete text, do not report an error */
152 size_t used = outp - dest;
154 dest = g_realloc (dest, outbuf_size);
157 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
162 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
163 _("Invalid byte sequence in conversion input"));
167 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
168 _("Error during conversion: %s"),
180 *bytes_read = p - str;
183 if ((p - str) != len)
185 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
186 _("Partial character sequence at end of input"));
192 *bytes_written = outp - dest; /* Doesn't include '\0' */
204 * g_convert_with_fallback:
205 * @str: the string to convert
206 * @len: the length of the string
207 * @to_codeset: name of character set into which to convert @str
208 * @from_codeset: character set of @str.
209 * @fallback: UTF-8 string to use in place of character not
210 * present in the target encoding. (This must be
211 * in the target encoding), if %NULL, characters
212 * not in the target encoding will be represented
213 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
214 * @bytes_read: location to store the number of bytes in the
215 * input string that were successfully converted, or %NULL.
216 * Even if the conversion was succesful, this may be
217 * less than len if there were partial characters
218 * at the end of the input. If the error
219 * G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
220 * stored will the byte fofset after the last valid
222 * @bytes_written: the stored in the output buffer (not including the
224 * @error: location to store the error occuring, or %NULL to ignore
225 * errors. Any of the errors in #GConvertError may occur.
227 * Convert a string from one character set to another, possibly
228 * including fallback sequences for characters not representable
229 * in the output. Note that it is not guaranteed that the specification
230 * for the fallback sequences in @fallback will be honored. Some
231 * systems may do a approximate conversion from @from_codeset
232 * to @to_codeset in their iconv() functions, in which case GLib
233 * will simply return that approximate conversion.
235 * Return value: If the conversion was successful, a newly allocated
236 * NUL-terminated string, which must be freed with
237 * g_free. Otherwise %NULL and @error will be set.
240 g_convert_with_fallback (const gchar *str,
242 const gchar *to_codeset,
243 const gchar *from_codeset,
252 const gchar *insert_str = NULL;
254 int inbytes_remaining;
255 const gchar *save_p = NULL;
256 size_t save_inbytes = 0;
257 size_t outbytes_remaining;
261 gboolean have_error = FALSE;
262 gboolean done = FALSE;
264 GError *local_error = NULL;
266 g_return_val_if_fail (str != NULL, NULL);
267 g_return_val_if_fail (to_codeset != NULL, NULL);
268 g_return_val_if_fail (from_codeset != NULL, NULL);
273 /* Try an exact conversion; we only proceed if this fails
274 * due to an illegal sequence in the input string.
276 dest = g_convert (str, len, to_codeset, from_codeset,
277 bytes_read, bytes_written, &local_error);
281 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
283 g_propagate_error (error, local_error);
287 g_error_free (local_error);
289 /* No go; to proceed, we need a converter from "UTF-8" to
290 * to_codeset, and the string as UTF-8.
292 cd = open_converter (to_codeset, "UTF-8", error);
293 if (cd == (iconv_t) -1)
304 utf8 = g_convert (str, len, "UTF-8", from_codeset,
305 bytes_read, &inbytes_remaining, error);
309 /* Now the heart of the code. We loop through the UTF-8 string, and
310 * whenever we hit an offending character, we form fallback, convert
311 * the fallback to the target codeset, and then go back to
312 * converting the original string after finishing with the fallback.
314 * The variables save_p and save_inbytes store the input state
315 * for the original string while we are converting the fallback
318 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
319 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
320 outp = dest = g_malloc (outbuf_size);
322 while (!done && !have_error)
324 size_t inbytes_tmp = inbytes_remaining;
325 err = iconv (cd, &p, &inbytes_tmp, &outp, &outbytes_remaining);
326 inbytes_remaining = inbytes_tmp;
328 if (err == (size_t) -1)
333 g_assert_not_reached();
337 size_t used = outp - dest;
339 dest = g_realloc (dest, outbuf_size);
342 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
349 /* Error converting fallback string - fatal
351 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
352 _("Cannot convert fallback '%s' to codeset '%s'"),
353 insert_str, to_codeset);
361 gunichar ch = g_utf8_get_char (p);
362 insert_str = g_strdup_printf ("\\x{%0*X}",
363 (ch < 0x10000) ? 4 : 6,
367 insert_str = fallback;
369 save_p = g_utf8_next_char (p);
370 save_inbytes = inbytes_remaining - (save_p - p);
372 inbytes_remaining = strlen (p);
376 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
377 _("Error during conversion: %s"),
388 g_free ((gchar *)insert_str);
390 inbytes_remaining = save_inbytes;
405 *bytes_written = outp - str; /* Doesn't include '\0' */
411 if (save_p && !fallback)
412 g_free ((gchar *)insert_str);
423 * Converts a string which is in the encoding used for strings by
424 * the C runtime (usually the same as that used by the operating
425 * system) in the current locale into a UTF-8 string.
429 g_locale_to_utf8 (const gchar *opsysstring, GError **error)
433 gint i, clen, wclen, first;
434 const gint len = strlen (opsysstring);
439 wcs = g_new (wchar_t, len);
440 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
444 for (i = 0; i < wclen; i++)
452 else if (wc < 0x10000)
454 else if (wc < 0x200000)
456 else if (wc < 0x4000000)
462 result = g_malloc (clen + 1);
466 for (i = 0; i < wclen; i++)
480 else if (wc < 0x10000)
485 else if (wc < 0x200000)
490 else if (wc < 0x4000000)
504 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
505 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
506 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
507 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
508 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
509 case 1: bp[0] = wc | first;
524 if (g_get_charset (&charset))
525 return g_strdup (opsysstring);
527 str = g_convert (opsysstring, strlen (opsysstring),
528 "UTF-8", charset, NULL, NULL, error);
537 * The reverse of g_locale_to_utf8.
541 g_locale_from_utf8 (const gchar *utf8string, GError **error)
545 gint i, mask, clen, mblen;
546 const gint len = strlen (utf8string);
552 /* First convert to wide chars */
553 cp = (guchar *) utf8string;
556 wcs = g_new (wchar_t, len + 1);
568 else if ((c & 0xe0) == 0xc0)
573 else if ((c & 0xf0) == 0xe0)
578 else if ((c & 0xf8) == 0xf0)
583 else if ((c & 0xfc) == 0xf8)
588 else if ((c & 0xfc) == 0xfc)
605 *wcp = (cp[0] & mask);
606 for (i = 1; i < clen; i++)
608 if ((cp[i] & 0xc0) != 0x80)
614 *wcp |= (cp[i] & 0x3f);
627 /* n is the number of wide chars constructed */
629 /* Convert to a string in the current ANSI codepage */
631 result = g_new (gchar, 3 * n + 1);
632 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
640 gchar *charset, *str;
642 if (g_get_charset (&charset))
643 return g_strdup (utf8string);
645 str = g_convert (utf8string, strlen (utf8string),
646 charset, "UTF-8", NULL, NULL, error);
653 /* Filenames are in UTF-8 unless specificially requested otherwise */
656 g_filename_to_utf8 (const gchar *string, GError **error)
659 return g_locale_to_utf8 (string, error);
661 if (getenv ("G_BROKEN_FILENAMES"))
662 return g_locale_to_utf8 (string, error);
664 return g_strdup (string);
669 g_filename_from_utf8 (const gchar *string, GError **error)
672 return g_locale_from_utf8 (string, error);
674 if (getenv ("G_BROKEN_FILENAMES"))
675 return g_locale_from_utf8 (string, error);
677 return g_strdup (string);