5af8456dd2964cb0daf27d30ac208db3d50be5dd
[debian/tar] / src / utf8.c
1 /* Charset handling for GNU tar.
2
3    Copyright 2004, 2006-2007, 2013 Free Software Foundation, Inc.
4
5    This file is part of GNU tar.
6
7    GNU tar is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    GNU tar is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include <system.h>
21 #include <quotearg.h>
22 #include <localcharset.h>
23 #include "common.h"
24 #ifdef HAVE_ICONV_H
25 # include <iconv.h>
26 #endif
27
28 #ifndef ICONV_CONST
29 # define ICONV_CONST
30 #endif
31
32 #ifndef HAVE_ICONV
33
34 # undef iconv_open
35 # define iconv_open(tocode, fromcode) ((iconv_t) -1)
36
37 # undef iconv
38 # define iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft) ((size_t) 0)
39
40 # undef iconv_close
41 # define iconv_close(cd) 0
42
43 #endif
44
45
46 \f
47
48 static iconv_t conv_desc[2] = { (iconv_t) -1, (iconv_t) -1 };
49
50 static iconv_t
51 utf8_init (bool to_utf)
52 {
53   if (conv_desc[(int) to_utf] == (iconv_t) -1)
54     {
55       if (to_utf)
56         conv_desc[(int) to_utf] = iconv_open ("UTF-8", locale_charset ());
57       else
58         conv_desc[(int) to_utf] = iconv_open (locale_charset (), "UTF-8");
59     }
60   return conv_desc[(int) to_utf];
61 }
62
63 bool
64 utf8_convert (bool to_utf, char const *input, char **output)
65 {
66   char ICONV_CONST *ib;
67   char *ob;
68   size_t inlen;
69   size_t outlen;
70   size_t rc;
71   iconv_t cd = utf8_init (to_utf);
72
73   if (cd == 0)
74     {
75       *output = xstrdup (input);
76       return true;
77     }
78   else if (cd == (iconv_t)-1)
79     return false;
80
81   inlen = strlen (input) + 1;
82   outlen = inlen * MB_LEN_MAX + 1;
83   ob = *output = xmalloc (outlen);
84   ib = (char ICONV_CONST *) input;
85   rc = iconv (cd, &ib, &inlen, &ob, &outlen);
86   *ob = 0;
87   return rc != -1;
88 }
89 \f
90
91 bool
92 string_ascii_p (char const *p)
93 {
94   for (; *p; p++)
95     if (*p & ~0x7f)
96       return false;
97   return true;
98 }