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
74
75
76
77
|
/*
* Copyright (c) 2012 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <unicode/ustring.h>
#include <cassert>
#include <string>
#include <vector>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
class ICUConverter {
public:
typedef std::vector<UChar, SafeAllocator<UChar> > ICUString;
template<typename T>
ICUString convertToICUString(const T& s) {
ICUString result;
result.resize(s.size());
UErrorCode status = U_ZERO_ERROR;
int icuResultLength = result.size();
u_strFromUTF8Lenient(vecptr(result), result.size(), &icuResultLength, toConstCharArray(s), s.size(), &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
result.resize(icuResultLength);
u_strFromUTF8Lenient(vecptr(result), result.size(), &icuResultLength, toConstCharArray(s), s.size(), &status);
}
if (U_FAILURE(status)) {
return ICUString();
}
result.resize(icuResultLength);
return result;
}
std::string convertToString(const ICUString& input) {
return std::string(vecptr(convertToArray(input)));
}
std::vector<char, SafeAllocator<char> > convertToArray(const ICUString& input) {
std::vector<char, SafeAllocator<char> > result;
result.resize(input.size());
UErrorCode status = U_ZERO_ERROR;
int inputLength = result.size();
u_strToUTF8(vecptr(result), result.size(), &inputLength, vecptr(input), input.size(), &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
result.resize(inputLength);
u_strToUTF8(vecptr(result), result.size(), &inputLength, vecptr(input), input.size(), &status);
}
if (U_FAILURE(status)) {
return std::vector<char, SafeAllocator<char> >();
}
result.resize(inputLength + 1);
result[result.size() - 1] = '\0';
return result;
}
private:
static const char* toConstCharArray(const std::string& input) {
return input.c_str();
}
static const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) {
return reinterpret_cast<const char*>(vecptr(input));
}
};
}
|