-
Notifications
You must be signed in to change notification settings - Fork 0
/
utf8conv.h
124 lines (110 loc) · 2.37 KB
/
utf8conv.h
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#pragma once
#include <Windows.h>
#include <string>
#include <stdexcept>
#include "utf8except.h"
std::wstring Utf8ToUtf16(const std::string& utf8)
{
std::wstring utf16; // Result
if (utf8.empty())
{
return utf16;
}
// Safely fails if an invalid UTF-8 character
// is encountered in the input string
constexpr DWORD kFlags = MB_ERR_INVALID_CHARS;
if (utf8.length() > static_cast<size_t>((std::numeric_limits<int>::max)()))
{
throw std::overflow_error(
"Input string too long: size_t-length doesn't fit into int.");
}
const int utf8Length = static_cast<int>(utf8.length());
const int utf16Length = ::MultiByteToWideChar(
CP_UTF8,
kFlags,
utf8.data(),
utf8Length,
nullptr,
0
);
if (utf16Length == 0)
{
// Conversion error: capture error code and throw
const DWORD error = ::GetLastError();
throw Utf8ConversionException(
"Cannot get result sring length when converting " \
"from UTF-8 to UTF-16 (MultiByteToWideChar failed).",
error);
}
utf16.resize(utf16Length);
int result = ::MultiByteToWideChar(
CP_UTF8,
kFlags,
utf8.data(),
utf8Length,
&utf16[0],
utf16Length
);
if (result == 0)
{
const DWORD error = ::GetLastError();
throw Utf8ConversionException(
"Cannot convert from UTF-8 to UTF-16 "\
"(MultiByteToWideChar failed).",
error);
}
return utf16;
}
std::string Utf16ToUtf8(const std::wstring& utf16)
{
std::string utf8; // Result
if (utf16.empty())
{
return utf8;
}
if (utf16.length() > static_cast<size_t>((std::numeric_limits<int>::max)()))
{
throw std::overflow_error(
"Input string too long: size_t-length doesn't fit into int.");
}
const int utf16Length = static_cast<int>(utf16.length());
const int utf8Length = ::WideCharToMultiByte(
CP_UTF8,
0,
utf16.data(),
utf16Length,
nullptr,
0,
NULL,
NULL
);
if (utf8Length == 0)
{
const DWORD error = ::GetLastError();
throw Utf8ConversionException(
"Cannot get result sring length when converting " \
"from UTF-16 to UTF-8 (WideCharToMultiByte failed).",
error
);
}
utf8.resize(utf8Length);
int result = ::WideCharToMultiByte(
CP_UTF8,
0,
utf16.data(),
utf16Length,
&utf8[0],
utf8Length,
NULL,
NULL
);
if (result == 0)
{
const DWORD error = ::GetLastError();
throw Utf8ConversionException(
"Cannot convert from UTF-16 to UTF-8 "\
"(WideCharToMultiByte failed).",
error);
}
return utf8;
}