This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_utils.cc
76 lines (60 loc) · 1.66 KB
/
shared_utils.cc
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
#include "shared_utils.h"
#include <iostream>
#include <v8.h>
typedef struct {
const uint8_t* data;
size_t size;
} serialized_value;
SharedUtils::SharedUtils() {
}
SharedUtils::~SharedUtils()
{
}
bool SharedUtils::serialize(napi_value value, Buffer & result)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueSerializer serializer(isolate);
serializer.WriteHeader();
v8::Local<v8::Value> v8_value = toV8LocalValue(value);
if (serializer.WriteValue(context, v8_value).FromMaybe(false)) {
auto data = serializer.Release();
serialized_value sv = { data.first, data.second };
for (int i = 0; i < sv.size; i++)
result.push_back(sv.data[i]);
return true;
}
return false;
}
bool SharedUtils::deserialize(ShmemBuffer & buf, napi_value & result)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::ValueDeserializer deserializer(isolate, (const uint8_t*)buf.data(), buf.size());
if (deserializer.ReadHeader(context).FromMaybe(false)) {
v8::MaybeLocal<v8::Value> value = deserializer.ReadValue(context);
if (!value.IsEmpty()) {
result = fromV8LocalValue(value.ToLocalChecked());
}
return true;
}
else
{
return false;
}
}
void SharedUtils::copy(Buffer & buf, ShmemBuffer & sbuf)
{
for (int i = 0; i < buf.size(); i++)
{
sbuf.push_back(buf[i]);
}
}
napi_value SharedUtils::fromV8LocalValue(v8::Local<v8::Value> local) {
return reinterpret_cast<napi_value>(*local);
}
v8::Local<v8::Value> SharedUtils::toV8LocalValue(napi_value v) {
v8::Local<v8::Value> local;
memcpy(&local, &v, sizeof(v));
return local;
}