1 /***************************************************************************
2 * Copyright (C) 2008-2009 by Andrzej Rybczak *
3 * electricityispower@gmail.com *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
36 inline bool char_non_ascii(char ch
)
38 return (ch
& 0x80) != 0;
41 bool has_non_ascii_chars(const char *s
)
44 if (char_non_ascii(*s
))
49 bool has_non_ascii_chars(const std::string
&s
)
51 for (std::string::const_iterator it
= s
.begin(); it
!= s
.end(); ++it
)
52 if (char_non_ascii(*it
))
57 void charset_convert(const char *from
, const char *to
, const char *&inbuf
, bool delete_old
, size_t len
= 0)
59 if (!inbuf
|| !from
|| !to
)
62 iconv_t cd
= iconv_open(to
, from
);
64 if (cd
== iconv_t(-1))
69 size_t buflen
= len
*6+1;
70 char *outbuf
= new char[buflen
];
71 char *outstart
= outbuf
;
72 const char *instart
= inbuf
;
74 if (iconv(cd
, const_cast<ICONV_CONST
char **>(&inbuf
), &len
, &outbuf
, &buflen
) == size_t(-1))
89 void utf_to_locale(std::string
&s
)
91 if (s
.empty() || Config
.system_encoding
.empty() || !has_non_ascii_chars(s
))
93 const char *tmp
= strdup(s
.c_str());
94 charset_convert("utf-8", Config
.system_encoding
.c_str(), tmp
, 1, s
.length());
99 std::string
utf_to_locale_cpy(const std::string
&s
)
101 std::string result
= s
;
102 utf_to_locale(result
);
106 void locale_to_utf(std::string
&s
)
108 if (s
.empty() || Config
.system_encoding
.empty() || !has_non_ascii_chars(s
))
110 const char *tmp
= strdup(s
.c_str());
111 charset_convert(Config
.system_encoding
.c_str(), "utf-8", tmp
, 1, s
.length());
116 std::string
locale_to_utf_cpy(const std::string
&s
)
118 std::string result
= s
;
119 locale_to_utf(result
);
123 void utf_to_locale(const char *&s
, bool delete_old
)
125 if (!s
|| Config
.system_encoding
.empty() || !has_non_ascii_chars(s
))
127 charset_convert("utf-8", Config
.system_encoding
.c_str(), s
, delete_old
);
130 void locale_to_utf(const char *&s
, bool delete_old
)
132 if (!s
|| Config
.system_encoding
.empty() || !has_non_ascii_chars(s
))
134 charset_convert(Config
.system_encoding
.c_str(), "utf-8", s
, delete_old
);
137 #endif // HAVE_ICONV_H