gconvert.c 62.9 KB
Newer Older
1 2 3 4
/* GLIB - Library of useful routines for C programming
 *
 * gconvert.c: Convert between character sets using iconv
 * Copyright Red Hat Inc., 2000
5
 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com>
6 7 8 9
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20
 */

21
#include "config.h"
22
#include "glibconfig.h"
Owen Taylor's avatar
Owen Taylor committed
23

24
#ifndef G_OS_WIN32
25
#include <iconv.h>
26
#endif
27
#include <errno.h>
28
#include <stdio.h>
29
#include <string.h>
30 31
#include <stdlib.h>

32 33 34 35
#ifdef G_OS_WIN32
#include "win_iconv.c"
#endif

36 37
#ifdef G_PLATFORM_WIN32
#define STRICT
38
#include <windows.h>
39
#undef STRICT
40
#endif
41

Matthias Clasen's avatar
Matthias Clasen committed
42 43
#include "gconvert.h"

44
#include "gcharsetprivate.h"
Matthias Clasen's avatar
Matthias Clasen committed
45 46 47 48
#include "gslist.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
#include "gthread.h"
49
#include "gthreadprivate.h"
Matthias Clasen's avatar
Matthias Clasen committed
50
#include "gunicode.h"
Matthias Clasen's avatar
Matthias Clasen committed
51
#include "gfileutils.h"
Matthias Clasen's avatar
Matthias Clasen committed
52

Owen Taylor's avatar
Owen Taylor committed
53
#include "glibintl.h"
54

55 56
#if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
#error GNU libiconv in use but included iconv.h not from libiconv
57
#endif
58 59
#if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H) \
     && !defined (__APPLE_CC__) && !defined (__LP_64__)
60
#error GNU libiconv not in use but included iconv.h is from libiconv
61 62
#endif

63

64 65 66
/**
 * SECTION:conversions
 * @title: Character Set Conversion
67
 * @short_description: convert strings between different character sets
68
 *
69 70 71
 * The g_convert() family of function wraps the functionality of iconv().
 * In addition to pure character set conversions, GLib has functions to
 * deal with the extra complications of encodings for file names.
72
 *
73 74 75 76 77 78 79
 * ## File Name Encodings
 *
 * Historically, UNIX has not had a defined encoding for file names:
 * a file name is valid as long as it does not have path separators
 * in it ("/"). However, displaying file names may require conversion:
 * from the character set in which they were created, to the character
 * set in which the application operates. Consider the Spanish file name
80
 * "Presentación.sxi". If the application which created it uses
81
 * ISO-8859-1 for its encoding,
82
 * |[
Phillip Wood's avatar
Phillip Wood committed
83
 * Character:  P  r  e  s  e  n  t  a  c  i  ó  n  .  s  x  i
84
 * Hex code:   50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
85
 * ]|
86 87
 * However, if the application use UTF-8, the actual file name on
 * disk would look like this:
88
 * |[
Phillip Wood's avatar
Phillip Wood committed
89
 * Character:  P  r  e  s  e  n  t  a  c  i  ó     n  .  s  x  i
90
 * Hex code:   50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
91
 * ]|
92
 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+ that use
93
 * GLib do the same thing. If you get a file name from the file system,
94 95 96
 * for example, from readdir() or from g_dir_read_name(), and you wish
 * to display the file name to the user, you  will need to convert it
 * into UTF-8. The opposite case is when the user types the name of a
97
 * file they wish to save: the toolkit will give you that string in
98 99 100 101
 * UTF-8 encoding, and you will need to convert it to the character
 * set used for file names before you can create the file with open()
 * or fopen().
 *
102
 * By default, GLib assumes that file names on disk are in UTF-8
103 104
 * encoding. This is a valid assumption for file systems which
 * were created relatively recently: most applications use UTF-8
105
 * encoding for their strings, and that is also what they use for
106
 * the file names they create. However, older file systems may
107
 * still contain file names created in "older" encodings, such as
108
 * ISO-8859-1. In this case, for compatibility reasons, you may want
109
 * to instruct GLib to use that particular encoding for file names
110 111
 * rather than UTF-8. You can do this by specifying the encoding for
 * file names in the [`G_FILENAME_ENCODING`][G_FILENAME_ENCODING]
112
 * environment variable. For example, if your installation uses
113
 * ISO-8859-1 for file names, you can put this in your `~/.profile`:
114
 * |[
115
 * export G_FILENAME_ENCODING=ISO-8859-1
116
 * ]|
117
 * GLib provides the functions g_filename_to_utf8() and
118 119
 * g_filename_from_utf8() to perform the necessary conversions.
 * These functions convert file names from the encoding specified
120 121
 * in `G_FILENAME_ENCODING` to UTF-8 and vice-versa. This
 * [diagram][file-name-encodings-diagram] illustrates how
122 123
 * these functions are used to convert between UTF-8 and the
 * encoding for file names in the file system.
124
 *
125 126 127
 * ## Conversion between file name encodings # {#file-name-encodings-diagram)
 *
 * ![](file-name-encodings.png)
128 129 130
 *
 * ## Checklist for Application Writers
 *
131 132 133
 * This section is a practical summary of the detailed
 * things to do to make sure your applications process file
 * name encodings correctly.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
 * 
 * 1. If you get a file name from the file system from a function
 *    such as readdir() or gtk_file_chooser_get_filename(), you do
 *    not need to do any conversion to pass that file name to
 *    functions like open(), rename(), or fopen() -- those are "raw"
 *    file names which the file system understands.
 *
 * 2. If you need to display a file name, convert it to UTF-8 first
 *    by using g_filename_to_utf8(). If conversion fails, display a
 *    string like "Unknown file name". Do not convert this string back
 *    into the encoding used for file names if you wish to pass it to
 *    the file system; use the original file name instead.
 *
 *    For example, the document window of a word processor could display
 *    "Unknown file name" in its title bar but still let the user save
149 150 151 152
 *    the file, as it would keep the raw file name internally. This
 *    can happen if the user has not set the `G_FILENAME_ENCODING`
 *    environment variable even though he has files whose names are
 *    not encoded in UTF-8.
153 154 155 156 157 158
 *
 * 3. If your user interface lets the user type a file name for saving
 *    or renaming, convert it to the encoding used for file names in
 *    the file system by using g_filename_from_utf8(). Pass the converted
 *    file name to functions like fopen(). If conversion fails, ask the
 *    user to enter a different file name. This can happen if the user
159 160
 *    types Japanese characters when `G_FILENAME_ENCODING` is set to
 *    `ISO-8859-1`, for example.
161 162
 */

