update from prep
[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.8/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 #include "gettext.h"
52 #define _(msgid) gettext (msgid)
53 #define N_(msgid) msgid
54
55 /* Specification.  */
56 #include "unicodeio.h"
57
58 /* When we pass a Unicode character to iconv(), we must pass it in a
59    suitable encoding. The standardized Unicode encodings are
60    UTF-8, UCS-2, UCS-4, UTF-16, UTF-16BE, UTF-16LE, UTF-7.
61    UCS-2 supports only characters up to \U0000FFFF.
62    UTF-16 and variants support only characters up to \U0010FFFF.
63    UTF-7 is way too complex and not supported by glibc-2.1.
64    UCS-4 specification leaves doubts about endianness and byte order
65    mark. glibc currently interprets it as big endian without byte order
66    mark, but this is not backed by an RFC.
67    So we use UTF-8. It supports characters up to \U7FFFFFFF and is
68    unambiguously defined.  */
69
70 /* Stores the UTF-8 representation of the Unicode character wc in r[0..5].
71    Returns the number of bytes stored, or -1 if wc is out of range.  */
72 static int
73 utf8_wctomb (unsigned char *r, unsigned int wc)
74 {
75   int count;
76
77   if (wc < 0x80)
78     count = 1;
79   else if (wc < 0x800)
80     count = 2;
81   else if (wc < 0x10000)
82     count = 3;
83   else if (wc < 0x200000)
84     count = 4;
85   else if (wc < 0x4000000)
86     count = 5;
87   else if (wc <= 0x7fffffff)
88     count = 6;
89   else
90     return -1;
91
92   switch (count)
93     {
94       /* Note: code falls through cases! */
95       case 6: r[5] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x4000000;
96       case 5: r[4] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x200000;
97       case 4: r[3] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x10000;
98       case 3: r[2] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0x800;
99       case 2: r[1] = 0x80 | (wc & 0x3f); wc = wc >> 6; wc |= 0xc0;
100       case 1: r[0] = wc;
101     }
102
103   return count;
104 }
105
106 /* Luckily, the encoding's name is platform independent.  */
107 #define UTF8_NAME "UTF-8"
108
109 /* Converts the Unicode character CODE to its multibyte representation
110    in the current locale and calls the SUCCESS callback on the resulting
111    byte sequence.  If an error occurs, invokes the FAILURE callback instead,
112    passing it CODE and an English error string.
113    Returns whatever the callback returned.
114    Assumes that the locale doesn't change between two calls.  */
115 long
116 unicode_to_mb (unsigned int code,
117                long (*success) PARAMS ((const char *buf, size_t buflen,
118                                         void *callback_arg)),
119                long (*failure) PARAMS ((unsigned int code, const char *msg,
120                                         void *callback_arg)),
121                void *callback_arg)
122 {
123   static int initialized;
124   static int is_utf8;
125 #if HAVE_ICONV
126   static iconv_t utf8_to_local;
127 #endif
128
129   char inbuf[6];
130   int count;
131
132   if (!initialized)
133     {
134       extern const char *locale_charset PARAMS ((void));
135       const char *charset = locale_charset ();
136
137       is_utf8 = !strcmp (charset, UTF8_NAME);
138 #if HAVE_ICONV
139       if (!is_utf8)
140         {
141           utf8_to_local = iconv_open (charset, UTF8_NAME);
142           if (utf8_to_local == (iconv_t)(-1))
143             /* For an unknown encoding, assume ASCII.  */
144             utf8_to_local = iconv_open ("ASCII", UTF8_NAME);
145         }
146 #endif
147       initialized = 1;
148     }
149
150   /* Test whether the utf8_to_local converter is available at all.  */
151   if (!is_utf8)
152     {
153 #if HAVE_ICONV
154       if (utf8_to_local == (iconv_t)(-1))
155         return failure (code, N_("iconv function not usable"), callback_arg);
156 #else
157       return failure (code, N_("iconv function not available"), callback_arg);
158 #endif
159     }
160
161   /* Convert the character to UTF-8.  */
162   count = utf8_wctomb ((unsigned char *) inbuf, code);
163   if (count < 0)
164     return failure (code, N_("character out of range"), callback_arg);
165
166 #if HAVE_ICONV
167   if (!is_utf8)
168     {
169       char outbuf[25];
170       const char *inptr;
171       size_t inbytesleft;
172       char *outptr;
173       size_t outbytesleft;
174       size_t res;
175
176       inptr = inbuf;
177       inbytesleft = count;
178       outptr = outbuf;
179       outbytesleft = sizeof (outbuf);
180
181       /* Convert the character from UTF-8 to the locale's charset.  */
182       res = iconv (utf8_to_local,
183                    (ICONV_CONST char **)&inptr, &inbytesleft,
184                    &outptr, &outbytesleft);
185       if (inbytesleft > 0 || res == (size_t)(-1)
186           /* Irix iconv() inserts a NUL byte if it cannot convert. */
187 # if !defined _LIBICONV_VERSION && (defined sgi || defined __sgi)
188           || (res > 0 && code != 0 && outptr - outbuf == 1 && *outbuf == '\0')
189 # endif
190          )
191         return failure (code, NULL, callback_arg);
192
193       /* Avoid glibc-2.1 bug and Solaris 2.7 bug.  */
194 # if defined _LIBICONV_VERSION \
195     || !((__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) || defined __sun)
196
197       /* Get back to the initial shift state.  */
198       res = iconv (utf8_to_local, NULL, NULL, &outptr, &outbytesleft);
199       if (res == (size_t)(-1))
200         return failure (code, NULL, callback_arg);
201 # endif
202
203       return success (outbuf, outptr - outbuf, callback_arg);
204     }
205 #endif
206
207   /* At this point, is_utf8 is true, so no conversion is needed.  */
208   return success (inbuf, count, callback_arg);
209 }
210
211 /* Simple success callback that outputs the converted string.
212    The STREAM is passed as callback_arg.  */
213 long
214 fwrite_success_callback (const char *buf, size_t buflen, void *callback_arg)
215 {
216   FILE *stream = (FILE *) callback_arg;
217
218   fwrite (buf, 1, buflen, stream);
219   return 0;
220 }
221
222 /* Simple failure callback that displays an error and exits.  */
223 static long
224 exit_failure_callback (unsigned int code, const char *msg, void *callback_arg)
225 {
226   if (msg == NULL)
227     error (1, 0, _("cannot convert U+%04X to local character set"), code);
228   else
229     error (1, 0, _("cannot convert U+%04X to local character set: %s"), code,
230            gettext (msg));
231   return -1;
232 }
233
234 /* Simple failure callback that displays a fallback representation in plain
235    ASCII, using the same notation as ISO C99 strings.  */
236 static long
237 fallback_failure_callback (unsigned int code, const char *msg, void *callback_arg)
238 {
239   FILE *stream = (FILE *) callback_arg;
240
241   if (code < 0x10000)
242     fprintf (stream, "\\u%04X", code);
243   else
244     fprintf (stream, "\\U%08X", code);
245   return -1;
246 }
247
248 /* Outputs the Unicode character CODE to the output stream STREAM.
249    Upon failure, exit if exit_on_error is true, otherwise output a fallback
250    notation.  */
251 void
252 print_unicode_char (FILE *stream, unsigned int code, int exit_on_error)
253 {
254   unicode_to_mb (code, fwrite_success_callback,
255                  exit_on_error
256                  ? exit_failure_callback
257                  : fallback_failure_callback,
258                  stream);
259 }