4
0

utf8.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* Charset handling for GNU tar.
  2. Copyright (C) 2004 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify it
  4. under the terms of the GNU General Public License as published by the
  5. Free Software Foundation; either version 2, or (at your option) any later
  6. version.
  7. This program is distributed in the hope that it will be useful, but
  8. WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  10. Public License for more details.
  11. You should have received a copy of the GNU General Public License along
  12. with this program; if not, write to the Free Software Foundation, Inc.,
  13. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. #include <system.h>
  15. #include <quotearg.h>
  16. #include <localcharset.h>
  17. #include "common.h"
  18. #ifdef HAVE_ICONV_H
  19. # include <iconv.h>
  20. #endif
  21. #ifndef ICONV_CONST
  22. # define ICONV_CONST
  23. #endif
  24. #ifndef HAVE_ICONV
  25. # undef iconv_open
  26. # define iconv_open(tocode, fromcode) ((iconv_t) -1)
  27. # undef iconv
  28. # define iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft) ((size_t) 0)
  29. # undef iconv_close
  30. # define iconv_close(cd) 0
  31. #endif
  32. static iconv_t conv_desc[2] = { (iconv_t) -1, (iconv_t) -1 };
  33. static iconv_t
  34. utf8_init (bool to_utf)
  35. {
  36. if (conv_desc[(int) to_utf] == (iconv_t) -1)
  37. {
  38. if (to_utf)
  39. conv_desc[(int) to_utf] = iconv_open ("UTF-8", locale_charset ());
  40. else
  41. conv_desc[(int) to_utf] = iconv_open (locale_charset (), "UTF-8");
  42. }
  43. return conv_desc[(int) to_utf];
  44. }
  45. bool
  46. utf8_convert (bool to_utf, char const *input, char **output)
  47. {
  48. char ICONV_CONST *ib;
  49. char *ob;
  50. size_t inlen;
  51. size_t outlen;
  52. size_t rc;
  53. iconv_t cd = utf8_init (to_utf);
  54. if (cd == 0)
  55. {
  56. *output = xstrdup (input);
  57. return true;
  58. }
  59. else if (cd == (iconv_t)-1)
  60. return false;
  61. inlen = strlen (input) + 1;
  62. outlen = inlen * MB_LEN_MAX + 1;
  63. ob = *output = xmalloc (outlen);
  64. ib = (char ICONV_CONST *) input;
  65. rc = iconv (cd, &ib, &inlen, &ob, &outlen);
  66. *ob = 0;
  67. return rc != -1;
  68. }
  69. bool
  70. string_ascii_p (const char *str)
  71. {
  72. const unsigned char *p = (const unsigned char *)str;
  73. for (; *p; p++)
  74. if (*p > 127)
  75. return false;
  76. return true;
  77. }