163 164 165 166 167 168
/* We try to terminate strings in unknown charsets with this many zero bytes
 * to ensure that multibyte strings really are nul-terminated when we return
 * them from g_convert() and friends.
 */
#define NUL_TERMINATOR_LENGTH 4

169
G_DEFINE_QUARK (g_convert_error, g_convert_error)
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
static gboolean
try_conversion (const char *to_codeset,
		const char *from_codeset,
		iconv_t    *cd)
{
  *cd = iconv_open (to_codeset, from_codeset);

  if (*cd == (iconv_t)-1 && errno == EINVAL)
    return FALSE;
  else
    return TRUE;
}

static gboolean
try_to_aliases (const char **to_aliases,
		const char  *from_codeset,
		iconv_t     *cd)
{
  if (to_aliases)
    {
      const char **p = to_aliases;
      while (*p)
	{
	  if (try_conversion (*p, from_codeset, cd))
	    return TRUE;

	  p++;
	}
    }

  return FALSE;
}

Havoc Pennington's avatar
Havoc Pennington committed
204
/**
205
 * g_iconv_open: (skip)
Havoc Pennington's avatar
Havoc Pennington committed
206 207 208
 * @to_codeset: destination codeset
 * @from_codeset: source codeset
 * 
209
 * Same as the standard UNIX routine iconv_open(), but
210
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
Havoc Pennington committed
211 212
 * a native implementation.
 * 
Owen Taylor's avatar
Owen Taylor committed
213
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
Havoc Pennington committed
214 215
 * more convenient than the raw iconv wrappers.
 * 
216
 * Returns: a "conversion descriptor", or (GIConv)-1 if
217
 *  opening the converter failed.
Havoc Pennington's avatar
Havoc Pennington committed
218
 **/
219 220 221 222
GIConv
g_iconv_open (const gchar  *to_codeset,
	      const gchar  *from_codeset)
{
223
  iconv_t cd;
224
  
225 226 227
  if (!try_conversion (to_codeset, from_codeset, &cd))
    {
      const char **to_aliases = _g_charset_get_aliases (to_codeset);
228
      const char **from_aliases = _g_charset_get_aliases (from_codeset);
229 230 231 232 233 234 235

      if (from_aliases)
	{
	  const char **p = from_aliases;
	  while (*p)
	    {
	      if (try_conversion (to_codeset, *p, &cd))
236
		goto out;
237 238

	      if (try_to_aliases (to_aliases, *p, &cd))
239
		goto out;
240 241 242 243 244 245

	      p++;
	    }
	}

      if (try_to_aliases (to_aliases, from_codeset, &cd))
246
	goto out;
247 248
    }

249
 out:
250
  return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
251 252
}

Havoc Pennington's avatar
Havoc Pennington committed
253
/**
254
 * g_iconv: (skip)
Havoc Pennington's avatar
Havoc Pennington committed
255 256 257 258 259 260
 * @converter: conversion descriptor from g_iconv_open()
 * @inbuf: bytes to convert
 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
 * @outbuf: converted output bytes
 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
 * 
261
 * Same as the standard UNIX routine iconv(), but
262
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
Havoc Pennington committed
263 264
 * a native implementation.
 *
Owen Taylor's avatar
Owen Taylor committed
265
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
Havoc Pennington committed
266 267
 * more convenient than the raw iconv wrappers.
 * 
268 269 270 271 272 273 274
 * Note that the behaviour of iconv() for characters which are valid in the
 * input character set, but which have no representation in the output character
 * set, is implementation defined. This function may return success (with a
 * positive number of non-reversible conversions as replacement characters were
 * used), or it may return -1 and set an error such as %EILSEQ, in such a
 * situation.
 *
275
 * Returns: count of non-reversible conversions, or -1 on error
Havoc Pennington's avatar
Havoc Pennington committed
276
 **/
277
gsize 
278 279
g_iconv (GIConv   converter,
	 gchar  **inbuf,
280
	 gsize   *inbytes_left,
281
	 gchar  **outbuf,
282
	 gsize   *outbytes_left)
283 284 285 286 287 288
{
  iconv_t cd = (iconv_t)converter;

  return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
}

Havoc Pennington's avatar
Havoc Pennington committed
289
/**
290
 * g_iconv_close: (skip)
Havoc Pennington's avatar
Havoc Pennington committed
291 292
 * @converter: a conversion descriptor from g_iconv_open()
 *
293
 * Same as the standard UNIX routine iconv_close(), but
294
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
Havoc Pennington committed
295
 * a native implementation. Should be called to clean up
Matthias Clasen's avatar
Matthias Clasen committed
296
 * the conversion descriptor from g_iconv_open() when
Havoc Pennington's avatar
Havoc Pennington committed
297 298
 * you are done converting things.
 *
Owen Taylor's avatar
Owen Taylor committed
299
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
Havoc Pennington committed
300 301
 * more convenient than the raw iconv wrappers.
 * 
302
 * Returns: -1 on error, 0 on success
Havoc Pennington's avatar
Havoc Pennington committed
303
 **/
