iconvConvert.cc Source File

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
iconvConvert.cc
Go to the documentation of this file.
1 /* iconvConvert.cc
2 */
3 #include "osl/misc/iconvConvert.h"
4 #include <cstdlib>
5 #include <cstring>
6 #ifndef _WIN32
7 #include <iconv.h>
8
9 struct osl::misc::IconvConvert::IconvCD
10 {
11 iconv_t cd;
12 IconvCD(const std::string& fromcode, const std::string& tocode)
13 {
14 cd = iconv_open(tocode.c_str(), fromcode.c_str());
15 }
16 ~IconvCD()
17 {
18 iconv_close(cd);
19 }
20 };
21
22
23 std::string osl::misc::
24 IconvConvert::langToIconvCode(const std::string& lang)
25 {
26 if (lang.empty())
27 return "";
28 const bool euc_jp =
29 (lang.find("jp") != lang.npos || lang.find("JP") != lang.npos)
30 && (lang.find("euc") != lang.npos || lang.find("EUC") != lang.npos);
31 if (euc_jp)
32 return "EUC-JP";
33 const bool shift_jis =
34 (lang.find("sjis") != lang.npos || lang.find("SJIS") != lang.npos);
35 if (shift_jis)
36 return "SHIFT_JIS";
37 const bool utf8 =
38 (lang.find("UTF-8") != lang.npos || lang.find("UTF8") != lang.npos);
39 if (utf8)
40 return "UTF-8";
41 return "";
42 }
43
44 std::string osl::misc::
45 IconvConvert::eucToLang(const std::string& src)
46 {
47 static const char *lang = getenv("LANG");
48 if (! lang)
49 return "";
50 static const std::string tocode = langToIconvCode(lang);
51 if (tocode.empty())
52 return "";
53 if ("EUC-JP" == tocode)
54 return src;
55 IconvCD cd("EUC-JP", tocode);
56 return convert(cd, src);
57 }
58
59 std::string osl::misc::
60 IconvConvert::convert(const std::string& fromcode,
61 const std::string& tocode,
62 const std::string& src)
63 {
64 if (fromcode == tocode)
65 return src;
66 IconvCD cd(fromcode, tocode);
67 return convert(cd, src);
68 }
69
70 std::string osl::misc::
71 IconvConvert::convert(IconvCD& cd, const std::string& src)
72 {
73 const char * inbuf = src.c_str();
74 char outbuf[1024], *outbufptr = outbuf;
75 size_t inbytesleft = src.size(), outbytesleft = 1024;
76 #if (defined __linux__ || defined __APPLE__)
77 typedef char ** iconv_inbuf_t;
78 #else
79 typedef const char ** iconv_inbuf_t;
80 #endif
81 std::string ret;
82 int success;
83 while ((success = iconv(cd.cd, (iconv_inbuf_t)&inbuf, &inbytesleft,
84 &outbufptr, &outbytesleft)) >= 0
85 && inbytesleft > 0)
86 if (outbufptr - outbuf >= 512)
87 {
88 ret += std::string(outbuf, outbufptr);
89 outbufptr = outbuf;
90 }
91 if (success == -1)
92 return "";
93 ret += std::string(outbuf, outbufptr);
94 return ret;
95 }
96
97 #endif /* _WIN32 */
98 // ;;; Local Variables:
99 // ;;; mode:c++
100 // ;;; c-basic-offset:2
101 // ;;; End: