Repository navigation
Expand file tree
/
Copy pathTextDecoder.cpp
More file actions
231 lines (206 loc) · 8 KB
/
Copy pathTextDecoder.cpp
File metadata and controls
231 lines (206 loc) · 8 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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include <Babylon/Polyfills/TextDecoder.h>
#include <napi/napi.h>
#include <cstring>
#include <string>
namespace
{
// Normalize an encoding label per the WHATWG Encoding Standard "get an encoding"
// algorithm: strip leading/trailing ASCII whitespace and ASCII-lowercase the result.
std::string NormalizeEncodingLabel(const std::string& encoding)
{
const auto isAsciiWhitespace = [](char c) {
return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' ';
};
size_t begin = 0;
size_t end = encoding.size();
while (begin < end && isAsciiWhitespace(encoding[begin]))
{
++begin;
}
while (end > begin && isAsciiWhitespace(encoding[end - 1]))
{
--end;
}
std::string label = encoding.substr(begin, end - begin);
for (auto& c : label)
{
if (c >= 'A' && c <= 'Z')
{
c = static_cast<char>(c - 'A' + 'a');
}
}
return label;
}
class TextDecoder final : public Napi::ObjectWrap<TextDecoder>
{
// Only the encodings the runtime actually needs. UTF-16 shows up in Emscripten output
// (UTF16ToString creates a `new TextDecoder('utf-16le')` at module scope), so refusing
// it makes whole WebAssembly modules unloadable.
enum class Encoding
{
Utf8,
Utf16LittleEndian,
Utf16BigEndian
};
public:
static void Initialize(Napi::Env env)
{
Napi::HandleScope scope{env};
static constexpr auto JS_TEXTDECODER_CONSTRUCTOR_NAME = "TextDecoder";
if (env.Global().Get(JS_TEXTDECODER_CONSTRUCTOR_NAME).IsUndefined())
{
Napi::Function func = DefineClass(
env,
JS_TEXTDECODER_CONSTRUCTOR_NAME,
{
InstanceMethod("decode", &TextDecoder::Decode),
});
env.Global().Set(JS_TEXTDECODER_CONSTRUCTOR_NAME, func);
}
}
explicit TextDecoder(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<TextDecoder>{info}
{
if (info.Length() > 0 && info[0].IsString())
{
auto encoding = info[0].As<Napi::String>().Utf8Value();
// Several labels (e.g. "utf8", "unicode-1-1-utf-8") all map to UTF-8 after
// normalization; callers such as the glTF/Draco loader pass "utf8".
const std::string label = NormalizeEncodingLabel(encoding);
if (label == "utf-8" ||
label == "utf8" ||
label == "unicode-1-1-utf-8" ||
label == "unicode11utf8" ||
label == "unicode20utf8" ||
label == "x-unicode20utf8")
{
m_encoding = Encoding::Utf8;
}
else if (label == "utf-16" ||
label == "utf-16le" ||
label == "ucs-2" ||
label == "unicode" ||
label == "unicodefeff" ||
label == "csunicode" ||
label == "iso-10646-ucs-2")
{
m_encoding = Encoding::Utf16LittleEndian;
}
else if (label == "utf-16be" ||
label == "unicodefffe")
{
m_encoding = Encoding::Utf16BigEndian;
}
else
{
throw Napi::Error::New(Env(), "TextDecoder: unsupported encoding '" + encoding + "', only UTF-8 and UTF-16 are supported");
}
}
}
private:
Encoding m_encoding{Encoding::Utf8};
Napi::Value DecodeUtf16(Napi::Env env, const std::string& data) const
{
// WHATWG UTF-16 decoder in replacement mode: unpaired surrogates and a
// leftover odd byte become U+FFFD. A lead surrogate followed by a
// non-trail is one replacement, then the second unit is reprocessed.
const bool littleEndian = m_encoding == Encoding::Utf16LittleEndian;
std::u16string units;
units.reserve(data.size() / 2 + 1);
constexpr char16_t LEAD_MIN = 0xD800;
constexpr char16_t LEAD_MAX = 0xDBFF;
constexpr char16_t TRAIL_MIN = 0xDC00;
constexpr char16_t TRAIL_MAX = 0xDFFF;
constexpr char16_t REPLACEMENT = 0xFFFD;
bool pendingLead = false;
char16_t lead = 0;
size_t byteIndex = 0;
while (byteIndex + 1 < data.size())
{
const auto first = static_cast<unsigned char>(data[byteIndex]);
const auto second = static_cast<unsigned char>(data[byteIndex + 1]);
byteIndex += 2;
const auto unit = littleEndian
? static_cast<char16_t>(first | (second << 8))
: static_cast<char16_t>(second | (first << 8));
if (pendingLead)
{
pendingLead = false;
if (unit >= TRAIL_MIN && unit <= TRAIL_MAX)
{
units.push_back(lead);
units.push_back(unit);
continue;
}
units.push_back(REPLACEMENT);
// Fall through and reprocess `unit` as a standalone code unit.
}
if (unit >= LEAD_MIN && unit <= LEAD_MAX)
{
pendingLead = true;
lead = unit;
}
else if (unit >= TRAIL_MIN && unit <= TRAIL_MAX)
{
units.push_back(REPLACEMENT);
}
else
{
units.push_back(unit);
}
}
// End-of-queue: an unpaired lead and/or leftover odd byte is one error.
if (pendingLead || byteIndex < data.size())
{
units.push_back(REPLACEMENT);
}
if (!units.empty() && units.front() == u'\uFEFF')
{
units.erase(0, 1);
}
return Napi::String::New(env, units);
}
Napi::Value Decode(const Napi::CallbackInfo& info)
{
if (info.Length() < 1 || info[0].IsUndefined())
{
return Napi::String::New(info.Env(), "");
}
std::string data;
if (info[0].IsTypedArray())
{
auto typedArray = info[0].As<Napi::TypedArray>();
auto arrayBuffer = typedArray.ArrayBuffer();
auto byteOffset = typedArray.ByteOffset();
auto byteLength = typedArray.ByteLength();
data.resize(byteLength);
if (byteLength > 0)
{
std::memcpy(data.data(), static_cast<uint8_t*>(arrayBuffer.Data()) + byteOffset, byteLength);
}
}
else if (info[0].IsArrayBuffer())
{
auto arrayBuffer = info[0].As<Napi::ArrayBuffer>();
auto byteLength = arrayBuffer.ByteLength();
data.resize(byteLength);
if (byteLength > 0)
{
std::memcpy(data.data(), arrayBuffer.Data(), byteLength);
}
}
else
{
throw Napi::TypeError::New(Env(), "TextDecoder.decode: input must be a BufferSource (ArrayBuffer or TypedArray)");
}
return m_encoding == Encoding::Utf8 ? Napi::String::New(info.Env(), data) : DecodeUtf16(info.Env(), data);
}
};
}
namespace Babylon::Polyfills::TextDecoder
{
void BABYLON_API Initialize(Napi::Env env)
{
::TextDecoder::Initialize(env);
}
}