304 305 306 307 308 309 310 311
gint
g_iconv_close (GIConv converter)
{
  iconv_t cd = (iconv_t)converter;

  return iconv_close (cd);
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
static GIConv
open_converter (const gchar *to_codeset,
		const gchar *from_codeset,
		GError     **error)
{
  GIConv cd;

  cd = g_iconv_open (to_codeset, from_codeset);

  if (cd == (GIConv) -1)
    {
      /* Something went wrong.  */
      if (error)
	{
	  if (errno == EINVAL)
	    g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
328
			 _("Conversion from character set “%s” to “%s” is not supported"),
329 330 331
			 from_codeset, to_codeset);
	  else
	    g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
332
			 _("Could not open converter from “%s” to “%s”"),
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
			 from_codeset, to_codeset);
	}
    }
  
  return cd;
}

static int
close_converter (GIConv cd)
{
  if (cd == (GIConv) -1)
    return 0;
  
  return g_iconv_close (cd);  
}

349
/**
350
 * g_convert_with_iconv: (skip)
351 352
 * @str:           (array length=len) (element-type guint8):
 *                 the string to convert.
353
 * @len:           the length of the string in bytes, or -1 if the string is
354 355 356
 *                 nul-terminated (Note that some encodings may allow nul
 *                 bytes to occur inside strings. In that case, using -1
 *                 for the @len parameter is unsafe)
357
 * @converter:     conversion descriptor from g_iconv_open()
358 359
 * @bytes_read:    (out) (optional): location to store the number of bytes in
 *                 the input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
360
 *                 Even if the conversion was successful, this may be 
361
 *                 less than @len if there were partial characters
362
 *                 at the end of the input. If the error
363
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
364
 *                 stored will be the byte offset after the last valid
365
 *                 input sequence.
366 367
 * @bytes_written: (out) (optional): the number of bytes stored in
 *                 the output buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
368
 * @error:         location to store the error occurring, or %NULL to ignore
369 370
 *                 errors. Any of the errors in #GConvertError may occur.
 *
371 372
 * Converts a string from one character set to another. 
 * 
373
 * Note that you should use g_iconv() for streaming conversions. 
374
 * Despite the fact that @bytes_read can return information about partial
375 376 377 378 379 380 381
 * characters, the g_convert_... functions are not generally suitable
 * for streaming. If the underlying converter maintains internal state,
 * then this won't be preserved across successive calls to g_convert(),
 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
 * this is the GNU C converter for CP1255 which does not emit a base
 * character until it knows that the next character is not a mark that
 * could combine with the base character.)
382
 *
383 384 385 386 387 388 389 390
 * Characters which are valid in the input character set, but which have no
 * representation in the output character set will result in a
 * %G_CONVERT_ERROR_ILLEGAL_SEQUENCE error. This is in contrast to the iconv()
 * specification, which leaves this behaviour implementation defined. Note that
 * this is the same error code as is returned for an invalid byte sequence in
 * the input character set. To get defined behaviour for conversion of
 * unrepresentable characters, use g_convert_with_fallback().
 *
391 392 393
 * Returns: (array length=bytes_written) (element-type guint8) (transfer full):
 *               If the conversion was successful, a newly allocated buffer
 *               containing the converted string, which must be freed with
394
 *               g_free(). Otherwise %NULL and @error will be set.
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
 **/
gchar*
g_convert_with_iconv (const gchar *str,
		      gssize       len,
		      GIConv       converter,
		      gsize       *bytes_read, 
		      gsize       *bytes_written, 
		      GError     **error)
{
  gchar *dest;
  gchar *outp;
  const gchar *p;
  gsize inbytes_remaining;
  gsize outbytes_remaining;
  gsize err;
  gsize outbuf_size;
  gboolean have_error = FALSE;
412
  gboolean done = FALSE;
413
  gboolean reset = FALSE;
414 415 416
  
  g_return_val_if_fail (converter != (GIConv) -1, NULL);
     
417 418 419 420 421
  if (len < 0)
    len = strlen (str);

  p = str;
  inbytes_remaining = len;
422
  outbuf_size = len + NUL_TERMINATOR_LENGTH;
423
  
424
  outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
425 426
  outp = dest = g_malloc (outbuf_size);

427
  while (!done && !have_error)
428
    {
429 430 431 432
      if (reset)
        err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
      else
        err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
433

434
      if (err == (gsize) -1)
435
	{
436 437 438 439
	  switch (errno)
	    {
	    case EINVAL:
	      /* Incomplete text, do not report an error */
440
	      done = TRUE;
441 442 443
	      break;
	    case E2BIG:
	      {
444
		gsize used = outp - dest;
445
		
446 447 448 449
		outbuf_size *= 2;
		dest = g_realloc (dest, outbuf_size);
		
		outp = dest + used;
450
		outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
451 452 453
	      }
	      break;
	    case EILSEQ:
454 455
              g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                                   _("Invalid byte sequence in conversion input"));
456 457 458
	      have_error = TRUE;
	      break;
	    default:
459 460 461 462 463 464 465
              {
                int errsv = errno;

                g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
                             _("Error during conversion: %s"),
                             g_strerror (errsv));
              }
466 467 468 469
	      have_error = TRUE;
	      break;
	    }
	}
470 471 472 473 474 475 476
      else if (err > 0)
        {
          /* @err gives the number of replacement characters used. */
          g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                               _("Unrepresentable character in conversion input"));
          have_error = TRUE;
        }
477 478
      else 
	{
479
	  if (!reset)
480 481
	    {
	      /* call g_iconv with NULL inbuf to cleanup shift state */
482
	      reset = TRUE;
483 484 485 486
	      inbytes_remaining = 0;
	    }
	  else
	    done = TRUE;
487 488 489
	}
    }

490
  memset (outp, 0, NUL_TERMINATOR_LENGTH);
491 492 493
  
  if (bytes_read)
    *bytes_read = p - str;
494 495 496 497
  else
    {
      if ((p - str) != len) 
	{
498 499
          if (!have_error)
            {
500 501
              g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
                                   _("Partial character sequence at end of input"));
502 503
              have_error = TRUE;
            }
504 505
	}
    }
506 507 508 509 510 511 512 513 514 515 516 517 518

  if (bytes_written)
    *bytes_written = outp - dest;	/* Doesn't include '\0' */

  if (have_error)
    {
      g_free (dest);
      return NULL;
    }
  else
    return dest;
}

