4 Website: http://www.vultaire.net/software/jben/
5 License: GNU General Public License (GPL) version 2
6 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt)
8 File: encoding_convert.h
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>
24 #ifndef encoding_convert_h
25 #define encoding_convert_h
33 #define utfconv_wm(data) ConvertString<wchar_t, char>(data, wcType.c_str(), "UTF-8")
34 #define utfconv_mw(data) ConvertString<char, wchar_t>(data, "UTF-8", wcType.c_str())
36 template <class tsrc
, class tdest
>
37 basic_string
<tdest
> ConvertString
38 (const basic_string
<tsrc
>& sourceData
,
39 const char* sourceEncoding
,
40 const char* targetEncoding
) {
41 basic_string
<tdest
> result
;
42 size_t inputBytesLeft
= (sourceData
.length()+1) * sizeof(tsrc
);
44 /* Set sizing vars, and create a byte buffer sufficiently large for any
46 size_t outputBytesLeft
=
47 (inputBytesLeft
) * (sizeof(wchar_t) / sizeof(tsrc
));
48 char *buffer
= new char[outputBytesLeft
+ sizeof(wchar_t)];
49 memset((void*)buffer
, 0, outputBytesLeft
+ sizeof(wchar_t));
50 /* The libc iconv function takes a char* source, while the libiconv iconv
51 takes a const char* source. */
53 const char *srcData
= (char *)sourceData
.c_str();
55 char *srcData
= (char *)sourceData
.c_str();
58 char *destData
= buffer
;
62 iconv_t conv
= iconv_open(targetEncoding
, sourceEncoding
);
63 if(conv
== (iconv_t
)-1) goto exit_now
;
65 &srcData
, &inputBytesLeft
,
66 &destData
, &outputBytesLeft
);
67 if(retcode
==(size_t)-1) {
68 /* If we put in error reporting later, we'll want this to return
69 conversion errors. For now though, we'll do nothing and simply
75 /* Copy result data to the string or wstring */
76 result
= (tdest
*) buffer
;