Renamed kpengine to jben_kpengine and made its data dir relocatable.
[jben.git] / encoding_convert.h
blob629752d1d95618acc70c71b62f9ff54a011813b7
1 /*
2 Project: J-Ben
3 Author: Paul Goins
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
27 #include <iconv.h>
28 #include <string>
29 using namespace std;
31 extern string wcType;
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
45 conversion. */
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. */
52 #ifdef __WXMSW__
53 const char *srcData = (char *)sourceData.c_str();
54 #else
55 char *srcData = (char *)sourceData.c_str();
56 #endif
58 char *destData = buffer;
60 /* libiconv stuff */
61 size_t retcode;
62 iconv_t conv = iconv_open(targetEncoding, sourceEncoding);
63 if(conv == (iconv_t)-1) goto exit_now;
64 retcode = iconv(conv,
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
70 bail. */
71 goto exit_now;
73 iconv_close(conv);
75 /* Copy result data to the string or wstring */
76 result = (tdest*) buffer;
78 exit_now:
79 delete[] buffer;
80 return result;
83 #endif