519 520
/**
 * g_convert:
521 522
 * @str:           (array length=len) (element-type guint8):
 *                 the string to convert.
523
 * @len:           the length of the string in bytes, or -1 if the string is
524 525 526
 *                 nul-terminated (Note that some encodings may allow nul
 *                 bytes to occur inside strings. In that case, using -1
 *                 for the @len parameter is unsafe)
527 528
 * @to_codeset:    name of character set into which to convert @str
 * @from_codeset:  character set of @str.
529 530
 * @bytes_read:    (out) (optional): location to store the number of bytes in
 *                 the input string that were successfully converted, or %NULL.
531 532 533 534
 *                 Even if the conversion was successful, this may be 
 *                 less than @len if there were partial characters
 *                 at the end of the input. If the error
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
535
 *                 stored will be the byte offset after the last valid
536
 *                 input sequence.
537 538
 * @bytes_written: (out) (optional): the number of bytes stored in
 *                 the output buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
539
 * @error:         location to store the error occurring, or %NULL to ignore
540 541 542 543
 *                 errors. Any of the errors in #GConvertError may occur.
 *
 * Converts a string from one character set to another.
 *
544
 * Note that you should use g_iconv() for streaming conversions. 
545
 * Despite the fact that @bytes_read can return information about partial
546 547 548 549 550 551 552
 * characters, the g_convert_... functions are not generally suitable
 * for streaming. If the underlying converter maintains internal state,
 * then this won't be preserved across successive calls to g_convert(),
 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
 * this is the GNU C converter for CP1255 which does not emit a base
 * character until it knows that the next character is not a mark that
 * could combine with the base character.)
553
 *
554 555 556
 * Using extensions such as "//TRANSLIT" may not work (or may not work
 * well) on many platforms.  Consider using g_str_to_ascii() instead.
 *
557 558 559 560
 * Returns: (array length=bytes_written) (element-type guint8) (transfer full):
 *          If the conversion was successful, a newly allocated buffer
 *          containing the converted string, which must be freed with g_free().
 *          Otherwise %NULL and @error will be set.
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
 **/
gchar*
g_convert (const gchar *str,
           gssize       len,  
           const gchar *to_codeset,
           const gchar *from_codeset,
           gsize       *bytes_read, 
	   gsize       *bytes_written, 
	   GError     **error)
{
  gchar *res;
  GIConv cd;

  g_return_val_if_fail (str != NULL, NULL);
  g_return_val_if_fail (to_codeset != NULL, NULL);
  g_return_val_if_fail (from_codeset != NULL, NULL);
  
  cd = open_converter (to_codeset, from_codeset, error);

  if (cd == (GIConv) -1)
    {
      if (bytes_read)
        *bytes_read = 0;
      
      if (bytes_written)
        *bytes_written = 0;
      
      return NULL;
    }

  res = g_convert_with_iconv (str, len, cd,
			      bytes_read, bytes_written,
			      error);

  close_converter (cd);

  return res;
}

600 601
/**
 * g_convert_with_fallback:
602 603
 * @str:          (array length=len) (element-type guint8):
 *                the string to convert.
604
 * @len:          the length of the string in bytes, or -1 if the string is
605 606 607
 *                 nul-terminated (Note that some encodings may allow nul
 *                 bytes to occur inside strings. In that case, using -1
 *                 for the @len parameter is unsafe)
608 609
 * @to_codeset:   name of character set into which to convert @str
 * @from_codeset: character set of @str.
610
 * @fallback:     UTF-8 string to use in place of characters not
611 612
 *                present in the target encoding. (The string must be
 *                representable in the target encoding). 
613 614
 *                If %NULL, characters not in the target encoding will 
 *                be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
615 616
 * @bytes_read:   (out) (optional): location to store the number of bytes in
 *                the input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
617
 *                Even if the conversion was successful, this may be 
618
 *                less than @len if there were partial characters
619
 *                at the end of the input.
620 621
 * @bytes_written: (out) (optional): the number of bytes stored in
 *                 the output buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
622
 * @error:        location to store the error occurring, or %NULL to ignore
623 624
 *                errors. Any of the errors in #GConvertError may occur.
 *
Matthias Clasen's avatar
Matthias Clasen committed
625
 * Converts a string from one character set to another, possibly
626 627 628
 * including fallback sequences for characters not representable
 * in the output. Note that it is not guaranteed that the specification
 * for the fallback sequences in @fallback will be honored. Some
629
 * systems may do an approximate conversion from @from_codeset
630
 * to @to_codeset in their iconv() functions, 
Owen Taylor's avatar
Owen Taylor committed
631
 * in which case GLib will simply return that approximate conversion.
632
 *
633
 * Note that you should use g_iconv() for streaming conversions. 
634
 * Despite the fact that @bytes_read can return information about partial
635 636 637 638 639 640 641
 * characters, the g_convert_... functions are not generally suitable
 * for streaming. If the underlying converter maintains internal state,
 * then this won't be preserved across successive calls to g_convert(),
 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
 * this is the GNU C converter for CP1255 which does not emit a base
 * character until it knows that the next character is not a mark that
 * could combine with the base character.)
642
 *
643 644 645 646
 * Returns: (array length=bytes_written) (element-type guint8) (transfer full):
 *          If the conversion was successful, a newly allocated buffer
 *          containing the converted string, which must be freed with g_free().
 *          Otherwise %NULL and @error will be set.
647 648 649
 **/
