summaryrefslogtreecommitdiff
path: root/src/aliased_struct-inl.h
diff options
context:
space:
mode:
authorJames M Snell <jasnell@gmail.com>2020-04-10 19:42:37 -0700
committerAnna Henningsen <anna@addaleax.net>2020-04-14 02:21:43 +0200
commitcecb08f0c828dd5da8e4c6f8414bb1f9c778319e (patch)
tree04352ecba6680b8a689c0b3ea8f620de84c5c7b5 /src/aliased_struct-inl.h
parent81c03bcebd3841e5bcbd3af0a03e102b80d10d12 (diff)
downloadnode-new-cecb08f0c828dd5da8e4c6f8414bb1f9c778319e.tar.gz
src: add AliasedStruct utility
For http2 (and eventually QUIC) we have a struct that is backed by a v8::BackingStore and exposed to the JavaScript side as an ArrayBuffer and TypedArray. This is similar to AliasedBuffer except that it is fronted by a struct on the C++ side. ```c++ struct foo { uint32_t ex1; uint32_t ex2; }; AliasedStruct<foo> foo_; foo_->ex1 = 1; foo_->ex2 = 2; foo_.GetArrayBuffer(); ``` Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: https://github.com/nodejs/node/pull/32778 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Diffstat (limited to 'src/aliased_struct-inl.h')
-rw-r--r--src/aliased_struct-inl.h54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/aliased_struct-inl.h b/src/aliased_struct-inl.h
new file mode 100644
index 0000000000..17d5ff5809
--- /dev/null
+++ b/src/aliased_struct-inl.h
@@ -0,0 +1,54 @@
+#ifndef SRC_ALIASED_STRUCT_INL_H_
+#define SRC_ALIASED_STRUCT_INL_H_
+
+#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
+
+#include "aliased_struct.h"
+#include "v8.h"
+#include <memory>
+
+namespace node {
+
+template <typename T>
+template <typename... Args>
+AliasedStruct<T>::AliasedStruct(v8::Isolate* isolate, Args&&... args)
+ : isolate_(isolate) {
+ const v8::HandleScope handle_scope(isolate);
+
+ store_ = v8::ArrayBuffer::NewBackingStore(isolate, sizeof(T));
+ ptr_ = new (store_->Data()) T(std::forward<Args>(args)...);
+ DCHECK_NOT_NULL(ptr_);
+
+ v8::Local<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(isolate, store_);
+ buffer_ = v8::Global<v8::ArrayBuffer>(isolate, buffer);
+}
+
+template <typename T>
+AliasedStruct<T>::AliasedStruct(const AliasedStruct& that)
+ : AliasedStruct(that.isolate_, *that) {}
+
+template <typename T>
+AliasedStruct<T>& AliasedStruct<T>::operator=(
+ AliasedStruct<T>&& that) noexcept {
+ this->~AliasedStruct();
+ isolate_ = that.isolate_;
+ store_ = that.store_;
+ ptr_ = that.ptr_;
+
+ buffer_ = std::move(that.buffer_);
+
+ that.ptr_ = nullptr;
+ that.store_.reset();
+ return *this;
+}
+
+template <typename T>
+AliasedStruct<T>::~AliasedStruct() {
+ if (ptr_ != nullptr) ptr_->~T();
+}
+
+} // namespace node
+
+#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
+
+#endif // SRC_ALIASED_STRUCT_INL_H_