Test and document --keep-directory-symlink
[tar.git] / src / utf8.c
bloba018ce0a9169b0868bada7ce0efd711e7cb5c26f
1 /* Charset handling for GNU tar.
3 Copyright 2004, 2006-2007, 2013-2014, 2016-2017 Free Software
4 Foundation, Inc.
6 This file is part of GNU tar.
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.
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.
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/>. */
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
29 #ifndef ICONV_CONST
30 # define ICONV_CONST
31 #endif
33 #ifndef HAVE_ICONV
35 # undef iconv_open
36 # define iconv_open(tocode, fromcode) ((iconv_t) -1)
38 # undef iconv
39 # define iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft) ((size_t) 0)
41 # undef iconv_close
42 # define iconv_close(cd) 0
44 #endif
49 static iconv_t conv_desc[2] = { (iconv_t) -1, (iconv_t) -1 };
51 static iconv_t
52 utf8_init (bool to_utf)
54 if (conv_desc[(int) to_utf] == (iconv_t) -1)
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");
61 return conv_desc[(int) to_utf];
64 bool
65 utf8_convert (bool to_utf, char const *input, char **output)
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);
74 if (cd == 0)
76 *output = xstrdup (input);
77 return true;
79 else if (cd == (iconv_t)-1)
80 return false;
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;
92 bool
93 string_ascii_p (char const *p)
95 for (; *p; p++)
96 if (*p & ~0x7f)
97 return false;
98 return true;