-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathencoding.cpp
More file actions
73 lines (61 loc) · 1.54 KB
/
encoding.cpp
File metadata and controls
73 lines (61 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "encoding.h"
#include <iconv.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
Encoding* encIn = new Encoding("GBK", "UTF-8");
Encoding* encOut = new Encoding("UTF-8", "GBK");
Encoding::Encoding(const string &fromCharset, const string &toCharset)
{
//iconv_open is a freek(to goes first)
mIconv = iconv_open(toCharset.c_str(), fromCharset.c_str());
}
Encoding::~Encoding()
{
if (mIconv != (iconv_t)-1)
iconv_close(mIconv);
}
vector<char> Encoding::convert(const vector<char> &str)
{
vector<char> result(str.size()*3);
auto len = result.size();
if (convert(str.data(), str.size(), result.data(), &len))
{
result.resize(len);
result.shrink_to_fit();
return result;
}
return str;
}
string Encoding::convert(const string &str)
{
auto len = str.length()*3;
unique_ptr<char[]> buf(new char[len]);
if (convert(str.data(), str.size(), buf.get(), &len))
{
string result = buf.get();
return result;
}
return str;
}
bool Encoding::convert(const char *input, size_t len, char *output, size_t *outLen)
{
if (mIconv == (iconv_t)-1)
return false;
//copy in str
size_t inLen = len;
auto inBuf = unique_ptr<char[]>(new char[inLen+1]);
char* pIn = inBuf.get();
memcpy(pIn, input, inLen);
pIn[inLen]=0;
//do convert
int ret = iconv(mIconv, &pIn, &inLen, &output, outLen);
if (ret == -1)
{
perror("convert failed");
return false;
}
*output = 0;
return true;
}