gchar*
g_convert_with_fallback (const gchar *str,
650
			 gssize       len,    
651 652
			 const gchar *to_codeset,
			 const gchar *from_codeset,
653
			 const gchar *fallback,
654 655
			 gsize       *bytes_read,
			 gsize       *bytes_written,
656 657 658 659 660 661 662
			 GError     **error)
{
  gchar *utf8;
  gchar *dest;
  gchar *outp;
  const gchar *insert_str = NULL;
  const gchar *p;
663
  gsize inbytes_remaining;   
664
  const gchar *save_p = NULL;
665 666 667
  gsize save_inbytes = 0;
  gsize outbytes_remaining; 
  gsize err;
668
  GIConv cd;
669
  gsize outbuf_size;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
  gboolean have_error = FALSE;
  gboolean done = FALSE;

  GError *local_error = NULL;
  
  g_return_val_if_fail (str != NULL, NULL);
  g_return_val_if_fail (to_codeset != NULL, NULL);
  g_return_val_if_fail (from_codeset != NULL, NULL);
     
  if (len < 0)
    len = strlen (str);
  
  /* Try an exact conversion; we only proceed if this fails
   * due to an illegal sequence in the input string.
   */
  dest = g_convert (str, len, to_codeset, from_codeset, 
		    bytes_read, bytes_written, &local_error);
  if (!local_error)
    return dest;

  if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
    {
      g_propagate_error (error, local_error);
      return NULL;
    }
  else
    g_error_free (local_error);

698 699
  local_error = NULL;
  
700 701 702 703
  /* No go; to proceed, we need a converter from "UTF-8" to
   * to_codeset, and the string as UTF-8.
   */
  cd = open_converter (to_codeset, "UTF-8", error);
704
  if (cd == (GIConv) -1)
705 706 707 708 709 710 711 712 713 714 715 716 717
    {
      if (bytes_read)
        *bytes_read = 0;
      
      if (bytes_written)
        *bytes_written = 0;
      
      return NULL;
    }

  utf8 = g_convert (str, len, "UTF-8", from_codeset, 
		    bytes_read, &inbytes_remaining, error);
  if (!utf8)
718
    {
719
      close_converter (cd);
720 721 722 723
      if (bytes_written)
        *bytes_written = 0;
      return NULL;
    }
724 725 726 727 728 729 730 731 732 733

  /* Now the heart of the code. We loop through the UTF-8 string, and
   * whenever we hit an offending character, we form fallback, convert
   * the fallback to the target codeset, and then go back to
   * converting the original string after finishing with the fallback.
   *
   * The variables save_p and save_inbytes store the input state
   * for the original string while we are converting the fallback
   */
  p = utf8;
734

735 736
  outbuf_size = len + NUL_TERMINATOR_LENGTH;
  outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
737 738 739 740
  outp = dest = g_malloc (outbuf_size);

  while (!done && !have_error)
    {
741
      gsize inbytes_tmp = inbytes_remaining;
742
      err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
743
      inbytes_remaining = inbytes_tmp;
744

745
      if (err == (gsize) -1)
746 747 748 749 750 751 752 753
	{
	  switch (errno)
	    {
	    case EINVAL:
	      g_assert_not_reached();
	      break;
	    case E2BIG:
	      {
754
		gsize used = outp - dest;
755

756 757 758 759
		outbuf_size *= 2;
		dest = g_realloc (dest, outbuf_size);
		
		outp = dest + used;
760
		outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
761 762 763 764 765 766 767 768 769
		
		break;
	      }
	    case EILSEQ:
	      if (save_p)
		{
		  /* Error converting fallback string - fatal
		   */
		  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
770
			       _("Cannot convert fallback “%s” to codeset “%s”"),
771 772 773 774
			       insert_str, to_codeset);
		  have_error = TRUE;
		  break;
		}
775
	      else if (p)
776 777 778 779
		{
		  if (!fallback)
		    { 
		      gunichar ch = g_utf8_get_char (p);
780
		      insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
781 782 783 784 785 786 787 788 789
						    ch);
		    }
		  else
		    insert_str = fallback;
		  
		  save_p = g_utf8_next_char (p);
		  save_inbytes = inbytes_remaining - (save_p - p);
		  p = insert_str;
		  inbytes_remaining = strlen (p);
790
		  break;
791
		}
792 793
              /* if p is null */
              G_GNUC_FALLTHROUGH;
794
	    default:
Christian Persch's avatar
Christian Persch committed
795 796 797 798 799 800 801 802
              {
                int errsv = errno;

                g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
                             _("Error during conversion: %s"),
                             g_strerror (errsv));
              }

803 804 805 806 807 808 809 810 811 812 813 814 815 816
	      have_error = TRUE;
	      break;
	    }
	}
      else
	{
	  if (save_p)
	    {
	      if (!fallback)
		g_free ((gchar *)insert_str);
	      p = save_p;
	      inbytes_remaining = save_inbytes;
	      save_p = NULL;
	    }
817 818 819 820 821 822
	  else if (p)
	    {
	      /* call g_iconv with NULL inbuf to cleanup shift state */
	      p = NULL;
	      inbytes_remaining = 0;
	    }
823 824 825 826 827 828 829
	  else
	    done = TRUE;
	}
    }

  /* Cleanup
   */
830
  memset (outp, 0, NUL_TERMINATOR_LENGTH);
831
  
832
  close_converter (cd);
833 834

  if (bytes_written)
835
    *bytes_written = outp - dest;	/* Doesn't include '\0' */
836 837 838 839 840 841 842 843 844 845 846 847 848

  g_free (utf8);

  if (have_error)
    {
      if (save_p && !fallback)
	g_free ((gchar *)insert_str);
      g_free (dest);
      return NULL;
    }
  else
    return dest;
}
849 850 851 852

/*
 * g_locale_to_utf8
 *
853 854 855
 * 
 */

856 857 858 859 860 861 862 863 864 865 866
/*
 * Validate @string as UTF-8. @len can be negative if @string is
 * nul-terminated, or a non-negative value in bytes. If @string ends in an
 * incomplete sequence, or contains any illegal sequences or nul codepoints,
 * %NULL will be returned and the error set to
 * %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
 * On success, @bytes_read and @bytes_written, if provided, will be set to
 * the number of bytes in @string up to @len or the terminating nul byte.
 * On error, @bytes_read will be set to the byte offset after the last valid
 * and non-nul UTF-8 sequence in @string, and @bytes_written will be set to 0.
 */
