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