From fb049cb934dc7f417bd299b1c78d783a1e29bd6d Mon Sep 17 00:00:00 2001 From: l3ops Date: Mon, 26 Oct 2020 08:57:14 +0100 Subject: [PATCH] Add Function::new_instance (#508) --- src/binding.cc | 8 ++++++++ src/function.rs | 21 +++++++++++++++++++++ tests/test_api.rs | 19 +++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/src/binding.cc b/src/binding.cc index b978d259..315c0f63 100644 --- a/src/binding.cc +++ b/src/binding.cc @@ -1285,6 +1285,14 @@ const v8::Value* v8__Function__Call(const v8::Function& self, argc, const_ptr_array_to_local_array(argv))); } +const v8::Object* v8__Function__NewInstance(const v8::Function& self, + const v8::Context& context, int argc, + const v8::Value* const argv[]) { + return maybe_local_to_ptr( + ptr_to_local(&self)->NewInstance(ptr_to_local(&context), + argc, const_ptr_array_to_local_array(argv))); +} + const v8::FunctionTemplate* v8__FunctionTemplate__New( v8::Isolate* isolate, v8::FunctionCallback callback = nullptr) { return local_to_ptr(v8::FunctionTemplate::New(isolate, callback)); diff --git a/src/function.rs b/src/function.rs index b334fbf5..8ccec99f 100644 --- a/src/function.rs +++ b/src/function.rs @@ -32,6 +32,12 @@ extern "C" { argc: int, argv: *const *const Value, ) -> *const Value; + fn v8__Function__NewInstance( + this: *const Function, + context: *const Context, + argc: int, + argv: *const *const Value, + ) -> *const Object; fn v8__FunctionCallbackInfo__GetReturnValue( info: *const FunctionCallbackInfo, @@ -326,4 +332,19 @@ impl Function { }) } } + + pub fn new_instance<'s>( + &self, + scope: &mut HandleScope<'s>, + args: &[Local], + ) -> Option> { + let args = Local::slice_into_raw(args); + let argc = int::try_from(args.len()).unwrap(); + let argv = args.as_ptr(); + unsafe { + scope.cast_local(|sd| { + v8__Function__NewInstance(self, sd.get_current_context(), argc, argv) + }) + } + } } diff --git a/tests/test_api.rs b/tests/test_api.rs index e0e1c78e..3671ab40 100644 --- a/tests/test_api.rs +++ b/tests/test_api.rs @@ -1671,6 +1671,25 @@ fn function() { } } +#[test] +fn constructor() { + let _setup_guard = setup(); + let isolate = &mut v8::Isolate::new(Default::default()); + + { + let scope = &mut v8::HandleScope::new(isolate); + let context = v8::Context::new(scope); + let scope = &mut v8::ContextScope::new(scope, context); + let global = context.global(scope); + let array_name = v8::String::new(scope, "Array").unwrap(); + let array_constructor = global.get(scope, array_name.into()).unwrap(); + let array_constructor = + v8::Local::::try_from(array_constructor).unwrap(); + let array = array_constructor.new_instance(scope, &[]).unwrap(); + v8::Local::::try_from(array).unwrap(); + } +} + extern "C" fn promise_reject_callback(msg: v8::PromiseRejectMessage) { let scope = &mut unsafe { v8::CallbackScope::new(&msg) }; let event = msg.get_event();