#ifndef ADDON_UTILITIES_H #define ADDON_UTILITIES_H #include using namespace v8; class NativeString { char *data; size_t length; char utf8ValueMemory[sizeof(String::Utf8Value)]; String::Utf8Value *utf8Value = nullptr; bool invalid = false; public: NativeString(Isolate *isolate, const Local &value) { if (value->IsUndefined()) { data = nullptr; length = 0; } else if (value->IsString()) { utf8Value = new (utf8ValueMemory) String::Utf8Value(isolate, value); data = (**utf8Value); length = utf8Value->length(); } else if (value->IsTypedArray()) { Local arrayBufferView = Local::Cast(value); ArrayBuffer::Contents contents = arrayBufferView->Buffer()->GetContents(); length = contents.ByteLength(); data = (char *) contents.Data(); } else if (value->IsArrayBuffer()) { Local arrayBuffer = Local::Cast(value); ArrayBuffer::Contents contents = arrayBuffer->GetContents(); length = contents.ByteLength(); data = (char *) contents.Data(); } else { invalid = true; } } bool isInvalid(const FunctionCallbackInfo &args) { if (invalid) { args.GetReturnValue().Set(isolate->ThrowException(String::NewFromUtf8(isolate, "Text and data can only be passed by String, ArrayBuffer or TypedArray."))); } return invalid; } std::string_view getString() { return {data, length}; } ~NativeString() { if (utf8Value) { utf8Value->~Utf8Value(); } } }; #endif