867 868 869
static gchar *
strdup_len (const gchar *string,
	    gssize       len,
870
	    gsize       *bytes_read,
871 872
	    gsize       *bytes_written,
	    GError     **error)
873 874
{
  gsize real_len;
875
  const gchar *end_valid;
876

877
  if (!g_utf8_validate (string, len, &end_valid))
878 879
    {
      if (bytes_read)
880
	*bytes_read = end_valid - string;
881 882 883
      if (bytes_written)
	*bytes_written = 0;

884 885
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                           _("Invalid byte sequence in conversion input"));
886 887
      return NULL;
    }
888 889 890

  real_len = end_valid - string;

891 892 893 894 895 896 897 898
  if (bytes_read)
    *bytes_read = real_len;
  if (bytes_written)
    *bytes_written = real_len;

  return g_strndup (string, real_len);
}

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
typedef enum
{
  CONVERT_CHECK_NO_NULS_IN_INPUT  = 1 << 0,
  CONVERT_CHECK_NO_NULS_IN_OUTPUT = 1 << 1
} ConvertCheckFlags;

/*
 * Convert from @string in the encoding identified by @from_codeset,
 * returning a string in the encoding identifed by @to_codeset.
 * @len can be negative if @string is nul-terminated, or a non-negative
 * value in bytes. Flags defined in #ConvertCheckFlags can be set in @flags
 * to check the input, the output, or both, for embedded nul bytes.
 * On success, @bytes_read, if provided, will be set to the number of bytes
 * in @string up to @len or the terminating nul byte, and @bytes_written, if
 * provided, will be set to the number of output bytes written into the
 * returned buffer, excluding the terminating nul sequence.
 * On error, @bytes_read will be set to the byte offset after the last valid
 * sequence in @string, and @bytes_written will be set to 0.
 */
918
static gchar *
919 920 921 922 923 924 925 926
convert_checked (const gchar      *string,
                 gssize            len,
                 const gchar      *to_codeset,
                 const gchar      *from_codeset,
                 ConvertCheckFlags flags,
                 gsize            *bytes_read,
                 gsize            *bytes_written,
                 GError          **error)
927
{
928
  gchar *out;
929 930
  gsize outbytes;

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  if ((flags & CONVERT_CHECK_NO_NULS_IN_INPUT) && len > 0)
    {
      const gchar *early_nul = memchr (string, '\0', len);
      if (early_nul != NULL)
        {
          if (bytes_read)
            *bytes_read = early_nul - string;
          if (bytes_written)
            *bytes_written = 0;

          g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
                               _("Embedded NUL byte in conversion input"));
          return NULL;
        }
    }

  out = g_convert (string, len, to_codeset, from_codeset,
                   bytes_read, &outbytes, error);
  if (out == NULL)
950 951 952 953 954
    {
      if (bytes_written)
        *bytes_written = 0;
      return NULL;
    }
955 956 957

  if ((flags & CONVERT_CHECK_NO_NULS_IN_OUTPUT)
      && memchr (out, '\0', outbytes) != NULL)
958
    {
959
      g_free (out);
960 961 962 963 964 965 966 967 968
      if (bytes_written)
        *bytes_written = 0;
      g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_EMBEDDED_NUL,
                           _("Embedded NUL byte in conversion output"));
      return NULL;
    }

  if (bytes_written)
    *bytes_written = outbytes;
969
  return out;
970 971
}

972 973
/**
 * g_locale_to_utf8:
974 975
 * @opsysstring:   (array length=len) (element-type guint8): a string in the
 *                 encoding of the current locale. On Windows
Tor Lillqvist's avatar
Tor Lillqvist committed
976
 *                 this means the system codepage.
977
 * @len:           the length of the string, or -1 if the string is
978 979 980
 *                 nul-terminated (Note that some encodings may allow nul
 *                 bytes to occur inside strings. In that case, using -1
 *                 for the @len parameter is unsafe)
981
 * @bytes_read: (out) (optional): location to store the number of bytes in the
982
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
983
 *                 Even if the conversion was successful, this may be 
984
 *                 less than @len if there were partial characters
985
 *                 at the end of the input. If the error
986
 *                 %G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
987
 *                 stored will be the byte offset after the last valid
988
 *                 input sequence.
989 990
 * @bytes_written: (out) (optional): the number of bytes stored in the output
 *                 buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
991
 * @error:         location to store the error occurring, or %NULL to ignore
992 993
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
994 995
 * Converts a string which is in the encoding used for strings by
 * the C runtime (usually the same as that used by the operating
996
 * system) in the [current locale][setlocale] into a UTF-8 string.
997 998 999 1000 1001 1002 1003 1004
 *
 * If the source encoding is not UTF-8 and the conversion output contains a
 * nul character, the error %G_CONVERT_ERROR_EMBEDDED_NUL is set and the
 * function returns %NULL.
 * If the source encoding is UTF-8, an embedded nul character is treated with
 * the %G_CONVERT_ERROR_ILLEGAL_SEQUENCE error for backward compatibility with
 * earlier versions of this library. Use g_convert() to produce output that
 * may contain embedded nul characters.
1005
 * 
1006
 * Returns: (type utf8): The converted string, or %NULL on an error.
1007
 **/
1008
gchar *
1009
g_locale_to_utf8 (const gchar  *opsysstring,
1010 1011 1012
		  gssize        len,            
		  gsize        *bytes_read,    
		  gsize        *bytes_written,
1013
		  GError      **error)
1014
{
1015
  const char *charset;
1016 1017

  if (g_get_charset (&charset))
1018
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1019
  else
1020 1021
    return convert_checked (opsysstring, len, "UTF-8", charset,
                            CONVERT_CHECK_NO_NULS_IN_OUTPUT,
1022
                            bytes_read, bytes_written, error);
1023 1024
}

