049b9afd0ae87039fe9dfa0fa3b44a7dc09eef15
[gnulib.git] / lib / unicodeio.c
1 /* Unicode character output to streams with locale dependent encoding.
2
3    Copyright (C) 2000-2002 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU Library General Public License as published
7    by the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Library General Public License for more details.
14
15    You should have received a copy of the GNU Library General Public
16    License along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18    USA.  */
19
20 /* Written by Bruno Haible <haible@clisp.cons.org>.  */
21
22 /* Note: This file requires the locale_charset() function.  See in
23    libiconv-1.7/libcharset/INTEGRATE for how to obtain it.  */
24
25 #ifdef HAVE_CONFIG_H
26 # include <config.h>
27 #endif
28
29 #if HAVE_STDDEF_H
30 # include <stddef.h>
31 #endif
32
33 #include <stdio.h>
34 #if HAVE_STRING_H
35 # include <string.h>
36 #else
37 # include <strings.h>
38 #endif
39
40 #include <errno.h>
41 #ifndef errno
42 extern int errno;
43 #endif
44
45 #if HAVE_ICONV
46 # include <iconv.h>
47 #endif
48
49 #include <error.h>
50
51 #if ENABLE_NLS
52 # include <libintl.h>
53 #else
54 # define gettext(Text) Text
55 #endif
56 #define _(Text) gettext (Text)
57 #define N_(Text) Text
58
59 /* Specification.  */
60 #include "unicodeio.h"
61
62 /* When we pass a Unicode character to iconv(), we must pass it in a
63    suitable encoding. The standardized Unicode encodings are
64    UTF-8, UCS-2, UCS-4, UTF-16, UTF-16BE, UTF-16LE, UTF-7.
65    UCS-2 supports only characters up to \U0000FFFF.
66    UTF-16 and variants support only characters up to \U0010FFFF.
67    UTF-7 is way too complex and not supported by glibc-2.1.
68    UCS-4 specification leaves doubts about endianness and byte order
69    mark. glibc currently interprets it as big endian without byte order
70    mark, but this is not backed by an RFC.
71    So we use UTF-8. It supports characters up to \U7FFFFFFF and is
72    unambiguously defined.  */
73
74 /* Stores the UTF-8 representation of the Unicode character wc in r[0..5].
75    Returns the number of bytes stored, or -1 if wc is out of range.  */
76 static int
77 utf8_wctomb (unsigned char *r, unsigned int wc)
78 {
79   int count;
80
81   if (wc < 0x80)
82     count = 1;
83   else if (wc < 0x800)
84     count = 2;
85   else if (wc < 0x10000)
86     count = 3;
87   else if (wc < 0x200000)
88     count = 4;
89   else if (wc < 0x4000000)
90     count = 5;
91   else if (wc <= 0x7fffffff)
92     count = 6;
93   else
94     return -1;
95
96   switch (count)
97     {
98       /* Note: code falls through cases! */
99       case 6: r[5] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x4000000;
100       case 5: r[4] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x200000;
101       case 4: r[3] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x10000;
102       case 3: r[2] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x800;
103       case 2: r[1] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0xc0;
104       case 1: r[0] = wc;
105     }
106
107   return count;
108 }
109
110 /* Luckily, the encoding's name is platform independent.  */
111 #define UTF8_NAME "UTF-8"
112
113 /* Converts the Unicode character CODE to its multibyte representation
114    in the current locale and calls the SUCCESS callback on the resulting
115    byte sequence.  If an error occurs, invokes the FAILURE callback instead,
116    passing it CODE and an English error string.
117    Returns whatever the callback returned.
118    Assumes that the locale doesn't change between two calls.  */
119 long
120 unicode_to_mb (unsigned int code,
121                long (*success) PARAMS ((const char *buf, size_t buflen,
122                                         void *callback_arg)),
123                long (*failure) PARAMS ((unsigned int code, const char *msg,
124                                         void *callback_arg)),
125                void *callback_arg)
126 {
127   static int initialized;
128   static int is_utf8;
129 #if HAVE_ICONV
130   static iconv_t utf8_to_local;
131 #endif
132
133   char inbuf[6];
134   int count;
135
136   if (!initialized)
137     {
138       extern const char *locale_charset PARAMS ((void));
139       const char *charset = locale_charset ();
140
141       is_utf8 = !strcmp (charset, UTF8_NAME);
142 #if HAVE_ICONV
143       if (!is_utf8)
144         {
145           utf8_to_local = iconv_open (charset, UTF8_NAME);
146           if (utf8_to_local == (iconv_t)(-1))
147             /* For an unknown encoding, assume ASCII.  */
148             utf8_to_local = iconv_open ("ASCII", UTF8_NAME);
149         }
150 #endif
151       initialized = 1;
152     }
153
154   /* Test whether the utf8_to_local converter is available at all.  */
155   if (!is_utf8)
156     {
157 #if HAVE_ICONV
158       if (utf8_to_local == (iconv_t)(-1))
159         return failure (code, N_("iconv function not usable"), callback_arg);
160 #else
161       return failure (code, N_("iconv function not available"), callback_arg);
162 #endif
163     }
164
165   /* Convert the character to UTF-8.  */
166   count = utf8_wctomb ((unsigned char *) inbuf, code);
167   if (count < 0)
168     return failure (code, N_("character out of range"), callback_arg);
169
170 #if HAVE_ICONV
171   if (!is_utf8)
172     {
173       char outbuf[25];
174       const char *inptr;
175       size_t inbytesleft;
176       char *outptr;
177       size_t outbytesleft;
178       size_t res;
179
180       inptr = inbuf;
181       inbytesleft = count;
182       outptr = outbuf;
183       outbytesleft = sizeof (outbuf);
184
185       /* Convert the character from UTF-8 to the locale's charset.  */
186       res = iconv (utf8_to_local,
187                    (ICONV_CONST char **)&inptr, &inbytesleft,
188                    &outptr, &outbytesleft);
189       if (inbytesleft > 0 || res == (size_t)(-1)
190           /* Irix iconv() inserts a NUL byte if it cannot convert. */
191 # if !defined _LIBICONV_VERSION && (defined sgi || defined __sgi)
192           || (res > 0 && code != 0 && outptr - outbuf == 1 && *outbuf == '\0')
193 # endif
194          )
195         return failure (code, NULL, callback_arg);
196
197       /* Avoid glibc-2.1 bug and Solaris 2.7 bug.  */
198 # if defined _LIBICONV_VERSION \
199     || !((__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) || defined __sun)
200
201       /* Get back to the initial shift state.  */
202       res = iconv (utf8_to_local, NULL, NULL, &outptr, &outbytesleft);
203       if (res == (size_t)(-1))
204         return failure (code, NULL, callback_arg);
205 # endif
206
207       return success (outbuf, outptr - outbuf, callback_arg);
208     }
209 #endif
210
211   /* At this point, is_utf8 is true, so no conversion is needed.  */
212   return success (inbuf, count, callback_arg);
213 }
214
215 /* Simple success callback that outputs the converted string.
216    The STREAM is passed as callback_arg.  */
217 long
218 fwrite_success_callback (const char *buf, size_t buflen, void *callback_arg)
219 {
220   FILE *stream = (FILE *) callback_arg;
221
222   fwrite (buf, 1, buflen, stream);
223   return 0;
224 }
225
226 /* Simple failure callback that displays an error and exits.  */
227 static long
228 exit_failure_callback (unsigned int code, const char *msg, void *callback_arg)
229 {
230   if (msg == NULL)
231     error (1, 0, _("cannot convert U+%04X to local character set"), code);
232   else
233     error (1, 0, _("cannot convert U+%04X to local character set: %s"), code,
234            gettext (msg));
235   return -1;
236 }
237
238 /* Simple failure callback that displays a fallback representation in plain
239    ASCII, using the same notation as ISO C99 strings.  */
240 static long
241 fallback_failure_callback (unsigned int code, const char *msg, void *callback_arg)
242 {
243   FILE *stream = (FILE *) callback_arg;
244
245   if (code < 0x10000)
246     fprintf (stream, "\\u%04X", code);
247   else
248     fprintf (stream, "\\U%08X", code);
249   return -1;
250 }
251
252 /* Outputs the Unicode character CODE to the output stream STREAM.
253    Upon failure, exit if exit_on_error is true, otherwise output a fallback
254    notation.  */
255 void
256 print_unicode_char (FILE *stream, unsigned int code, int exit_on_error)
257 {
258   unicode_to_mb (code, fwrite_success_callback,
259                  exit_on_error
260                  ? exit_failure_callback
261                  : fallback_failure_callback,
262                  stream);
263 }