Repository navigation
Expand file tree
/
Copy pathBase64Binding.cpp
More file actions
72 lines (62 loc) · 2.02 KB
/
Copy pathBase64Binding.cpp
File metadata and controls
72 lines (62 loc) · 2.02 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
#include "ns/Base64Binding.h"
#include <vector>
#include "ns/Base64.h"
namespace nativescript::common::base64 {
namespace {
// The string's code units as bytes. Fails when any unit is above U+00FF,
// which neither op can represent.
bool GetLatin1Bytes(v8::Isolate* isolate, v8::Local<v8::Value> value,
std::vector<uint8_t>* out) {
if (!value->IsString()) {
return false;
}
v8::Local<v8::String> str = value.As<v8::String>();
if (!str->ContainsOnlyOneByte()) {
return false;
}
const int length = str->Length();
out->resize(static_cast<size_t>(length));
if (length > 0) {
str->WriteOneByteV2(isolate, 0, static_cast<uint32_t>(length), out->data());
}
return true;
}
void ReturnOneByte(const v8::FunctionCallbackInfo<v8::Value>& info,
const uint8_t* data, size_t length) {
v8::Isolate* isolate = info.GetIsolate();
if (length == 0) {
info.GetReturnValue().Set(v8::String::Empty(isolate));
return;
}
v8::Local<v8::String> result;
if (v8::String::NewFromOneByte(isolate, data, v8::NewStringType::kNormal,
static_cast<int>(length))
.ToLocal(&result)) {
info.GetReturnValue().Set(result);
}
}
} // namespace
void Btoa(const v8::FunctionCallbackInfo<v8::Value>& info) {
std::vector<uint8_t> input;
if (!GetLatin1Bytes(info.GetIsolate(), info[0], &input)) {
info.GetReturnValue().SetNull();
return;
}
const std::string out = Encode(input.data(), input.size());
ReturnOneByte(info, reinterpret_cast<const uint8_t*>(out.data()), out.size());
}
void Atob(const v8::FunctionCallbackInfo<v8::Value>& info) {
std::vector<uint8_t> input;
if (!GetLatin1Bytes(info.GetIsolate(), info[0], &input)) {
info.GetReturnValue().SetNull();
return;
}
const std::optional<std::vector<uint8_t>> out =
ForgivingDecode(input.data(), input.size());
if (!out) {
info.GetReturnValue().SetNull();
return;
}
ReturnOneByte(info, out->data(), out->size());
}
} // namespace nativescript::common::base64