Skip to content

Commit

Permalink
Merge pull request #10 from zombieyang/arraybuffer
Browse files Browse the repository at this point in the history
implement some new ArrayBuffer api
  • Loading branch information
zombieyang authored Mar 22, 2024
2 parents 9e18632 + b44bb4c commit 9197acb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions include/v8.h
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,11 @@ class V8_EXPORT BackingStore {
void* data_;

size_t byte_length_;

using DeleterCallback = void (*)(void* data, size_t length,
void* deleter_data);

static void EmptyDeleter(void* data, size_t length, void* deleter_data) {}
};

class V8_EXPORT ArrayBuffer : public Object {
Expand Down Expand Up @@ -706,8 +711,15 @@ class V8_EXPORT ArrayBuffer : public Object {
static Local<ArrayBuffer> New(Isolate* isolate, void* data, size_t byte_length,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);

static Local<ArrayBuffer> New(Isolate* isolate,
std::shared_ptr<BackingStore> backing_store);

Contents GetContents();

static std::unique_ptr<BackingStore> NewBackingStore(
void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
void* deleter_data);

std::shared_ptr<BackingStore> GetBackingStore();

V8_INLINE static ArrayBuffer* Cast(class Value* obj) {
Expand Down
20 changes: 20 additions & 0 deletions src/v8-impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -695,12 +695,32 @@ Local<ArrayBuffer> ArrayBuffer::New(Isolate* isolate, void* data, size_t byte_le
return Local<ArrayBuffer>(ab);
}

Local<ArrayBuffer> ArrayBuffer::New(Isolate* isolate, std::shared_ptr<BackingStore> backing_store) {
ArrayBuffer *ab = isolate->Alloc<ArrayBuffer>();
ab->value_ = JS_NewArrayBuffer(isolate->current_context_->context_, (uint8_t*)backing_store->Data(), backing_store->ByteLength(),
nullptr, nullptr, false);
return Local<ArrayBuffer>(ab);
}

ArrayBuffer::Contents ArrayBuffer::GetContents() {
ArrayBuffer::Contents ret;
ret.data_ = JS_GetArrayBuffer(Isolate::current_->current_context_->context_, &ret.byte_length_, value_);
return ret;
}

std::unique_ptr<BackingStore> ArrayBuffer::NewBackingStore(
void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
void* deleter_data
) {
V8::Check(deleter == BackingStore::EmptyDeleter, "only BackingStore::EmptyDeleter support!");

BackingStore *ret = new BackingStore;
ret->data_ = data;
ret->byte_length_ = byte_length;
std::unique_ptr<BackingStore> ptr(ret);
return ptr;
}

std::shared_ptr<BackingStore> ArrayBuffer::GetBackingStore() {
BackingStore *ret = new BackingStore;
ret->data_ = JS_GetArrayBuffer(Isolate::current_->current_context_->context_, &ret->byte_length_, value_);
Expand Down

0 comments on commit 9197acb

Please sign in to comment.