1025 1026 1027 1028
/**
 * g_locale_from_utf8:
 * @utf8string:    a UTF-8 encoded string 
 * @len:           the length of the string, or -1 if the string is
1029
 *                 nul-terminated.
1030
 * @bytes_read: (out) (optional): location to store the number of bytes in the
1031
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
1032
 *                 Even if the conversion was successful, this may be 
1033
 *                 less than @len if there were partial characters
1034
 *                 at the end of the input. If the error
1035
 *                 %G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1036
 *                 stored will be the byte offset after the last valid
1037
 *                 input sequence.
1038 1039
 * @bytes_written: (out) (optional): the number of bytes stored in the output
 *                 buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
1040
 * @error:         location to store the error occurring, or %NULL to ignore
1041 1042 1043 1044
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
 * Converts a string from UTF-8 to the encoding used for strings by
 * the C runtime (usually the same as that used by the operating
1045 1046
 * system) in the [current locale][setlocale]. On Windows this means
 * the system codepage.
1047
 *
1048 1049
 * The input string shall not contain nul characters even if the @len
 * argument is positive. A nul character found inside the string will result
1050 1051 1052
 * in error %G_CONVERT_ERROR_ILLEGAL_SEQUENCE. Use g_convert() to convert
 * input that may contain embedded nul characters.
 *
1053 1054 1055
 * Returns: (array length=bytes_written) (element-type guint8) (transfer full):
 *          A newly-allocated buffer containing the converted string,
 *          or %NULL on an error, and error will be set.
1056
 **/
1057
gchar *
1058
g_locale_from_utf8 (const gchar *utf8string,
1059 1060 1061
		    gssize       len,            
		    gsize       *bytes_read,    
		    gsize       *bytes_written,
1062
		    GError     **error)
1063
{
1064
  const gchar *charset;
1065 1066

  if (g_get_charset (&charset))
1067
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1068
  else
1069 1070 1071
    return convert_checked (utf8string, len, charset, "UTF-8",
                            CONVERT_CHECK_NO_NULS_IN_INPUT,
                            bytes_read, bytes_written, error);
1072 1073
}

1074
#ifndef G_PLATFORM_WIN32
1075

1076 1077 1078 1079 1080
typedef struct _GFilenameCharsetCache GFilenameCharsetCache;

struct _GFilenameCharsetCache {
  gboolean is_utf8;
  gchar *charset;
1081
  gchar **filename_charsets;
1082 1083 1084 1085 1086 1087 1088
};

static void
filename_charset_cache_free (gpointer data)
{
  GFilenameCharsetCache *cache = data;
  g_free (cache->charset);
1089
  g_strfreev (cache->filename_charsets);
1090 1091 1092
  g_free (cache);
}

1093
/**
1094
 * g_get_filename_charsets:
1095 1096
 * @filename_charsets: (out) (transfer none) (array zero-terminated=1):
 *    return location for the %NULL-terminated list of encoding names
1097
 *
1098 1099 1100
 * Determines the preferred character sets used for filenames.
 * The first character set from the @charsets is the filename encoding, the
 * subsequent character sets are used when trying to generate a displayable
Tor Lillqvist's avatar
Tor Lillqvist committed
1101
 * representation of a filename, see g_filename_display_name().
1102
 *
1103
 * On Unix, the character sets are determined by consulting the
1104 1105 1106 1107 1108
 * environment variables `G_FILENAME_ENCODING` and `G_BROKEN_FILENAMES`.
 * On Windows, the character set used in the GLib API is always UTF-8
 * and said environment variables have no effect.
 *
 * `G_FILENAME_ENCODING` may be set to a comma-separated list of
Phillip Wood's avatar
Phillip Wood committed
1109
 * character set names. The special token "\@locale" is taken
1110 1111 1112 1113 1114 1115
 * to  mean the character set for the [current locale][setlocale].
 * If `G_FILENAME_ENCODING` is not set, but `G_BROKEN_FILENAMES` is,
 * the character set of the current locale is taken as the filename
 * encoding. If neither environment variable  is set, UTF-8 is taken
 * as the filename encoding, but the character set of the current locale
 * is also put in the list of encodings.
1116 1117
 *
 * The returned @charsets belong to GLib and must not be freed.
1118 1119
 *
 * Note that on Unix, regardless of the locale character set or
1120
 * `G_FILENAME_ENCODING` value, the actual file names present 
1121
 * on a system might be in any random encoding or just gibberish.
1122
 *
1123
 * Returns: %TRUE if the filename encoding is UTF-8.
1124 1125
 * 
 * Since: 2.6
1126
 */
1127
gboolean
1128
g_get_filename_charsets (const gchar ***filename_charsets)
1129
{
1130 1131
  static GPrivate cache_private = G_PRIVATE_INIT (filename_charset_cache_free);
  GFilenameCharsetCache *cache = g_private_get (&cache_private);
1132
  const gchar *charset;
1133

1134
  if (!cache)
1135
    cache = g_private_set_alloc0 (&cache_private, sizeof (GFilenameCharsetCache));
1136 1137 1138 1139 1140 1141

  g_get_charset (&charset);

  if (!(cache->charset && strcmp (cache->charset, charset) == 0))
    {
      const gchar *new_charset;
1142 1143
      gchar *p;
      gint i;
1144

1145
      g_free (cache->charset);
1146
      g_strfreev (cache->filename_charsets);
1147
      cache->charset = g_strdup (charset);
1148 1149
      
      p = getenv ("G_FILENAME_ENCODING");
1150
      if (p != NULL && p[0] != '\0') 
1151
	{
1152 1153
	  cache->filename_charsets = g_strsplit (p, ",", 0);
	  cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1154

1155
	  for (i = 0; cache->filename_charsets[i]; i++)
1156
	    {
1157 1158 1159 1160 1161 1162
	      if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
		{
		  g_get_charset (&new_charset);
		  g_free (cache->filename_charsets[i]);
		  cache->filename_charsets[i] = g_strdup (new_charset);
		}
1163 1164 1165
	    }
	}
      else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1166
	{
1167
	  cache->filename_charsets = g_new0 (gchar *, 2);
1168
	  cache->is_utf8 = g_get_charset (&new_charset);
1169
	  cache->filename_charsets[0] = g_strdup (new_charset);
1170
	}
1171 1172
      else 
	{
1173
	  cache->filename_charsets = g_new0 (gchar *, 3);
1174
	  cache->is_utf8 = TRUE;
1175 1176 1177
	  cache->filename_charsets[0] = g_strdup ("UTF-8");
	  if (!g_get_charset (&new_charset))
	    cache->filename_charsets[1] = g_strdup (new_charset);
1178 1179
	}
    }
1180

1181 1182
  if (filename_charsets)
    *filename_charsets = (const gchar **)cache->filename_charsets;
1183

1184
  return cache->is_utf8;
1185
}
1186

