Repository navigation
Expand file tree
/
Copy pathV8Helpers.cpp
More file actions
68 lines (59 loc) · 1.84 KB
/
Copy pathV8Helpers.cpp
File metadata and controls
68 lines (59 loc) · 1.84 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
#include "ns/V8Helpers.h"
#include <cstdint>
#include <vector>
#include "ns/Utf8.h"
namespace nativescript::common {
namespace {
bool ToStringLocal(v8::Isolate* isolate, v8::Local<v8::Value> value,
v8::Local<v8::String>& out) {
if (value.IsEmpty()) {
return false;
}
if (value->IsString()) {
out = value.As<v8::String>();
return true;
}
if (value->IsStringObject()) {
out = value.As<v8::StringObject>()->ValueOf();
return true;
}
v8::TryCatch tc(isolate);
return value->ToString(isolate->GetCurrentContext()).ToLocal(&out);
}
} // namespace
std::string ToString(v8::Isolate* isolate, v8::Local<v8::Value> value) {
v8::Local<v8::String> str;
if (!ToStringLocal(isolate, value, str)) {
return std::string();
}
{
v8::String::ValueView view(isolate, str);
if (view.is_one_byte()) {
const uint8_t* data = view.data8();
const uint32_t length = static_cast<uint32_t>(view.length());
uint32_t i = 0;
while (i < length && data[i] < 0x80) {
i++;
}
// Latin-1 above 0x7F still needs widening, which the encode below does.
if (i == length) {
return std::string(reinterpret_cast<const char*>(data), length);
}
}
}
const size_t length = str->Utf8LengthV2(isolate);
std::string result(length, '\0');
if (length > 0) {
str->WriteUtf8V2(isolate, result.data(), length,
v8::String::WriteFlags::kReplaceInvalidUtf8);
}
return result;
}
std::optional<std::string> ToExactUtf8(v8::Isolate* isolate,
v8::Local<v8::String> value) {
const uint32_t length = static_cast<uint32_t>(value->Length());
std::vector<uint16_t> units(length);
value->WriteV2(isolate, 0, length, units.data());
return Utf16ToExactUtf8(units.data(), units.size());
}
} // namespace nativescript::common