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