1187
#else /* G_PLATFORM_WIN32 */
1188

1189
gboolean
1190
g_get_filename_charsets (const gchar ***filename_charsets) 
1191
{
1192
  static const gchar *charsets[] = {
1193 1194 1195 1196
    "UTF-8",
    NULL
  };

1197 1198
#ifdef G_OS_WIN32
  /* On Windows GLib pretends that the filename charset is UTF-8 */
1199 1200 1201
  if (filename_charsets)
    *filename_charsets = charsets;

1202 1203
  return TRUE;
#else
1204 1205
  gboolean result;

1206
  /* Cygwin works like before */
1207 1208 1209 1210 1211 1212
  result = g_get_charset (&(charsets[0]));

  if (filename_charsets)
    *filename_charsets = charsets;

  return result;
1213 1214 1215
#endif
}

1216
#endif /* G_PLATFORM_WIN32 */
1217 1218

static gboolean
1219
get_filename_charset (const gchar **filename_charset)
1220
{
1221 1222 1223 1224
  const gchar **charsets;
  gboolean is_utf8;
  
  is_utf8 = g_get_filename_charsets (&charsets);
1225

1226 1227 1228 1229 1230
  if (filename_charset)
    *filename_charset = charsets[0];
  
  return is_utf8;
}
1231

1232 1233
/**
 * g_filename_to_utf8:
1234
 * @opsysstring: (type filename): a string in the encoding for filenames
1235
 * @len:           the length of the string, or -1 if the string is
1236 1237 1238
 *                 nul-terminated (Note that some encodings may allow nul
 *                 bytes to occur inside strings. In that case, using -1
 *                 for the @len parameter is unsafe)
1239
 * @bytes_read: (out) (optional): location to store the number of bytes in the
1240
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
1241
 *                 Even if the conversion was successful, this may be 
1242
 *                 less than @len if there were partial characters
1243
 *                 at the end of the input. If the error
1244
 *                 %G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1245
 *                 stored will be the byte offset after the last valid
1246
 *                 input sequence.
1247 1248
 * @bytes_written: (out) (optional): the number of bytes stored in the output
 *                 buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
1249
 * @error:         location to store the error occurring, or %NULL to ignore
1250 1251
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
1252 1253
 * Converts a string which is in the encoding used by GLib for
 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1254
 * for filenames; on other platforms, this function indirectly depends on 
1255
 * the [current locale][setlocale].
1256
 *
1257 1258 1259
 * The input string shall not contain nul characters even if the @len
 * argument is positive. A nul character found inside the string will result
 * in error %G_CONVERT_ERROR_ILLEGAL_SEQUENCE.
1260 1261
 * If the source encoding is not UTF-8 and the conversion output contains a
 * nul character, the error %G_CONVERT_ERROR_EMBEDDED_NUL is set and the
1262
 * function returns %NULL. Use g_convert() to produce output that
1263
 * may contain embedded nul characters.
1264
 * 
1265
 * Returns: (type utf8): The converted string, or %NULL on an error.
1266
 **/
1267
gchar*
1268
g_filename_to_utf8 (const gchar *opsysstring, 
1269 1270 1271
		    gssize       len,           
		    gsize       *bytes_read,   
		    gsize       *bytes_written,
1272
		    GError     **error)
1273
{
1274 1275
  const gchar *charset;

1276 1277
  g_return_val_if_fail (opsysstring != NULL, NULL);

1278
  if (get_filename_charset (&charset))
1279
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1280
  else
1281 1282 1283
    return convert_checked (opsysstring, len, "UTF-8", charset,
                            CONVERT_CHECK_NO_NULS_IN_INPUT |
                            CONVERT_CHECK_NO_NULS_IN_OUTPUT,
1284
                            bytes_read, bytes_written, error);
1285 1286
}

1287 1288
/**
 * g_filename_from_utf8:
1289
 * @utf8string:    (type utf8): a UTF-8 encoded string.
1290
 * @len:           the length of the string, or -1 if the string is
1291
 *                 nul-terminated.
1292
 * @bytes_read:    (out) (optional): location to store the number of bytes in
1293
 *                 the input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
1294
 *                 Even if the conversion was successful, this may be 
1295
 *                 less than @len if there were partial characters
1296
 *                 at the end of the input. If the error
1297
 *                 %G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1298
 *                 stored will be the byte offset after the last valid
1299
 *                 input sequence.
1300 1301
 * @bytes_written: (out) (optional): the number of bytes stored in
 *                 the output buffer (not including the terminating nul).
Matthias Clasen's avatar
Matthias Clasen committed
1302
 * @error:         location to store the error occurring, or %NULL to ignore
1303 1304
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
1305
 * Converts a string from UTF-8 to the encoding GLib uses for
1306 1307
 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
 * on other platforms, this function indirectly depends on the 
1308
 * [current locale][setlocale].
1309
 *
1310 1311
 * The input string shall not contain nul characters even if the @len
 * argument is positive. A nul character found inside the string will result
1312 1313 1314
 * in error %G_CONVERT_ERROR_ILLEGAL_SEQUENCE. If the filename encoding is
 * not UTF-8 and the conversion output contains a nul character, the error
 * %G_CONVERT_ERROR_EMBEDDED_NUL is set and the function returns %NULL.
1315
 *