1 /* toutf8.c convert strings from system locale into UTF-8
2 * Copyright (C) 2002 Simon Josefsson
4 * This file is part of libstringprep.
6 * Libstringprep is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libstringprep is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with libstringprep; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
34 # if !STDC_HEADERS && HAVE_MEMORY_H
54 stringprep_locale_charset_slow ()
56 const char *charset
= getenv ("CHARSET");
59 if (charset
&& *charset
)
63 p
= setlocale (LC_CTYPE
, NULL
);
64 setlocale (LC_CTYPE
, "");
66 charset
= nl_langinfo (CODESET
);
68 setlocale (LC_CTYPE
, p
);
71 if (charset
&& *charset
)
77 static const char *stringprep_locale_charset_cache
= NULL
;
80 stringprep_locale_charset ()
82 if (!stringprep_locale_charset_cache
)
83 stringprep_locale_charset_cache
= stringprep_locale_charset_slow ();
85 return stringprep_locale_charset_cache
;
89 stringprep_convert (const char *str
,
90 const char *to_codeset
, const char *from_codeset
)
96 size_t inbytes_remaining
;
97 size_t outbytes_remaining
;
103 if (strcmp (to_codeset
, from_codeset
) == 0)
106 cd
= iconv_open (to_codeset
, from_codeset
);
108 if (cd
== (iconv_t
) - 1)
114 inbytes_remaining
= len
;
115 outbuf_size
= len
+ 1; /* + 1 for nul in case len == 1 */
117 outbytes_remaining
= outbuf_size
- 1; /* -1 for nul */
118 outp
= dest
= malloc (outbuf_size
);
122 err
= iconv (cd
, &p
, &inbytes_remaining
, &outp
, &outbytes_remaining
);
124 if (err
== (size_t) - 1)
129 /* Incomplete text, do not report an error */
134 size_t used
= outp
- dest
;
137 dest
= realloc (dest
, outbuf_size
);
140 outbytes_remaining
= outbuf_size
- used
- 1; /* -1 for nul */
158 if ((p
- str
) != len
)
175 stringprep_locale_charset ()
181 stringprep_convert (const char *str
,
182 const char *to_codeset
, const char *from_codeset
)
190 stringprep_locale_to_utf8 (const char *str
)
192 return stringprep_convert (str
, "UTF-8", stringprep_locale_charset ());