From eb4770016358270bc1c3fba870d6f77ad518de85 Mon Sep 17 00:00:00 2001 From: Kevin Eady <8634912+KevinEady@users.noreply.github.com> Date: Thu, 28 Apr 2022 18:19:47 +0200 Subject: [PATCH] Fix C++ via clang-format --- benchmark/function_args.cc | 157 +- benchmark/property_descriptor.cc | 61 +- napi-inl.deprecated.h | 248 +- napi-inl.h | 2227 +++---- napi.h | 5456 +++++++++-------- test/addon.cc | 14 +- test/addon_build/tpl/addon.cc | 3 +- test/addon_data.cc | 23 +- test/basic_types/boolean.cc | 6 +- test/basic_types/number.cc | 18 +- test/basic_types/value.cc | 2 +- test/bigint.cc | 3 +- test/binding.cc | 12 +- test/buffer.cc | 84 +- test/callbackscope.cc | 2 +- test/date.cc | 3 +- test/error.cc | 11 +- test/external.cc | 68 +- test/function.cc | 94 +- test/handlescope.cc | 6 +- test/memory_management.cc | 17 +- test/object/finalizer.cc | 25 +- test/object/object.cc | 302 +- test/object/object_deprecated.cc | 44 +- test/objectwrap.cc | 75 +- test/objectwrap_constructor_exception.cc | 10 +- test/objectwrap_multiple_inheritance.cc | 14 +- test/reference.cc | 2 +- test/run_script.cc | 2 +- .../threadsafe_function.cc | 42 +- .../threadsafe_function_ctx.cc | 32 +- .../threadsafe_function_existing_tsfn.cc | 62 +- .../threadsafe_function_ptr.cc | 5 +- .../threadsafe_function_sum.cc | 79 +- .../threadsafe_function_unref.cc | 20 +- test/thunking_manual.cc | 135 +- test/typedarray.cc | 217 +- test/version_management.cc | 31 +- 38 files changed, 5001 insertions(+), 4611 deletions(-) diff --git a/benchmark/function_args.cc b/benchmark/function_args.cc index 54bdbe342..f82ebfe16 100644 --- a/benchmark/function_args.cc +++ b/benchmark/function_args.cc @@ -1,8 +1,8 @@ #include "napi.h" static napi_value NoArgFunction_Core(napi_env env, napi_callback_info info) { - (void) env; - (void) info; + (void)env; + (void)info; return nullptr; } @@ -12,7 +12,7 @@ static napi_value OneArgFunction_Core(napi_env env, napi_callback_info info) { if (napi_get_cb_info(env, info, &argc, &argv, nullptr, nullptr) != napi_ok) { return nullptr; } - (void) argv; + (void)argv; return nullptr; } @@ -22,8 +22,8 @@ static napi_value TwoArgFunction_Core(napi_env env, napi_callback_info info) { if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) { return nullptr; } - (void) argv[0]; - (void) argv[1]; + (void)argv[0]; + (void)argv[1]; return nullptr; } @@ -33,9 +33,9 @@ static napi_value ThreeArgFunction_Core(napi_env env, napi_callback_info info) { if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) { return nullptr; } - (void) argv[0]; - (void) argv[1]; - (void) argv[2]; + (void)argv[0]; + (void)argv[1]; + (void)argv[2]; return nullptr; } @@ -45,95 +45,128 @@ static napi_value FourArgFunction_Core(napi_env env, napi_callback_info info) { if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) { return nullptr; } - (void) argv[0]; - (void) argv[1]; - (void) argv[2]; - (void) argv[3]; + (void)argv[0]; + (void)argv[1]; + (void)argv[2]; + (void)argv[3]; return nullptr; } static void NoArgFunction(const Napi::CallbackInfo& info) { - (void) info; + (void)info; } static void OneArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; + Napi::Value argv0 = info[0]; + (void)argv0; } static void TwoArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; } static void ThreeArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; - Napi::Value argv2 = info[2]; (void) argv2; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; + Napi::Value argv2 = info[2]; + (void)argv2; } static void FourArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; - Napi::Value argv2 = info[2]; (void) argv2; - Napi::Value argv3 = info[3]; (void) argv3; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; + Napi::Value argv2 = info[2]; + (void)argv2; + Napi::Value argv3 = info[3]; + (void)argv3; } #if NAPI_VERSION > 5 class FunctionArgsBenchmark : public Napi::Addon { public: FunctionArgsBenchmark(Napi::Env env, Napi::Object exports) { - DefineAddon(exports, { - InstanceValue("addon", DefineProperties(Napi::Object::New(env), { - InstanceMethod("noArgFunction", &FunctionArgsBenchmark::NoArgFunction), - InstanceMethod("oneArgFunction", - &FunctionArgsBenchmark::OneArgFunction), - InstanceMethod("twoArgFunction", - &FunctionArgsBenchmark::TwoArgFunction), - InstanceMethod("threeArgFunction", - &FunctionArgsBenchmark::ThreeArgFunction), - InstanceMethod("fourArgFunction", - &FunctionArgsBenchmark::FourArgFunction), - }), napi_enumerable), - InstanceValue("addon_templated", - DefineProperties(Napi::Object::New(env), { - InstanceMethod<&FunctionArgsBenchmark::NoArgFunction>( - "noArgFunction"), - InstanceMethod<&FunctionArgsBenchmark::OneArgFunction>( - "oneArgFunction"), - InstanceMethod<&FunctionArgsBenchmark::TwoArgFunction>( - "twoArgFunction"), - InstanceMethod<&FunctionArgsBenchmark::ThreeArgFunction>( - "threeArgFunction"), - InstanceMethod<&FunctionArgsBenchmark::FourArgFunction>( - "fourArgFunction"), - }), napi_enumerable), - }); + DefineAddon( + exports, + { + InstanceValue( + "addon", + DefineProperties( + Napi::Object::New(env), + { + InstanceMethod("noArgFunction", + &FunctionArgsBenchmark::NoArgFunction), + InstanceMethod("oneArgFunction", + &FunctionArgsBenchmark::OneArgFunction), + InstanceMethod("twoArgFunction", + &FunctionArgsBenchmark::TwoArgFunction), + InstanceMethod( + "threeArgFunction", + &FunctionArgsBenchmark::ThreeArgFunction), + InstanceMethod("fourArgFunction", + &FunctionArgsBenchmark::FourArgFunction), + }), + napi_enumerable), + InstanceValue( + "addon_templated", + DefineProperties( + Napi::Object::New(env), + { + InstanceMethod<&FunctionArgsBenchmark::NoArgFunction>( + "noArgFunction"), + InstanceMethod<&FunctionArgsBenchmark::OneArgFunction>( + "oneArgFunction"), + InstanceMethod<&FunctionArgsBenchmark::TwoArgFunction>( + "twoArgFunction"), + InstanceMethod< + &FunctionArgsBenchmark::ThreeArgFunction>( + "threeArgFunction"), + InstanceMethod<&FunctionArgsBenchmark::FourArgFunction>( + "fourArgFunction"), + }), + napi_enumerable), + }); } + private: - void NoArgFunction(const Napi::CallbackInfo& info) { - (void) info; - } + void NoArgFunction(const Napi::CallbackInfo& info) { (void)info; } void OneArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; + Napi::Value argv0 = info[0]; + (void)argv0; } void TwoArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; } void ThreeArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; - Napi::Value argv2 = info[2]; (void) argv2; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; + Napi::Value argv2 = info[2]; + (void)argv2; } void FourArgFunction(const Napi::CallbackInfo& info) { - Napi::Value argv0 = info[0]; (void) argv0; - Napi::Value argv1 = info[1]; (void) argv1; - Napi::Value argv2 = info[2]; (void) argv2; - Napi::Value argv3 = info[3]; (void) argv3; + Napi::Value argv0 = info[0]; + (void)argv0; + Napi::Value argv1 = info[1]; + (void)argv1; + Napi::Value argv2 = info[2]; + (void)argv2; + Napi::Value argv3 = info[3]; + (void)argv3; } }; #endif // NAPI_VERSION > 5 diff --git a/benchmark/property_descriptor.cc b/benchmark/property_descriptor.cc index 19803f595..18cafcdfa 100644 --- a/benchmark/property_descriptor.cc +++ b/benchmark/property_descriptor.cc @@ -1,7 +1,7 @@ #include "napi.h" static napi_value Getter_Core(napi_env env, napi_callback_info info) { - (void) info; + (void)info; napi_value result; napi_status status = napi_create_uint32(env, 42, &result); NAPI_THROW_IF_FAILED(env, status, nullptr); @@ -14,7 +14,7 @@ static napi_value Setter_Core(napi_env env, napi_callback_info info) { napi_status status = napi_get_cb_info(env, info, &argc, &argv, nullptr, nullptr); NAPI_THROW_IF_FAILED(env, status, nullptr); - (void) argv; + (void)argv; return nullptr; } @@ -23,22 +23,23 @@ static Napi::Value Getter(const Napi::CallbackInfo& info) { } static void Setter(const Napi::CallbackInfo& info) { - (void) info[0]; + (void)info[0]; } #if NAPI_VERSION > 5 class PropDescBenchmark : public Napi::Addon { public: PropDescBenchmark(Napi::Env, Napi::Object exports) { - DefineAddon(exports, { - InstanceAccessor("addon", - &PropDescBenchmark::Getter, - &PropDescBenchmark::Setter, - napi_enumerable), - InstanceAccessor<&PropDescBenchmark::Getter, - &PropDescBenchmark::Setter>("addon_templated", - napi_enumerable), - }); + DefineAddon(exports, + { + InstanceAccessor("addon", + &PropDescBenchmark::Getter, + &PropDescBenchmark::Setter, + napi_enumerable), + InstanceAccessor<&PropDescBenchmark::Getter, + &PropDescBenchmark::Setter>( + "addon_templated", napi_enumerable), + }); } private: @@ -47,39 +48,31 @@ class PropDescBenchmark : public Napi::Addon { } void Setter(const Napi::CallbackInfo& info, const Napi::Value& val) { - (void) info[0]; - (void) val; + (void)info[0]; + (void)val; } }; #endif // NAPI_VERSION > 5 static Napi::Object Init(Napi::Env env, Napi::Object exports) { napi_status status; - napi_property_descriptor core_prop = { - "core", - nullptr, - nullptr, - Getter_Core, - Setter_Core, - nullptr, - napi_enumerable, - nullptr - }; + napi_property_descriptor core_prop = {"core", + nullptr, + nullptr, + Getter_Core, + Setter_Core, + nullptr, + napi_enumerable, + nullptr}; status = napi_define_properties(env, exports, 1, &core_prop); NAPI_THROW_IF_FAILED(env, status, Napi::Object()); - exports.DefineProperty( - Napi::PropertyDescriptor::Accessor(env, - exports, - "cplusplus", - Getter, - Setter, - napi_enumerable)); + exports.DefineProperty(Napi::PropertyDescriptor::Accessor( + env, exports, "cplusplus", Getter, Setter, napi_enumerable)); - exports.DefineProperty( - Napi::PropertyDescriptor::Accessor("templated", - napi_enumerable)); + exports.DefineProperty(Napi::PropertyDescriptor::Accessor( + "templated", napi_enumerable)); #if NAPI_VERSION > 5 PropDescBenchmark::Init(env, exports); diff --git a/napi-inl.deprecated.h b/napi-inl.deprecated.h index 51e954cea..3ddbb2efa 100644 --- a/napi-inl.deprecated.h +++ b/napi-inl.deprecated.h @@ -6,187 +6,181 @@ //////////////////////////////////////////////////////////////////////////////// template -inline PropertyDescriptor -PropertyDescriptor::Accessor(const char* utf8name, - Getter getter, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { using CbData = details::CallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ getter, nullptr }); - - return PropertyDescriptor({ - utf8name, - nullptr, - nullptr, - CbData::Wrapper, - nullptr, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(const std::string& utf8name, - Getter getter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { return Accessor(utf8name.c_str(), getter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, - Getter getter, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { using CbData = details::CallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ getter, nullptr }); - - return PropertyDescriptor({ - nullptr, - name, - nullptr, - CbData::Wrapper, - nullptr, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Name name, - Getter getter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, Getter getter, napi_property_attributes attributes, void* data) { napi_value nameValue = name; return PropertyDescriptor::Accessor(nameValue, getter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { using CbData = details::AccessorCallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ getter, setter, nullptr }); - - return PropertyDescriptor({ - utf8name, - nullptr, - nullptr, - CbData::GetterWrapper, - CbData::SetterWrapper, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(const std::string& utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { return Accessor(utf8name.c_str(), getter, setter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { using CbData = details::AccessorCallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ getter, setter, nullptr }); - - return PropertyDescriptor({ - nullptr, - name, - nullptr, - CbData::GetterWrapper, - CbData::SetterWrapper, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { napi_value nameValue = name; - return PropertyDescriptor::Accessor(nameValue, getter, setter, attributes, data); + return PropertyDescriptor::Accessor( + nameValue, getter, setter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Function(const char* utf8name, - Callable cb, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); using CbData = details::CallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ cb, nullptr }); - - return PropertyDescriptor({ - utf8name, - nullptr, - CbData::Wrapper, - nullptr, - nullptr, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Function(const std::string& utf8name, - Callable cb, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { return Function(utf8name.c_str(), cb, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Function(napi_value name, - Callable cb, - napi_property_attributes attributes, - void* /*data*/) { +inline PropertyDescriptor PropertyDescriptor::Function( + napi_value name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); using CbData = details::CallbackData; // TODO: Delete when the function is destroyed - auto callbackData = new CbData({ cb, nullptr }); - - return PropertyDescriptor({ - nullptr, - name, - CbData::Wrapper, - nullptr, - nullptr, - nullptr, - attributes, - callbackData - }); + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({nullptr, + name, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Function(Name name, - Callable cb, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Function( + Name name, Callable cb, napi_property_attributes attributes, void* data) { napi_value nameValue = name; return PropertyDescriptor::Function(nameValue, cb, attributes, data); } -#endif // !SRC_NAPI_INL_DEPRECATED_H_ +#endif // !SRC_NAPI_INL_DEPRECATED_H_ diff --git a/napi-inl.h b/napi-inl.h index 14e75aa10..2583f81f8 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -45,22 +45,16 @@ static inline napi_status AttachData(napi_env env, napi_value symbol, external; status = napi_create_symbol(env, nullptr, &symbol); if (status == napi_ok) { - status = napi_create_external(env, - data, - finalizer, - hint, - &external); + status = napi_create_external(env, data, finalizer, hint, &external); if (status == napi_ok) { - napi_property_descriptor desc = { - nullptr, - symbol, - nullptr, - nullptr, - nullptr, - external, - napi_default, - nullptr - }; + napi_property_descriptor desc = {nullptr, + symbol, + nullptr, + nullptr, + nullptr, + external, + napi_default, + nullptr}; status = napi_define_properties(env, obj, 1, &desc); } } @@ -81,16 +75,16 @@ inline napi_value WrapCallback(Callable callback) { e.ThrowAsJavaScriptException(); return nullptr; } -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS // When C++ exceptions are disabled, errors are immediately thrown as JS // exceptions, so there is no need to catch and rethrow them here. return callback(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS } // For use in JS to C++ void callback wrappers to catch any Napi::Error -// exceptions and rethrow them as JavaScript exceptions before returning from the -// callback. +// exceptions and rethrow them as JavaScript exceptions before returning from +// the callback. template inline void WrapVoidCallback(Callable callback) { #ifdef NAPI_CPP_EXCEPTIONS @@ -99,21 +93,20 @@ inline void WrapVoidCallback(Callable callback) { } catch (const Error& e) { e.ThrowAsJavaScriptException(); } -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS // When C++ exceptions are disabled, errors are immediately thrown as JS // exceptions, so there is no need to catch and rethrow them here. callback(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS } template struct CallbackData { - static inline - napi_value Wrapper(napi_env env, napi_callback_info info) { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = - static_cast(callbackInfo.Data()); + static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->callback(callbackInfo); }); @@ -125,12 +118,11 @@ struct CallbackData { template struct CallbackData { - static inline - napi_value Wrapper(napi_env env, napi_callback_info info) { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = - static_cast(callbackInfo.Data()); + static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->callback(callbackInfo); return nullptr; @@ -142,8 +134,8 @@ struct CallbackData { }; template -static napi_value -TemplatedVoidCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { +static napi_value TemplatedVoidCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback([&] { CallbackInfo cbInfo(env, info); Callback(cbInfo); @@ -152,8 +144,8 @@ TemplatedVoidCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { } template -static napi_value -TemplatedCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { +static napi_value TemplatedCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback([&] { CallbackInfo cbInfo(env, info); return Callback(cbInfo); @@ -162,8 +154,8 @@ TemplatedCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { template -static napi_value -TemplatedInstanceCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { +static napi_value TemplatedInstanceCallback( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback([&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); @@ -172,9 +164,8 @@ TemplatedInstanceCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { } template -static napi_value -TemplatedInstanceVoidCallback(napi_env env, - napi_callback_info info) NAPI_NOEXCEPT { +static napi_value TemplatedInstanceVoidCallback( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback([&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); @@ -200,7 +191,8 @@ struct FinalizeData { void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback([&] { FinalizeData* finalizeData = static_cast(finalizeHint); - finalizeData->callback(Env(env), static_cast(data), finalizeData->hint); + finalizeData->callback( + Env(env), static_cast(data), finalizeData->hint); delete finalizeData; }); } @@ -210,14 +202,14 @@ struct FinalizeData { }; #if (NAPI_VERSION > 3 && !defined(__wasm32__)) -template , - typename FinalizerDataType=void> +template , + typename FinalizerDataType = void> struct ThreadSafeFinalize { - static inline - void Wrapper(napi_env env, void* rawFinalizeData, void* /* rawContext */) { - if (rawFinalizeData == nullptr) - return; + static inline void Wrapper(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); @@ -225,12 +217,10 @@ struct ThreadSafeFinalize { delete finalizeData; } - static inline - void FinalizeWrapperWithData(napi_env env, - void* rawFinalizeData, - void* /* rawContext */) { - if (rawFinalizeData == nullptr) - return; + static inline void FinalizeWrapperWithData(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); @@ -238,12 +228,10 @@ struct ThreadSafeFinalize { delete finalizeData; } - static inline - void FinalizeWrapperWithContext(napi_env env, - void* rawFinalizeData, - void* rawContext) { - if (rawFinalizeData == nullptr) - return; + static inline void FinalizeWrapperWithContext(napi_env env, + void* rawFinalizeData, + void* rawContext) { + if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); @@ -251,17 +239,14 @@ struct ThreadSafeFinalize { delete finalizeData; } - static inline - void FinalizeFinalizeWrapperWithDataAndContext(napi_env env, - void* rawFinalizeData, - void* rawContext) { - if (rawFinalizeData == nullptr) - return; + static inline void FinalizeFinalizeWrapperWithDataAndContext( + napi_env env, void* rawFinalizeData, void* rawContext) { + if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); - finalizeData->callback(Env(env), finalizeData->data, - static_cast(rawContext)); + finalizeData->callback( + Env(env), finalizeData->data, static_cast(rawContext)); delete finalizeData; } @@ -311,23 +296,23 @@ napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { template struct AccessorCallbackData { - static inline - napi_value GetterWrapper(napi_env env, napi_callback_info info) { + static inline napi_value GetterWrapper(napi_env env, + napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = - static_cast(callbackInfo.Data()); + static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->getterCallback(callbackInfo); }); } - static inline - napi_value SetterWrapper(napi_env env, napi_callback_info info) { + static inline napi_value SetterWrapper(napi_env env, + napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = - static_cast(callbackInfo.Data()); + static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->setterCallback(callbackInfo); return nullptr; @@ -342,8 +327,8 @@ struct AccessorCallbackData { } // namespace details #ifndef NODE_ADDON_API_DISABLE_DEPRECATED -# include "napi-inl.deprecated.h" -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED +#include "napi-inl.deprecated.h" +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED //////////////////////////////////////////////////////////////////////////////// // Module registration @@ -358,16 +343,15 @@ struct AccessorCallbackData { // Register an add-on based on a subclass of `Addon` with a custom Node.js // module name. -#define NODE_API_NAMED_ADDON(modname, classname) \ - static napi_value __napi_ ## classname(napi_env env, \ - napi_value exports) { \ - return Napi::RegisterModule(env, exports, &classname::Init); \ - } \ - NAPI_MODULE(modname, __napi_ ## classname) +#define NODE_API_NAMED_ADDON(modname, classname) \ + static napi_value __napi_##classname(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, &classname::Init); \ + } \ + NAPI_MODULE(modname, __napi_##classname) // Register an add-on based on a subclass of `Addon` with the Node.js module // name given by node-gyp from the `target_name` in binding.gyp. -#define NODE_API_ADDON(classname) \ +#define NODE_API_ADDON(classname) \ NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname) // Adapt the NAPI_MODULE registration function: @@ -377,8 +361,8 @@ inline napi_value RegisterModule(napi_env env, napi_value exports, ModuleRegisterCallback registerCallback) { return details::WrapCallback([&] { - return napi_value(registerCallback(Napi::Env(env), - Napi::Object(env, exports))); + return napi_value( + registerCallback(Napi::Env(env), Napi::Object(env, exports))); }); } @@ -452,8 +436,7 @@ inline Maybe Just(const T& t) { // Env class //////////////////////////////////////////////////////////////////////////////// -inline Env::Env(napi_env env) : _env(env) { -} +inline Env::Env(napi_env env) : _env(env) {} inline Env::operator napi_env() const { return _env; @@ -483,7 +466,8 @@ inline Value Env::Null() const { inline bool Env::IsExceptionPending() const { bool result; napi_status status = napi_is_exception_pending(_env, &result); - if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. + if (status != napi_ok) + result = false; // Checking for a pending exception shouldn't throw. return result; } @@ -536,10 +520,11 @@ void Env::CleanupHook::WrapperWithArg(void* data) NAPI_NOEXCEPT { #if NAPI_VERSION > 5 template fini> inline void Env::SetInstanceData(T* data) const { - napi_status status = - napi_set_instance_data(_env, data, [](napi_env env, void* data, void*) { - fini(env, static_cast(data)); - }, nullptr); + napi_status status = napi_set_instance_data( + _env, + data, + [](napi_env env, void* data, void*) { fini(env, static_cast(data)); }, + nullptr); NAPI_THROW_IF_FAILED_VOID(_env, status); } @@ -547,11 +532,13 @@ template fini> inline void Env::SetInstanceData(DataType* data, HintType* hint) const { - napi_status status = - napi_set_instance_data(_env, data, + napi_status status = napi_set_instance_data( + _env, + data, [](napi_env env, void* data, void* hint) { fini(env, static_cast(data), static_cast(hint)); - }, hint); + }, + hint); NAPI_THROW_IF_FAILED_VOID(_env, status); } @@ -565,7 +552,8 @@ inline T* Env::GetInstanceData() const { return static_cast(data); } -template void Env::DefaultFini(Env, T* data) { +template +void Env::DefaultFini(Env, T* data) { delete data; } @@ -579,22 +567,21 @@ void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) { // Value class //////////////////////////////////////////////////////////////////////////////// -inline Value::Value() : _env(nullptr), _value(nullptr) { -} +inline Value::Value() : _env(nullptr), _value(nullptr) {} -inline Value::Value(napi_env env, napi_value value) : _env(env), _value(value) { -} +inline Value::Value(napi_env env, napi_value value) + : _env(env), _value(value) {} inline Value::operator napi_value() const { return _value; } -inline bool Value::operator ==(const Value& other) const { +inline bool Value::operator==(const Value& other) const { return StrictEquals(other); } -inline bool Value::operator !=(const Value& other) const { - return !this->operator ==(other); +inline bool Value::operator!=(const Value& other) const { + return !this->operator==(other); } inline bool Value::StrictEquals(const Value& other) const { @@ -788,11 +775,10 @@ inline Boolean Boolean::New(napi_env env, bool val) { return Boolean(env, value); } -inline Boolean::Boolean() : Napi::Value() { -} +inline Boolean::Boolean() : Napi::Value() {} -inline Boolean::Boolean(napi_env env, napi_value value) : Napi::Value(env, value) { -} +inline Boolean::Boolean(napi_env env, napi_value value) + : Napi::Value(env, value) {} inline Boolean::operator bool() const { return Value(); @@ -816,11 +802,9 @@ inline Number Number::New(napi_env env, double val) { return Number(env, value); } -inline Number::Number() : Value() { -} +inline Number::Number() : Value() {} -inline Number::Number(napi_env env, napi_value value) : Value(env, value) { -} +inline Number::Number(napi_env env, napi_value value) : Value(env, value) {} inline Number::operator int32_t() const { return Int32Value(); @@ -893,46 +877,50 @@ inline BigInt BigInt::New(napi_env env, uint64_t val) { return BigInt(env, value); } -inline BigInt BigInt::New(napi_env env, int sign_bit, size_t word_count, const uint64_t* words) { +inline BigInt BigInt::New(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words) { napi_value value; - napi_status status = napi_create_bigint_words(env, sign_bit, word_count, words, &value); + napi_status status = + napi_create_bigint_words(env, sign_bit, word_count, words, &value); NAPI_THROW_IF_FAILED(env, status, BigInt()); return BigInt(env, value); } -inline BigInt::BigInt() : Value() { -} +inline BigInt::BigInt() : Value() {} -inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) { -} +inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {} inline int64_t BigInt::Int64Value(bool* lossless) const { int64_t result; - napi_status status = napi_get_value_bigint_int64( - _env, _value, &result, lossless); + napi_status status = + napi_get_value_bigint_int64(_env, _value, &result, lossless); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline uint64_t BigInt::Uint64Value(bool* lossless) const { uint64_t result; - napi_status status = napi_get_value_bigint_uint64( - _env, _value, &result, lossless); + napi_status status = + napi_get_value_bigint_uint64(_env, _value, &result, lossless); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline size_t BigInt::WordCount() const { size_t word_count; - napi_status status = napi_get_value_bigint_words( - _env, _value, nullptr, &word_count, nullptr); + napi_status status = + napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr); NAPI_THROW_IF_FAILED(_env, status, 0); return word_count; } -inline void BigInt::ToWords(int* sign_bit, size_t* word_count, uint64_t* words) { - napi_status status = napi_get_value_bigint_words( - _env, _value, sign_bit, word_count, words); +inline void BigInt::ToWords(int* sign_bit, + size_t* word_count, + uint64_t* words) { + napi_status status = + napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words); NAPI_THROW_IF_FAILED_VOID(_env, status); } #endif // NAPI_VERSION > 5 @@ -949,11 +937,9 @@ inline Date Date::New(napi_env env, double val) { return Date(env, value); } -inline Date::Date() : Value() { -} +inline Date::Date() : Value() {} -inline Date::Date(napi_env env, napi_value value) : Value(env, value) { -} +inline Date::Date(napi_env env, napi_value value) : Value(env, value) {} inline Date::operator double() const { return ValueOf(); @@ -961,8 +947,7 @@ inline Date::operator double() const { inline double Date::ValueOf() const { double result; - napi_status status = napi_get_date_value( - _env, _value, &result); + napi_status status = napi_get_date_value(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } @@ -972,11 +957,9 @@ inline double Date::ValueOf() const { // Name class //////////////////////////////////////////////////////////////////////////////// -inline Name::Name() : Value() { -} +inline Name::Name() : Value() {} -inline Name::Name(napi_env env, napi_value value) : Value(env, value) { -} +inline Name::Name(napi_env env, napi_value value) : Value(env, value) {} //////////////////////////////////////////////////////////////////////////////// // String class @@ -998,7 +981,8 @@ inline String String::New(napi_env env, const char* val) { NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); } napi_value value; - napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); + napi_status status = + napi_create_string_utf8(env, val, std::strlen(val), &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } @@ -1011,7 +995,8 @@ inline String String::New(napi_env env, const char16_t* val) { // Throw an error that looks like it came from core. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); } - napi_status status = napi_create_string_utf16(env, val, std::u16string(val).size(), &value); + napi_status status = + napi_create_string_utf16(env, val, std::u16string(val).size(), &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } @@ -1030,11 +1015,9 @@ inline String String::New(napi_env env, const char16_t* val, size_t length) { return String(env, value); } -inline String::String() : Name() { -} +inline String::String() : Name() {} -inline String::String(napi_env env, napi_value value) : Name(env, value) { -} +inline String::String(napi_env env, napi_value value) : Name(env, value) {} inline String::operator std::string() const { return Utf8Value(); @@ -1046,26 +1029,30 @@ inline String::operator std::u16string() const { inline std::string String::Utf8Value() const { size_t length; - napi_status status = napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); + napi_status status = + napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); NAPI_THROW_IF_FAILED(_env, status, ""); std::string value; value.reserve(length + 1); value.resize(length); - status = napi_get_value_string_utf8(_env, _value, &value[0], value.capacity(), nullptr); + status = napi_get_value_string_utf8( + _env, _value, &value[0], value.capacity(), nullptr); NAPI_THROW_IF_FAILED(_env, status, ""); return value; } inline std::u16string String::Utf16Value() const { size_t length; - napi_status status = napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); + napi_status status = + napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); std::u16string value; value.reserve(length + 1); value.resize(length); - status = napi_get_value_string_utf16(_env, _value, &value[0], value.capacity(), nullptr); + status = napi_get_value_string_utf16( + _env, _value, &value[0], value.capacity(), nullptr); NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); return value; } @@ -1075,8 +1062,9 @@ inline std::u16string String::Utf16Value() const { //////////////////////////////////////////////////////////////////////////////// inline Symbol Symbol::New(napi_env env, const char* description) { - napi_value descriptionValue = description != nullptr ? - String::New(env, description) : static_cast(nullptr); + napi_value descriptionValue = description != nullptr + ? String::New(env, description) + : static_cast(nullptr); return Symbol::New(env, descriptionValue); } @@ -1108,7 +1096,12 @@ inline MaybeOrValue Symbol::WellKnown(napi_env env, } return Nothing(); #else - return Napi::Env(env).Global().Get("Symbol").As().Get(name).As(); + return Napi::Env(env) + .Global() + .Get("Symbol") + .As() + .Get(name) + .As(); #endif } @@ -1149,11 +1142,9 @@ inline MaybeOrValue Symbol::For(napi_env env, napi_value description) { #endif } -inline Symbol::Symbol() : Name() { -} +inline Symbol::Symbol() : Name() {} -inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) { -} +inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {} //////////////////////////////////////////////////////////////////////////////// // Automagic value creation @@ -1167,7 +1158,7 @@ struct vf_number { } }; -template<> +template <> struct vf_number { static Boolean From(napi_env env, bool value) { return Boolean::New(env, value); @@ -1199,36 +1190,33 @@ struct vf_utf16_string { template struct vf_fallback { - static Value From(napi_env env, const T& value) { - return Value(env, value); - } + static Value From(napi_env env, const T& value) { return Value(env, value); } }; -template struct disjunction : std::false_type {}; -template struct disjunction : B {}; +template +struct disjunction : std::false_type {}; +template +struct disjunction : B {}; template struct disjunction : std::conditional>::type {}; template struct can_make_string - : disjunction::type, - typename std::is_convertible::type, + : disjunction::type, + typename std::is_convertible::type, typename std::is_convertible::type, typename std::is_convertible::type> {}; -} +} // namespace details template Value Value::From(napi_env env, const T& value) { using Helper = typename std::conditional< - std::is_integral::value || std::is_floating_point::value, - details::vf_number, - typename std::conditional< - details::can_make_string::value, - String, - details::vf_fallback - >::type - >::type; + std::is_integral::value || std::is_floating_point::value, + details::vf_number, + typename std::conditional::value, + String, + details::vf_fallback>::type>::type; return Helper::From(env, value); } @@ -1236,22 +1224,18 @@ template String String::From(napi_env env, const T& value) { struct Dummy {}; using Helper = typename std::conditional< - std::is_convertible::value, - details::vf_utf8_charp, - typename std::conditional< - std::is_convertible::value, - details::vf_utf16_charp, + std::is_convertible::value, + details::vf_utf8_charp, typename std::conditional< - std::is_convertible::value, - details::vf_utf8_string, - typename std::conditional< - std::is_convertible::value, - details::vf_utf16_string, - Dummy - >::type - >::type - >::type - >::type; + std::is_convertible::value, + details::vf_utf16_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf8_string, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_string, + Dummy>::type>::type>::type>::type; return Helper::From(env, value); } @@ -1269,8 +1253,10 @@ inline Object::PropertyLValue::operator Value() const { #endif } -template template -inline Object::PropertyLValue& Object::PropertyLValue::operator =(ValueType value) { +template +template +inline Object::PropertyLValue& Object::PropertyLValue::operator=( + ValueType value) { #ifdef NODE_ADDON_API_ENABLE_MAYBE MaybeOrValue result = #endif @@ -1283,7 +1269,7 @@ inline Object::PropertyLValue& Object::PropertyLValue::operator =(Valu template inline Object::PropertyLValue::PropertyLValue(Object object, Key key) - : _env(object.Env()), _object(object), _key(key) {} + : _env(object.Env()), _object(object), _key(key) {} inline Object Object::New(napi_env env) { napi_value value; @@ -1292,11 +1278,9 @@ inline Object Object::New(napi_env env) { return Object(env, value); } -inline Object::Object() : Value() { -} +inline Object::Object() : Value() {} -inline Object::Object(napi_env env, napi_value value) : Value(env, value) { -} +inline Object::Object(napi_env env, napi_value value) : Value(env, value) {} inline Object::PropertyLValue Object::operator[]( const char* utf8name) { @@ -1365,7 +1349,8 @@ inline MaybeOrValue Object::HasOwnProperty(Value key) const { inline MaybeOrValue Object::HasOwnProperty(const char* utf8name) const { napi_value key; - napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); + napi_status status = + napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool); return HasOwnProperty(key); } @@ -1480,22 +1465,31 @@ inline MaybeOrValue Object::GetPropertyNames() const { inline MaybeOrValue Object::DefineProperty( const PropertyDescriptor& property) const { - napi_status status = napi_define_properties(_env, _value, 1, - reinterpret_cast(&property)); + napi_status status = napi_define_properties( + _env, + _value, + 1, + reinterpret_cast(&property)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::DefineProperties( const std::initializer_list& properties) const { - napi_status status = napi_define_properties(_env, _value, properties.size(), - reinterpret_cast(properties.begin())); + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.begin())); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::DefineProperties( const std::vector& properties) const { - napi_status status = napi_define_properties(_env, _value, properties.size(), - reinterpret_cast(properties.data())); + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.data())); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } @@ -1530,12 +1524,12 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback, details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); - napi_status status = - details::AttachData(_env, - *this, - data, - details::FinalizeData::WrapperWithHint, - finalizeData); + napi_status status = details::AttachData( + _env, + *this, + data, + details::FinalizeData::WrapperWithHint, + finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED_VOID(_env, status); @@ -1638,7 +1632,8 @@ inline MaybeOrValue Object::Seal() const { template inline External External::New(napi_env env, T* data) { napi_value value; - napi_status status = napi_create_external(env, data, nullptr, nullptr, &value); + napi_status status = + napi_create_external(env, data, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, External()); return External(env, value); } @@ -1652,12 +1647,12 @@ inline External External::New(napi_env env, details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); - napi_status status = napi_create_external( - env, - data, - details::FinalizeData::Wrapper, - finalizeData, - &value); + napi_status status = + napi_create_external(env, + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, External()); @@ -1676,11 +1671,11 @@ inline External External::New(napi_env env, new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external( - env, - data, - details::FinalizeData::WrapperWithHint, - finalizeData, - &value); + env, + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, External()); @@ -1689,12 +1684,11 @@ inline External External::New(napi_env env, } template -inline External::External() : Value() { -} +inline External::External() : Value() {} template -inline External::External(napi_env env, napi_value value) : Value(env, value) { -} +inline External::External(napi_env env, napi_value value) + : Value(env, value) {} template inline T* External::Data() const { @@ -1722,11 +1716,9 @@ inline Array Array::New(napi_env env, size_t length) { return Array(env, value); } -inline Array::Array() : Object() { -} +inline Array::Array() : Object() {} -inline Array::Array(napi_env env, napi_value value) : Object(env, value) { -} +inline Array::Array(napi_env env, napi_value value) : Object(env, value) {} inline uint32_t Array::Length() const { uint32_t result; @@ -1753,7 +1745,7 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { napi_value value; napi_status status = napi_create_external_arraybuffer( - env, externalData, byteLength, nullptr, nullptr, &value); + env, externalData, byteLength, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); return ArrayBuffer(env, value); @@ -1769,12 +1761,12 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = napi_create_external_arraybuffer( - env, - externalData, - byteLength, - details::FinalizeData::Wrapper, - finalizeData, - &value); + env, + externalData, + byteLength, + details::FinalizeData::Wrapper, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); @@ -1794,12 +1786,12 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external_arraybuffer( - env, - externalData, - byteLength, - details::FinalizeData::WrapperWithHint, - finalizeData, - &value); + env, + externalData, + byteLength, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); @@ -1808,12 +1800,10 @@ inline ArrayBuffer ArrayBuffer::New(napi_env env, return ArrayBuffer(env, value); } -inline ArrayBuffer::ArrayBuffer() : Object() { -} +inline ArrayBuffer::ArrayBuffer() : Object() {} inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) - : Object(env, value) { -} + : Object(env, value) {} inline void* ArrayBuffer::Data() { void* data; @@ -1824,7 +1814,8 @@ inline void* ArrayBuffer::Data() { inline size_t ArrayBuffer::ByteLength() { size_t length; - napi_status status = napi_get_arraybuffer_info(_env, _value, nullptr, &length); + napi_status status = + napi_get_arraybuffer_info(_env, _value, nullptr, &length); NAPI_THROW_IF_FAILED(_env, status, 0); return length; } @@ -1846,8 +1837,7 @@ inline void ArrayBuffer::Detach() { //////////////////////////////////////////////////////////////////////////////// // DataView class //////////////////////////////////////////////////////////////////////////////// -inline DataView DataView::New(napi_env env, - Napi::ArrayBuffer arrayBuffer) { +inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) { return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); } @@ -1855,12 +1845,12 @@ inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset) { if (byteOffset > arrayBuffer.ByteLength()) { - NAPI_THROW(RangeError::New(env, - "Start offset is outside the bounds of the buffer"), - DataView()); + NAPI_THROW(RangeError::New( + env, "Start offset is outside the bounds of the buffer"), + DataView()); } - return New(env, arrayBuffer, byteOffset, - arrayBuffer.ByteLength() - byteOffset); + return New( + env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); } inline DataView DataView::New(napi_env env, @@ -1868,52 +1858,47 @@ inline DataView DataView::New(napi_env env, size_t byteOffset, size_t byteLength) { if (byteOffset + byteLength > arrayBuffer.ByteLength()) { - NAPI_THROW(RangeError::New(env, "Invalid DataView length"), - DataView()); + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); } napi_value value; - napi_status status = napi_create_dataview( - env, byteLength, arrayBuffer, byteOffset, &value); + napi_status status = + napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); NAPI_THROW_IF_FAILED(env, status, DataView()); return DataView(env, value); } -inline DataView::DataView() : Object() { -} +inline DataView::DataView() : Object() {} inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { - napi_status status = napi_get_dataview_info( - _env, - _value /* dataView */, - &_length /* byteLength */, - &_data /* data */, - nullptr /* arrayBuffer */, - nullptr /* byteOffset */); + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + &_length /* byteLength */, + &_data /* data */, + nullptr /* arrayBuffer */, + nullptr /* byteOffset */); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline Napi::ArrayBuffer DataView::ArrayBuffer() const { napi_value arrayBuffer; - napi_status status = napi_get_dataview_info( - _env, - _value /* dataView */, - nullptr /* byteLength */, - nullptr /* data */, - &arrayBuffer /* arrayBuffer */, - nullptr /* byteOffset */); + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + &arrayBuffer /* arrayBuffer */, + nullptr /* byteOffset */); NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); return Napi::ArrayBuffer(_env, arrayBuffer); } inline size_t DataView::ByteOffset() const { size_t byteOffset; - napi_status status = napi_get_dataview_info( - _env, - _value /* dataView */, - nullptr /* byteLength */, - nullptr /* data */, - nullptr /* arrayBuffer */, - &byteOffset /* byteOffset */); + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + nullptr /* arrayBuffer */, + &byteOffset /* byteOffset */); NAPI_THROW_IF_FAILED(_env, status, 0); return byteOffset; } @@ -1994,8 +1979,9 @@ template inline T DataView::ReadData(size_t byteOffset) const { if (byteOffset + sizeof(T) > _length || byteOffset + sizeof(T) < byteOffset) { // overflow - NAPI_THROW(RangeError::New(_env, - "Offset is outside the bounds of the DataView"), 0); + NAPI_THROW( + RangeError::New(_env, "Offset is outside the bounds of the DataView"), + 0); } return *reinterpret_cast(static_cast(_data) + byteOffset); @@ -2005,8 +1991,8 @@ template inline void DataView::WriteData(size_t byteOffset, T value) const { if (byteOffset + sizeof(T) > _length || byteOffset + sizeof(T) < byteOffset) { // overflow - NAPI_THROW_VOID(RangeError::New(_env, - "Offset is outside the bounds of the DataView")); + NAPI_THROW_VOID( + RangeError::New(_env, "Offset is outside the bounds of the DataView")); } *reinterpret_cast(static_cast(_data) + byteOffset) = value; @@ -2017,25 +2003,27 @@ inline void DataView::WriteData(size_t byteOffset, T value) const { //////////////////////////////////////////////////////////////////////////////// inline TypedArray::TypedArray() - : Object(), _type(TypedArray::unknown_array_type), _length(0) { -} + : Object(), _type(TypedArray::unknown_array_type), _length(0) {} inline TypedArray::TypedArray(napi_env env, napi_value value) - : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) { -} + : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) {} inline TypedArray::TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length) - : Object(env, value), _type(type), _length(length) { -} + : Object(env, value), _type(type), _length(length) {} inline napi_typedarray_type TypedArray::TypedArrayType() const { if (_type == TypedArray::unknown_array_type) { - napi_status status = napi_get_typedarray_info(_env, _value, - &const_cast(this)->_type, &const_cast(this)->_length, - nullptr, nullptr, nullptr); + napi_status status = + napi_get_typedarray_info(_env, + _value, + &const_cast(this)->_type, + &const_cast(this)->_length, + nullptr, + nullptr, + nullptr); NAPI_THROW_IF_FAILED(_env, status, napi_int8_array); } @@ -2068,9 +2056,14 @@ inline uint8_t TypedArray::ElementSize() const { inline size_t TypedArray::ElementLength() const { if (_type == TypedArray::unknown_array_type) { - napi_status status = napi_get_typedarray_info(_env, _value, - &const_cast(this)->_type, &const_cast(this)->_length, - nullptr, nullptr, nullptr); + napi_status status = + napi_get_typedarray_info(_env, + _value, + &const_cast(this)->_type, + &const_cast(this)->_length, + nullptr, + nullptr, + nullptr); NAPI_THROW_IF_FAILED(_env, status, 0); } @@ -2080,7 +2073,7 @@ inline size_t TypedArray::ElementLength() const { inline size_t TypedArray::ByteOffset() const { size_t byteOffset; napi_status status = napi_get_typedarray_info( - _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); + _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); NAPI_THROW_IF_FAILED(_env, status, 0); return byteOffset; } @@ -2092,7 +2085,7 @@ inline size_t TypedArray::ByteLength() const { inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { napi_value arrayBuffer; napi_status status = napi_get_typedarray_info( - _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); return Napi::ArrayBuffer(_env, arrayBuffer); } @@ -2105,7 +2098,8 @@ template inline TypedArrayOf TypedArrayOf::New(napi_env env, size_t elementLength, napi_typedarray_type type) { - Napi::ArrayBuffer arrayBuffer = Napi::ArrayBuffer::New(env, elementLength * sizeof (T)); + Napi::ArrayBuffer arrayBuffer = + Napi::ArrayBuffer::New(env, elementLength * sizeof(T)); return New(env, elementLength, arrayBuffer, 0, type); } @@ -2117,21 +2111,24 @@ inline TypedArrayOf TypedArrayOf::New(napi_env env, napi_typedarray_type type) { napi_value value; napi_status status = napi_create_typedarray( - env, type, elementLength, arrayBuffer, bufferOffset, &value); + env, type, elementLength, arrayBuffer, bufferOffset, &value); NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); return TypedArrayOf( - env, value, type, elementLength, - reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + bufferOffset)); + env, + value, + type, + elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + + bufferOffset)); } template -inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) { -} +inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) {} template inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) - : TypedArray(env, value), _data(nullptr) { + : TypedArray(env, value), _data(nullptr) { napi_status status = napi_ok; if (value != nullptr) { void* data = nullptr; @@ -2151,21 +2148,24 @@ inline TypedArrayOf::TypedArrayOf(napi_env env, napi_typedarray_type type, size_t length, T* data) - : TypedArray(env, value, type, length), _data(data) { + : TypedArray(env, value, type, length), _data(data) { if (!(type == TypedArrayTypeForPrimitiveType() || - (type == napi_uint8_clamped_array && std::is_same::value))) { - NAPI_THROW_VOID(TypeError::New(env, "Array type must match the template parameter. " - "(Uint8 arrays may optionally have the \"clamped\" array type.)")); + (type == napi_uint8_clamped_array && + std::is_same::value))) { + NAPI_THROW_VOID(TypeError::New( + env, + "Array type must match the template parameter. " + "(Uint8 arrays may optionally have the \"clamped\" array type.)")); } } template -inline T& TypedArrayOf::operator [](size_t index) { +inline T& TypedArrayOf::operator[](size_t index) { return _data[index]; } template -inline const T& TypedArrayOf::operator [](size_t index) const { +inline const T& TypedArrayOf::operator[](size_t index) const { return _data[index]; } @@ -2184,12 +2184,11 @@ inline const T* TypedArrayOf::Data() const { //////////////////////////////////////////////////////////////////////////////// template -static inline napi_status -CreateFunction(napi_env env, - const char* utf8name, - napi_callback cb, - CbData* data, - napi_value* result) { +static inline napi_status CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { napi_status status = napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); if (status == napi_ok) { @@ -2249,11 +2248,8 @@ inline Function Function::New(napi_env env, auto callbackData = new CbData{std::move(cb), data}; napi_value value; - napi_status status = CreateFunction(env, - utf8name, - CbData::Wrapper, - callbackData, - &value); + napi_status status = + CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, Function()); @@ -2270,11 +2266,10 @@ inline Function Function::New(napi_env env, return New(env, cb, utf8name.c_str(), data); } -inline Function::Function() : Object() { -} +inline Function::Function() : Object() {} -inline Function::Function(napi_env env, napi_value value) : Object(env, value) { -} +inline Function::Function(napi_env env, napi_value value) + : Object(env, value) {} inline MaybeOrValue Function::operator()( const std::initializer_list& args) const { @@ -2336,8 +2331,8 @@ inline MaybeOrValue Function::Call(napi_value recv, size_t argc, const napi_value* args) const { napi_value result; - napi_status status = napi_call_function( - _env, recv, _value, argc, args, &result); + napi_status status = + napi_call_function(_env, recv, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Value(_env, result), Napi::Value); } @@ -2362,8 +2357,8 @@ inline MaybeOrValue Function::MakeCallback( const napi_value* args, napi_async_context context) const { napi_value result; - napi_status status = napi_make_callback( - _env, context, recv, _value, argc, args, &result); + napi_status status = + napi_make_callback(_env, context, recv, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Value(_env, result), Napi::Value); } @@ -2381,8 +2376,7 @@ inline MaybeOrValue Function::New( inline MaybeOrValue Function::New(size_t argc, const napi_value* args) const { napi_value result; - napi_status status = napi_new_instance( - _env, _value, argc, args, &result); + napi_status status = napi_new_instance(_env, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Object(_env, result), Napi::Object); } @@ -2418,8 +2412,7 @@ inline void Promise::Deferred::Reject(napi_value value) const { NAPI_THROW_IF_FAILED_VOID(_env, status); } -inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) { -} +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} //////////////////////////////////////////////////////////////////////////////// // Buffer class @@ -2429,7 +2422,8 @@ template inline Buffer Buffer::New(napi_env env, size_t length) { napi_value value; void* data; - napi_status status = napi_create_buffer(env, length * sizeof (T), &data, &value); + napi_status status = + napi_create_buffer(env, length * sizeof(T), &data, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value, length, static_cast(data)); } @@ -2438,7 +2432,7 @@ template inline Buffer Buffer::New(napi_env env, T* data, size_t length) { napi_value value; napi_status status = napi_create_external_buffer( - env, length * sizeof (T), data, nullptr, nullptr, &value); + env, length * sizeof(T), data, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value, length, data); } @@ -2453,13 +2447,13 @@ inline Buffer Buffer::New(napi_env env, details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); - napi_status status = napi_create_external_buffer( - env, - length * sizeof (T), - data, - details::FinalizeData::Wrapper, - finalizeData, - &value); + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); @@ -2479,12 +2473,12 @@ inline Buffer Buffer::New(napi_env env, new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external_buffer( - env, - length * sizeof (T), - data, - details::FinalizeData::WrapperWithHint, - finalizeData, - &value); + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); @@ -2495,25 +2489,22 @@ inline Buffer Buffer::New(napi_env env, template inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { napi_value value; - napi_status status = napi_create_buffer_copy( - env, length * sizeof (T), data, nullptr, &value); + napi_status status = + napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value); } template -inline Buffer::Buffer() : Uint8Array(), _length(0), _data(nullptr) { -} +inline Buffer::Buffer() : Uint8Array(), _length(0), _data(nullptr) {} template inline Buffer::Buffer(napi_env env, napi_value value) - : Uint8Array(env, value), _length(0), _data(nullptr) { -} + : Uint8Array(env, value), _length(0), _data(nullptr) {} template inline Buffer::Buffer(napi_env env, napi_value value, size_t length, T* data) - : Uint8Array(env, value), _length(length), _data(data) { -} + : Uint8Array(env, value), _length(length), _data(data) {} template inline size_t Buffer::Length() const { @@ -2535,9 +2526,10 @@ inline void Buffer::EnsureInfo() const { if (_data == nullptr) { size_t byteLength; void* voidData; - napi_status status = napi_get_buffer_info(_env, _value, &voidData, &byteLength); + napi_status status = + napi_get_buffer_info(_env, _value, &voidData, &byteLength); NAPI_THROW_IF_FAILED_VOID(_env, status); - _length = byteLength / sizeof (T); + _length = byteLength / sizeof(T); _data = static_cast(voidData); } } @@ -2574,19 +2566,16 @@ inline Error Error::New(napi_env env) { // A pending exception takes precedence over any internal error status. if (is_exception_pending) { status = napi_get_and_clear_last_exception(env, &error); - NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception"); - } - else { + NAPI_FATAL_IF_FAILED( + status, "Error::New", "napi_get_and_clear_last_exception"); + } else { const char* error_message = last_error_info_copy.error_message != nullptr ? last_error_info_copy.error_message : "Error in native callback"; napi_value message; status = napi_create_string_utf8( - env, - error_message, - std::strlen(error_message), - &message); + env, error_message, std::strlen(error_message), &message); NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); switch (last_error_info_copy.error_code) { @@ -2607,21 +2596,24 @@ inline Error Error::New(napi_env env) { } inline Error Error::New(napi_env env, const char* message) { - return Error::New(env, message, std::strlen(message), napi_create_error); + return Error::New( + env, message, std::strlen(message), napi_create_error); } inline Error Error::New(napi_env env, const std::string& message) { - return Error::New(env, message.c_str(), message.size(), napi_create_error); + return Error::New( + env, message.c_str(), message.size(), napi_create_error); } -inline NAPI_NO_RETURN void Error::Fatal(const char* location, const char* message) { +inline NAPI_NO_RETURN void Error::Fatal(const char* location, + const char* message) { napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); } -inline Error::Error() : ObjectReference() { -} +inline Error::Error() : ObjectReference() {} -inline Error::Error(napi_env env, napi_value value) : ObjectReference(env, nullptr) { +inline Error::Error(napi_env env, napi_value value) + : ObjectReference(env, nullptr) { if (value != nullptr) { // Attempting to create a reference on the error object. // If it's not a Object/Function/Symbol, this call will return an error @@ -2699,18 +2691,16 @@ inline Object Error::Value() const { return Object(_env, refValue); } -inline Error::Error(Error&& other) : ObjectReference(std::move(other)) { -} +inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {} -inline Error& Error::operator =(Error&& other) { +inline Error& Error::operator=(Error&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } -inline Error::Error(const Error& other) : ObjectReference(other) { -} +inline Error::Error(const Error& other) : ObjectReference(other) {} -inline Error& Error::operator =(const Error& other) { +inline Error& Error::operator=(const Error& other) { Reset(); _env = other.Env(); @@ -2730,12 +2720,11 @@ inline const std::string& Error::Message() const NAPI_NOEXCEPT { #ifdef NAPI_CPP_EXCEPTIONS try { _message = Get("message").As(); - } - catch (...) { + } catch (...) { // Catch all errors here, to include e.g. a std::bad_alloc from // the std::string::operator=, because this method may not throw. } -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS #if defined(NODE_ADDON_API_ENABLE_MAYBE) Napi::Value message_val; if (Get("message").UnwrapTo(&message_val)) { @@ -2744,7 +2733,7 @@ inline const std::string& Error::Message() const NAPI_NOEXCEPT { #else _message = Get("message").As(); #endif -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS } return _message; } @@ -2790,9 +2779,10 @@ inline void Error::ThrowAsJavaScriptException() const { if (status != napi_ok) { throw Error::New(_env); } -#else // NAPI_CPP_EXCEPTIONS - NAPI_FATAL_IF_FAILED(status, "Error::ThrowAsJavaScriptException", "napi_throw"); -#endif // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS + NAPI_FATAL_IF_FAILED( + status, "Error::ThrowAsJavaScriptException", "napi_throw"); +#endif // NAPI_CPP_EXCEPTIONS } } @@ -2802,7 +2792,7 @@ inline const char* Error::what() const NAPI_NOEXCEPT { return Message().c_str(); } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT { return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal"; @@ -2825,39 +2815,42 @@ inline TError Error::New(napi_env env, } inline TypeError TypeError::New(napi_env env, const char* message) { - return Error::New(env, message, std::strlen(message), napi_create_type_error); + return Error::New( + env, message, std::strlen(message), napi_create_type_error); } inline TypeError TypeError::New(napi_env env, const std::string& message) { - return Error::New(env, message.c_str(), message.size(), napi_create_type_error); + return Error::New( + env, message.c_str(), message.size(), napi_create_type_error); } -inline TypeError::TypeError() : Error() { -} +inline TypeError::TypeError() : Error() {} -inline TypeError::TypeError(napi_env env, napi_value value) : Error(env, value) { -} +inline TypeError::TypeError(napi_env env, napi_value value) + : Error(env, value) {} inline RangeError RangeError::New(napi_env env, const char* message) { - return Error::New(env, message, std::strlen(message), napi_create_range_error); + return Error::New( + env, message, std::strlen(message), napi_create_range_error); } inline RangeError RangeError::New(napi_env env, const std::string& message) { - return Error::New(env, message.c_str(), message.size(), napi_create_range_error); + return Error::New( + env, message.c_str(), message.size(), napi_create_range_error); } -inline RangeError::RangeError() : Error() { -} +inline RangeError::RangeError() : Error() {} -inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) { -} +inline RangeError::RangeError(napi_env env, napi_value value) + : Error(env, value) {} //////////////////////////////////////////////////////////////////////////////// // Reference class //////////////////////////////////////////////////////////////////////////////// template -inline Reference Reference::New(const T& value, uint32_t initialRefcount) { +inline Reference Reference::New(const T& value, + uint32_t initialRefcount) { napi_env env = value.Env(); napi_value val = value; @@ -2872,15 +2865,13 @@ inline Reference Reference::New(const T& value, uint32_t initialRefcount) return Reference(env, ref); } - template -inline Reference::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) { -} +inline Reference::Reference() + : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {} template inline Reference::Reference(napi_env env, napi_ref ref) - : _env(env), _ref(ref), _suppressDestruct(false) { -} + : _env(env), _ref(ref), _suppressDestruct(false) {} template inline Reference::~Reference() { @@ -2895,14 +2886,16 @@ inline Reference::~Reference() { template inline Reference::Reference(Reference&& other) - : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) { + : _env(other._env), + _ref(other._ref), + _suppressDestruct(other._suppressDestruct) { other._env = nullptr; other._ref = nullptr; other._suppressDestruct = false; } template -inline Reference& Reference::operator =(Reference&& other) { +inline Reference& Reference::operator=(Reference&& other) { Reset(); _env = other._env; _ref = other._ref; @@ -2915,15 +2908,17 @@ inline Reference& Reference::operator =(Reference&& other) { template inline Reference::Reference(const Reference& other) - : _env(other._env), _ref(nullptr), _suppressDestruct(false) { + : _env(other._env), _ref(nullptr), _suppressDestruct(false) { HandleScope scope(_env); napi_value value = other.Value(); if (value != nullptr) { - // Copying is a limited scenario (currently only used for Error object) and always creates a - // strong reference to the given value even if the incoming reference is weak. + // Copying is a limited scenario (currently only used for Error object) and + // always creates a strong reference to the given value even if the incoming + // reference is weak. napi_status status = napi_create_reference(_env, value, 1, &_ref); - NAPI_FATAL_IF_FAILED(status, "Reference::Reference", "napi_create_reference"); + NAPI_FATAL_IF_FAILED( + status, "Reference::Reference", "napi_create_reference"); } } @@ -2933,14 +2928,14 @@ inline Reference::operator napi_ref() const { } template -inline bool Reference::operator ==(const Reference &other) const { +inline bool Reference::operator==(const Reference& other) const { HandleScope scope(_env); return this->Value().StrictEquals(other.Value()); } template -inline bool Reference::operator !=(const Reference &other) const { - return !this->operator ==(other); +inline bool Reference::operator!=(const Reference& other) const { + return !this->operator==(other); } template @@ -3037,33 +3032,29 @@ inline FunctionReference Persistent(Function value) { // ObjectReference class //////////////////////////////////////////////////////////////////////////////// -inline ObjectReference::ObjectReference(): Reference() { -} +inline ObjectReference::ObjectReference() : Reference() {} -inline ObjectReference::ObjectReference(napi_env env, napi_ref ref): Reference(env, ref) { -} +inline ObjectReference::ObjectReference(napi_env env, napi_ref ref) + : Reference(env, ref) {} inline ObjectReference::ObjectReference(Reference&& other) - : Reference(std::move(other)) { -} + : Reference(std::move(other)) {} -inline ObjectReference& ObjectReference::operator =(Reference&& other) { +inline ObjectReference& ObjectReference::operator=(Reference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline ObjectReference::ObjectReference(ObjectReference&& other) - : Reference(std::move(other)) { -} + : Reference(std::move(other)) {} -inline ObjectReference& ObjectReference::operator =(ObjectReference&& other) { +inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline ObjectReference::ObjectReference(const ObjectReference& other) - : Reference(other) { -} + : Reference(other) {} inline MaybeOrValue ObjectReference::Get( const char* utf8name) const { @@ -3215,27 +3206,25 @@ inline MaybeOrValue ObjectReference::Set(uint32_t index, // FunctionReference class //////////////////////////////////////////////////////////////////////////////// -inline FunctionReference::FunctionReference(): Reference() { -} +inline FunctionReference::FunctionReference() : Reference() {} inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) - : Reference(env, ref) { -} + : Reference(env, ref) {} inline FunctionReference::FunctionReference(Reference&& other) - : Reference(std::move(other)) { -} + : Reference(std::move(other)) {} -inline FunctionReference& FunctionReference::operator =(Reference&& other) { +inline FunctionReference& FunctionReference::operator=( + Reference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline FunctionReference::FunctionReference(FunctionReference&& other) - : Reference(std::move(other)) { -} + : Reference(std::move(other)) {} -inline FunctionReference& FunctionReference::operator =(FunctionReference&& other) { +inline FunctionReference& FunctionReference::operator=( + FunctionReference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } @@ -3441,10 +3430,15 @@ inline MaybeOrValue FunctionReference::New( //////////////////////////////////////////////////////////////////////////////// inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) - : _env(env), _info(info), _this(nullptr), _dynamicArgs(nullptr), _data(nullptr) { + : _env(env), + _info(info), + _this(nullptr), + _dynamicArgs(nullptr), + _data(nullptr) { _argc = _staticArgCount; _argv = _staticArgs; - napi_status status = napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); + napi_status status = + napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); NAPI_THROW_IF_FAILED_VOID(_env, status); if (_argc > _staticArgCount) { @@ -3483,7 +3477,7 @@ inline size_t CallbackInfo::Length() const { return _argc; } -inline const Value CallbackInfo::operator [](size_t index) const { +inline const Value CallbackInfo::operator[](size_t index) const { return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); } @@ -3507,10 +3501,8 @@ inline void CallbackInfo::SetData(void* data) { //////////////////////////////////////////////////////////////////////////////// template -PropertyDescriptor -PropertyDescriptor::Accessor(const char* utf8name, - napi_property_attributes attributes, - void* data) { +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; @@ -3522,18 +3514,16 @@ PropertyDescriptor::Accessor(const char* utf8name, } template -PropertyDescriptor -PropertyDescriptor::Accessor(const std::string& utf8name, - napi_property_attributes attributes, - void* data) { +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { return Accessor(utf8name.c_str(), attributes, data); } template -PropertyDescriptor -PropertyDescriptor::Accessor(Name name, - napi_property_attributes attributes, - void* data) { +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; @@ -3544,14 +3534,10 @@ PropertyDescriptor::Accessor(Name name, return desc; } -template < -typename PropertyDescriptor::GetterCallback Getter, -typename PropertyDescriptor::SetterCallback Setter> -PropertyDescriptor -PropertyDescriptor::Accessor(const char* utf8name, - napi_property_attributes attributes, - void* data) { - +template +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; @@ -3563,23 +3549,19 @@ PropertyDescriptor::Accessor(const char* utf8name, return desc; } -template < -typename PropertyDescriptor::GetterCallback Getter, -typename PropertyDescriptor::SetterCallback Setter> -PropertyDescriptor -PropertyDescriptor::Accessor(const std::string& utf8name, - napi_property_attributes attributes, - void* data) { +template +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { return Accessor(utf8name.c_str(), attributes, data); } -template < -typename PropertyDescriptor::GetterCallback Getter, -typename PropertyDescriptor::SetterCallback Setter> -PropertyDescriptor -PropertyDescriptor::Accessor(Name name, - napi_property_attributes attributes, - void* data) { +template +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; @@ -3592,15 +3574,15 @@ PropertyDescriptor::Accessor(Name name, } template -inline PropertyDescriptor -PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { using CbData = details::CallbackData; - auto callbackData = new CbData({ getter, data }); + auto callbackData = new CbData({getter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { @@ -3608,37 +3590,37 @@ PropertyDescriptor::Accessor(Napi::Env env, NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } - return PropertyDescriptor({ - utf8name, - nullptr, - nullptr, - CbData::Wrapper, - nullptr, - nullptr, - attributes, - callbackData - }); + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Getter getter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { return Accessor(env, object, utf8name.c_str(), getter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes, + void* data) { using CbData = details::CallbackData; - auto callbackData = new CbData({ getter, data }); + auto callbackData = new CbData({getter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { @@ -3646,28 +3628,27 @@ inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } - return PropertyDescriptor({ - nullptr, - name, - nullptr, - CbData::Wrapper, - nullptr, - nullptr, - attributes, - callbackData - }); + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { using CbData = details::AccessorCallbackData; - auto callbackData = new CbData({ getter, setter, data }); + auto callbackData = new CbData({getter, setter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { @@ -3675,39 +3656,40 @@ inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } - return PropertyDescriptor({ - utf8name, - nullptr, - nullptr, - CbData::GetterWrapper, - CbData::SetterWrapper, - nullptr, - attributes, - callbackData - }); + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { - return Accessor(env, object, utf8name.c_str(), getter, setter, attributes, data); +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor( + env, object, utf8name.c_str(), getter, setter, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { using CbData = details::AccessorCallbackData; - auto callbackData = new CbData({ getter, setter, data }); + auto callbackData = new CbData({getter, setter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { @@ -3715,99 +3697,99 @@ inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } - return PropertyDescriptor({ - nullptr, - name, - nullptr, - CbData::GetterWrapper, - CbData::SetterWrapper, - nullptr, - attributes, - callbackData - }); + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); } template -inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, - Napi::Object /*object*/, - const char* utf8name, - Callable cb, - napi_property_attributes attributes, - void* data) { - return PropertyDescriptor({ - utf8name, - nullptr, - nullptr, - nullptr, - nullptr, - Napi::Function::New(env, cb, utf8name, data), - attributes, - nullptr - }); +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, utf8name, data), + attributes, + nullptr}); } template -inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Callable cb, - napi_property_attributes attributes, - void* data) { +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { return Function(env, object, utf8name.c_str(), cb, attributes, data); } template -inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, - Napi::Object /*object*/, - Name name, - Callable cb, - napi_property_attributes attributes, - void* data) { - return PropertyDescriptor({ - nullptr, - name, - nullptr, - nullptr, - nullptr, - Napi::Function::New(env, cb, nullptr, data), - attributes, - nullptr - }); -} - -inline PropertyDescriptor PropertyDescriptor::Value(const char* utf8name, - napi_value value, - napi_property_attributes attributes) { - return PropertyDescriptor({ - utf8name, nullptr, nullptr, nullptr, nullptr, value, attributes, nullptr - }); +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({nullptr, + name, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, nullptr, data), + attributes, + nullptr}); } -inline PropertyDescriptor PropertyDescriptor::Value(const std::string& utf8name, - napi_value value, - napi_property_attributes attributes) { +inline PropertyDescriptor PropertyDescriptor::Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + value, + attributes, + nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes) { return Value(utf8name.c_str(), value, attributes); } -inline PropertyDescriptor PropertyDescriptor::Value(napi_value name, - napi_value value, - napi_property_attributes attributes) { - return PropertyDescriptor({ - nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr - }); +inline PropertyDescriptor PropertyDescriptor::Value( + napi_value name, napi_value value, napi_property_attributes attributes) { + return PropertyDescriptor( + {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr}); } -inline PropertyDescriptor PropertyDescriptor::Value(Name name, - Napi::Value value, - napi_property_attributes attributes) { +inline PropertyDescriptor PropertyDescriptor::Value( + Name name, Napi::Value value, napi_property_attributes attributes) { napi_value nameValue = name; napi_value valueValue = value; return PropertyDescriptor::Value(nameValue, valueValue, attributes); } inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) - : _desc(desc) { -} + : _desc(desc) {} inline PropertyDescriptor::operator napi_property_descriptor&() { return _desc; @@ -3822,26 +3804,22 @@ inline PropertyDescriptor::operator const napi_property_descriptor&() const { //////////////////////////////////////////////////////////////////////////////// template -inline void InstanceWrap::AttachPropData(napi_env env, - napi_value value, - const napi_property_descriptor* prop) { +inline void InstanceWrap::AttachPropData( + napi_env env, napi_value value, const napi_property_descriptor* prop) { napi_status status; if (!(prop->attributes & napi_static)) { if (prop->method == T::InstanceVoidMethodCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast(prop->data)); + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } else if (prop->method == T::InstanceMethodCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast(prop->data)); + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } else if (prop->getter == T::InstanceGetterCallbackWrapper || - prop->setter == T::InstanceSetterCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast(prop->data)); + prop->setter == T::InstanceSetterCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } } @@ -3854,7 +3832,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( napi_property_attributes attributes, void* data) { InstanceVoidMethodCallbackData* callbackData = - new InstanceVoidMethodCallbackData({ method, data}); + new InstanceVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; @@ -3870,7 +3848,8 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( InstanceMethodCallback method, napi_property_attributes attributes, void* data) { - InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; @@ -3887,7 +3866,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( napi_property_attributes attributes, void* data) { InstanceVoidMethodCallbackData* callbackData = - new InstanceVoidMethodCallbackData({ method, data}); + new InstanceVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; @@ -3903,7 +3882,8 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( InstanceMethodCallback method, napi_property_attributes attributes, void* data) { - InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; @@ -3916,9 +3896,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceVoidCallback; @@ -3930,9 +3908,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceCallback; @@ -3944,9 +3920,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceVoidCallback; @@ -3958,9 +3932,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceCallback; @@ -3977,7 +3949,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( napi_property_attributes attributes, void* data) { InstanceAccessorCallbackData* callbackData = - new InstanceAccessorCallbackData({ getter, setter, data }); + new InstanceAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; @@ -3996,7 +3968,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( napi_property_attributes attributes, void* data) { InstanceAccessorCallbackData* callbackData = - new InstanceAccessorCallbackData({ getter, setter, data }); + new InstanceAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; @@ -4011,9 +3983,7 @@ template template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedInstanceCallback; @@ -4027,9 +3997,7 @@ template template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedInstanceCallback; @@ -4053,9 +4021,7 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceValue( template inline ClassPropertyDescriptor InstanceWrap::InstanceValue( - Symbol name, - Napi::Value value, - napi_property_attributes attributes) { + Symbol name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.value = value; @@ -4065,12 +4031,11 @@ inline ClassPropertyDescriptor InstanceWrap::InstanceValue( template inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); InstanceVoidMethodCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; @@ -4081,12 +4046,11 @@ inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( template inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); InstanceMethodCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; @@ -4096,12 +4060,11 @@ inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( template inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->getterCallback; @@ -4111,12 +4074,11 @@ inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( template inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->setterCallback; @@ -4169,7 +4131,7 @@ inline ObjectWrap::~ObjectWrap() { } } -template +template inline T* ObjectWrap::Unwrap(Object wrapper) { void* unwrapped; napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped); @@ -4178,12 +4140,12 @@ inline T* ObjectWrap::Unwrap(Object wrapper) { } template -inline Function -ObjectWrap::DefineClass(Napi::Env env, - const char* utf8name, - const size_t props_count, - const napi_property_descriptor* descriptors, - void* data) { +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* descriptors, + void* data) { napi_status status; std::vector props(props_count); @@ -4199,16 +4161,18 @@ ObjectWrap::DefineClass(Napi::Env env, props[index] = descriptors[index]; napi_property_descriptor* prop = &props[index]; if (prop->method == T::StaticMethodCallbackWrapper) { - status = CreateFunction(env, - utf8name, - prop->method, - static_cast(prop->data), - &(prop->value)); + status = + CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); NAPI_THROW_IF_FAILED(env, status, Function()); prop->method = nullptr; prop->data = nullptr; } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { - status = CreateFunction(env, + status = + CreateFunction(env, utf8name, prop->method, static_cast(prop->data), @@ -4238,9 +4202,8 @@ ObjectWrap::DefineClass(Napi::Env env, if (prop->getter == T::StaticGetterCallbackWrapper || prop->setter == T::StaticSetterCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast(prop->data)); + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED(env, status, Function()); } else { // InstanceWrap::AttachPropData is responsible for attaching the data @@ -4258,11 +4221,12 @@ inline Function ObjectWrap::DefineClass( const char* utf8name, const std::initializer_list>& properties, void* data) { - return DefineClass(env, - utf8name, - properties.size(), - reinterpret_cast(properties.begin()), - data); + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.begin()), + data); } template @@ -4271,11 +4235,12 @@ inline Function ObjectWrap::DefineClass( const char* utf8name, const std::vector>& properties, void* data) { - return DefineClass(env, - utf8name, - properties.size(), - reinterpret_cast(properties.data()), - data); + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.data()), + data); } template @@ -4284,13 +4249,15 @@ inline ClassPropertyDescriptor ObjectWrap::StaticMethod( StaticVoidMethodCallback method, napi_property_attributes attributes, void* data) { - StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::StaticVoidMethodCallbackWrapper; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4300,13 +4267,15 @@ inline ClassPropertyDescriptor ObjectWrap::StaticMethod( StaticMethodCallback method, napi_property_attributes attributes, void* data) { - StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::StaticMethodCallbackWrapper; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4316,13 +4285,15 @@ inline ClassPropertyDescriptor ObjectWrap::StaticMethod( StaticVoidMethodCallback method, napi_property_attributes attributes, void* data) { - StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::StaticVoidMethodCallbackWrapper; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4332,69 +4303,67 @@ inline ClassPropertyDescriptor ObjectWrap::StaticMethod( StaticMethodCallback method, napi_property_attributes attributes, void* data) { - StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::StaticMethodCallbackWrapper; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template template ::StaticVoidMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedVoidCallback; desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template template ::StaticVoidMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedVoidCallback; desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template template ::StaticMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedCallback; desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template template ::StaticMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedCallback; desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4406,14 +4375,15 @@ inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( napi_property_attributes attributes, void* data) { StaticAccessorCallbackData* callbackData = - new StaticAccessorCallbackData({ getter, setter, data }); + new StaticAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4425,14 +4395,15 @@ inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( napi_property_attributes attributes, void* data) { StaticAccessorCallbackData* callbackData = - new StaticAccessorCallbackData({ getter, setter, data }); + new StaticAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; desc.data = callbackData; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4440,15 +4411,14 @@ template template ::StaticGetterCallback getter, typename ObjectWrap::StaticSetterCallback setter> inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( - const char* utf8name, - napi_property_attributes attributes, - void* data) { + const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedCallback; desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4456,35 +4426,38 @@ template template ::StaticGetterCallback getter, typename ObjectWrap::StaticSetterCallback setter> inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( - Symbol name, - napi_property_attributes attributes, - void* data) { + Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedCallback; desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); desc.data = data; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template -inline ClassPropertyDescriptor ObjectWrap::StaticValue(const char* utf8name, - Napi::Value value, napi_property_attributes attributes) { +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.value = value; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } template -inline ClassPropertyDescriptor ObjectWrap::StaticValue(Symbol name, - Napi::Value value, napi_property_attributes attributes) { +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + Symbol name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.value = value; - desc.attributes = static_cast(attributes | napi_static); + desc.attributes = + static_cast(attributes | napi_static); return desc; } @@ -4502,8 +4475,7 @@ inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} template inline napi_value ObjectWrap::ConstructorCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { napi_value new_target; napi_status status = napi_get_new_target(env, info, &new_target); if (status != napi_ok) return nullptr; @@ -4528,7 +4500,7 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( } else { instance->_construction_failed = false; } -# endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS return callbackInfo.This(); }); @@ -4537,12 +4509,11 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( template inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); StaticVoidMethodCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->callback(callbackInfo); return nullptr; @@ -4551,12 +4522,11 @@ inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( template inline napi_value ObjectWrap::StaticMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); StaticMethodCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->callback(callbackInfo); }); @@ -4564,12 +4534,11 @@ inline napi_value ObjectWrap::StaticMethodCallbackWrapper( template inline napi_value ObjectWrap::StaticGetterCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->getterCallback(callbackInfo); }); @@ -4577,12 +4546,11 @@ inline napi_value ObjectWrap::StaticGetterCallbackWrapper( template inline napi_value ObjectWrap::StaticSetterCallbackWrapper( - napi_env env, - napi_callback_info info) { + napi_env env, napi_callback_info info) { return details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = - reinterpret_cast(callbackInfo.Data()); + reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->setterCallback(callbackInfo, callbackInfo[0]); return nullptr; @@ -4590,7 +4558,9 @@ inline napi_value ObjectWrap::StaticSetterCallbackWrapper( } template -inline void ObjectWrap::FinalizeCallback(napi_env env, void* data, void* /*hint*/) { +inline void ObjectWrap::FinalizeCallback(napi_env env, + void* data, + void* /*hint*/) { HandleScope scope(env); T* instance = static_cast(data); instance->Finalize(Napi::Env(env)); @@ -4613,8 +4583,7 @@ inline napi_value ObjectWrap::WrappedMethod( //////////////////////////////////////////////////////////////////////////////// inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) - : _env(env), _scope(scope) { -} + : _env(env), _scope(scope) {} inline HandleScope::HandleScope(Napi::Env env) : _env(env) { napi_status status = napi_open_handle_scope(_env, &_scope); @@ -4623,9 +4592,8 @@ inline HandleScope::HandleScope(Napi::Env env) : _env(env) { inline HandleScope::~HandleScope() { napi_status status = napi_close_handle_scope(_env, _scope); - NAPI_FATAL_IF_FAILED(status, - "HandleScope::~HandleScope", - "napi_close_handle_scope"); + NAPI_FATAL_IF_FAILED( + status, "HandleScope::~HandleScope", "napi_close_handle_scope"); } inline HandleScope::operator napi_handle_scope() const { @@ -4641,8 +4609,8 @@ inline Napi::Env HandleScope::Env() const { //////////////////////////////////////////////////////////////////////////////// inline EscapableHandleScope::EscapableHandleScope( - napi_env env, napi_escapable_handle_scope scope) : _env(env), _scope(scope) { -} + napi_env env, napi_escapable_handle_scope scope) + : _env(env), _scope(scope) {} inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { napi_status status = napi_open_escapable_handle_scope(_env, &_scope); @@ -4671,28 +4639,25 @@ inline Value EscapableHandleScope::Escape(napi_value escapee) { return Value(_env, result); } - #if (NAPI_VERSION > 2) //////////////////////////////////////////////////////////////////////////////// // CallbackScope class //////////////////////////////////////////////////////////////////////////////// -inline CallbackScope::CallbackScope( - napi_env env, napi_callback_scope scope) : _env(env), _scope(scope) { -} +inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope) + : _env(env), _scope(scope) {} inline CallbackScope::CallbackScope(napi_env env, napi_async_context context) : _env(env) { - napi_status status = napi_open_callback_scope( - _env, Object::New(env), context, &_scope); + napi_status status = + napi_open_callback_scope(_env, Object::New(env), context, &_scope); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline CallbackScope::~CallbackScope() { napi_status status = napi_close_callback_scope(_env, _scope); - NAPI_FATAL_IF_FAILED(status, - "CallbackScope::~CallbackScope", - "napi_close_callback_scope"); + NAPI_FATAL_IF_FAILED( + status, "CallbackScope::~CallbackScope", "napi_close_callback_scope"); } inline CallbackScope::operator napi_callback_scope() const { @@ -4709,8 +4674,7 @@ inline Napi::Env CallbackScope::Env() const { //////////////////////////////////////////////////////////////////////////////// inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) - : AsyncContext(env, resource_name, Object::New(env)) { -} + : AsyncContext(env, resource_name, Object::New(env)) {} inline AsyncContext::AsyncContext(napi_env env, const char* resource_name, @@ -4739,7 +4703,7 @@ inline AsyncContext::AsyncContext(AsyncContext&& other) { other._context = nullptr; } -inline AsyncContext& AsyncContext::operator =(AsyncContext&& other) { +inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) { _env = other._env; other._env = nullptr; _context = other._context; @@ -4760,78 +4724,72 @@ inline Napi::Env AsyncContext::Env() const { //////////////////////////////////////////////////////////////////////////////// inline AsyncWorker::AsyncWorker(const Function& callback) - : AsyncWorker(callback, "generic") { -} + : AsyncWorker(callback, "generic") {} inline AsyncWorker::AsyncWorker(const Function& callback, const char* resource_name) - : AsyncWorker(callback, resource_name, Object::New(callback.Env())) { -} + : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {} inline AsyncWorker::AsyncWorker(const Function& callback, const char* resource_name, const Object& resource) - : AsyncWorker(Object::New(callback.Env()), - callback, - resource_name, - resource) { -} + : AsyncWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback) - : AsyncWorker(receiver, callback, "generic") { -} + : AsyncWorker(receiver, callback, "generic") {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name) - : AsyncWorker(receiver, - callback, - resource_name, - Object::New(callback.Env())) { -} + : AsyncWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource) - : _env(callback.Env()), - _receiver(Napi::Persistent(receiver)), - _callback(Napi::Persistent(callback)), - _suppress_destruct(false) { + : _env(callback.Env()), + _receiver(Napi::Persistent(receiver)), + _callback(Napi::Persistent(callback)), + _suppress_destruct(false) { napi_value resource_id; napi_status status = napi_create_string_latin1( _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); NAPI_THROW_IF_FAILED_VOID(_env, status); - status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, - OnAsyncWorkComplete, this, &_work); + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); NAPI_THROW_IF_FAILED_VOID(_env, status); } -inline AsyncWorker::AsyncWorker(Napi::Env env) - : AsyncWorker(env, "generic") { -} +inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {} -inline AsyncWorker::AsyncWorker(Napi::Env env, - const char* resource_name) - : AsyncWorker(env, resource_name, Object::New(env)) { -} +inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name) + : AsyncWorker(env, resource_name, Object::New(env)) {} inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name, const Object& resource) - : _env(env), - _receiver(), - _callback(), - _suppress_destruct(false) { + : _env(env), _receiver(), _callback(), _suppress_destruct(false) { napi_value resource_id; napi_status status = napi_create_string_latin1( _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); NAPI_THROW_IF_FAILED_VOID(_env, status); - status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, - OnAsyncWorkComplete, this, &_work); + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); NAPI_THROW_IF_FAILED_VOID(_env, status); } @@ -4857,7 +4815,7 @@ inline AsyncWorker::AsyncWorker(AsyncWorker&& other) { _suppress_destruct = other._suppress_destruct; } -inline AsyncWorker& AsyncWorker::operator =(AsyncWorker&& other) { +inline AsyncWorker& AsyncWorker::operator=(AsyncWorker&& other) { _env = other._env; other._env = nullptr; _work = other._work; @@ -4907,7 +4865,8 @@ inline void AsyncWorker::OnOK() { inline void AsyncWorker::OnError(const Error& e) { if (!_callback.IsEmpty()) { - _callback.Call(_receiver.Value(), std::initializer_list{ e.Value() }); + _callback.Call(_receiver.Value(), + std::initializer_list{e.Value()}); } } @@ -4937,9 +4896,9 @@ inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { } catch (const std::exception& e) { SetError(e.what()); } -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS Execute(); -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS } inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, @@ -4954,8 +4913,7 @@ inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) { details::WrapCallback([&] { if (_error.size() == 0) { OnOK(); - } - else { + } else { OnError(Error::New(_env, _error)); } return nullptr; @@ -5458,68 +5416,93 @@ TypedThreadSafeFunction::FunctionOrEmpty( // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount); + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New( + env, callback, Object(), resourceName, maxQueueSize, initialThreadCount); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount, context); + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount, finalizeCallback); + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback); } // static -template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback, - FinalizerDataType* data) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount, finalizeCallback, data); + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback, + data); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount, context, finalizeCallback); + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback); } // static -template +template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, @@ -5528,89 +5511,128 @@ inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { - return New(env, callback, Object(), resourceName, maxQueueSize, - initialThreadCount, context, finalizeCallback, data); + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, static_cast(nullptr) /* context */); + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, context, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, [](Env, ContextType*) {} /* empty finalizer */); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, static_cast(nullptr) /* context */, - finalizeCallback, static_cast(nullptr) /* data */, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + static_cast(nullptr) /* data */, details::ThreadSafeFinalize::Wrapper); } // static -template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback, - FinalizerDataType* data) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, static_cast(nullptr) /* context */, - finalizeCallback, data, - details::ThreadSafeFinalize< - void, Finalizer, FinalizerDataType>::FinalizeWrapperWithData); + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeWrapperWithData); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, context, finalizeCallback, - static_cast(nullptr) /* data */, - details::ThreadSafeFinalize< - ContextType, Finalizer>::FinalizeWrapperWithContext); + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::FinalizeWrapperWithContext); } // static -template +template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, @@ -5620,20 +5642,24 @@ inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { - return New(env, callback, resource, resourceName, maxQueueSize, - initialThreadCount, context, finalizeCallback, data, - details::ThreadSafeFinalize::FinalizeFinalizeWrapperWithDataAndContext); + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext); } -inline ThreadSafeFunction::ThreadSafeFunction() - : _tsfn() { -} +inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {} -inline ThreadSafeFunction::ThreadSafeFunction( - napi_threadsafe_function tsfn) - : _tsfn(tsfn) { -} +inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} inline ThreadSafeFunction::operator napi_threadsafe_function() const { return _tsfn; @@ -5644,20 +5670,18 @@ inline napi_status ThreadSafeFunction::BlockingCall() const { } template <> -inline napi_status ThreadSafeFunction::BlockingCall( - void* data) const { +inline napi_status ThreadSafeFunction::BlockingCall(void* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); } template -inline napi_status ThreadSafeFunction::BlockingCall( - Callback callback) const { +inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const { return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); } template -inline napi_status ThreadSafeFunction::BlockingCall( - DataType* data, Callback callback) const { +inline napi_status ThreadSafeFunction::BlockingCall(DataType* data, + Callback callback) const { auto wrapper = [data, callback](Env env, Function jsCallback) { callback(env, jsCallback, data); }; @@ -5669,8 +5693,7 @@ inline napi_status ThreadSafeFunction::NonBlockingCall() const { } template <> -inline napi_status ThreadSafeFunction::NonBlockingCall( - void* data) const { +inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); } @@ -5715,17 +5738,21 @@ inline napi_status ThreadSafeFunction::Abort() const { return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); } -inline ThreadSafeFunction::ConvertibleContext -ThreadSafeFunction::GetContext() const { +inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext() + const { void* context; napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); - NAPI_FATAL_IF_FAILED(status, "ThreadSafeFunction::GetContext", "napi_get_threadsafe_function_context"); - return ConvertibleContext({ context }); + NAPI_FATAL_IF_FAILED(status, + "ThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return ConvertibleContext({context}); } // static -template +template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, @@ -5736,16 +5763,26 @@ inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, Finalizer finalizeCallback, FinalizerDataType* data, napi_finalize wrapper) { - static_assert(details::can_make_string::value - || std::is_convertible::value, - "Resource name should be convertible to the string type"); + static_assert(details::can_make_string::value || + std::is_convertible::value, + "Resource name should be convertible to the string type"); ThreadSafeFunction tsfn; - auto* finalizeData = new details::ThreadSafeFinalize({ data, finalizeCallback }); - napi_status status = napi_create_threadsafe_function(env, callback, resource, - Value::From(env, resourceName), maxQueueSize, initialThreadCount, - finalizeData, wrapper, context, CallJS, &tsfn._tsfn); + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + Value::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + wrapper, + context, + CallJS, + &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction()); @@ -5757,8 +5794,8 @@ inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, inline napi_status ThreadSafeFunction::CallInternal( CallbackWrapper* callbackWrapper, napi_threadsafe_function_call_mode mode) const { - napi_status status = napi_call_threadsafe_function( - _tsfn, callbackWrapper, mode); + napi_status status = + napi_call_threadsafe_function(_tsfn, callbackWrapper, mode); if (status != napi_ok && callbackWrapper != nullptr) { delete callbackWrapper; } @@ -5788,13 +5825,15 @@ inline void ThreadSafeFunction::CallJS(napi_env env, // Async Progress Worker Base class //////////////////////////////////////////////////////////////////////////////// template -inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource, - size_t queue_size) - : AsyncWorker(receiver, callback, resource_name, resource) { - // Fill all possible arguments to work around ambiguous ThreadSafeFunction::New signatures. +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(receiver, callback, resource_name, resource) { + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. _tsfn = ThreadSafeFunction::New(callback.Env(), callback, resource, @@ -5808,15 +5847,18 @@ inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(const Object& #if NAPI_VERSION > 4 template -inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(Napi::Env env, - const char* resource_name, - const Object& resource, - size_t queue_size) - : AsyncWorker(env, resource_name, resource) { +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(env, resource_name, resource) { // TODO: Once the changes to make the callback optional for threadsafe - // functions are available on all versions we can remove the dummy Function here. + // functions are available on all versions we can remove the dummy Function + // here. Function callback; - // Fill all possible arguments to work around ambiguous ThreadSafeFunction::New signatures. + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. _tsfn = ThreadSafeFunction::New(env, callback, resource, @@ -5829,38 +5871,41 @@ inline AsyncProgressWorkerBase::AsyncProgressWorkerBase(Napi::Env env, } #endif -template +template inline AsyncProgressWorkerBase::~AsyncProgressWorkerBase() { // Abort pending tsfn call. // Don't send progress events after we've already completed. - // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release duplicated. + // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release + // duplicated. _tsfn.Abort(); } template -inline void AsyncProgressWorkerBase::OnAsyncWorkProgress(Napi::Env /* env */, - Napi::Function /* jsCallback */, - void* data) { +inline void AsyncProgressWorkerBase::OnAsyncWorkProgress( + Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) { ThreadSafeData* tsd = static_cast(data); tsd->asyncprogressworker()->OnWorkProgress(tsd->data()); delete tsd; } template -inline napi_status AsyncProgressWorkerBase::NonBlockingCall(DataType* data) { +inline napi_status AsyncProgressWorkerBase::NonBlockingCall( + DataType* data) { auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); return _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); } template -inline void AsyncProgressWorkerBase::OnWorkComplete(Napi::Env /* env */, napi_status status) { +inline void AsyncProgressWorkerBase::OnWorkComplete( + Napi::Env /* env */, napi_status status) { _work_completed = true; _complete_status = status; _tsfn.Release(); } template -inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize(Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { +inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize( + Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { if (context->_work_completed) { context->AsyncWorker::OnWorkComplete(env, context->_complete_status); } @@ -5869,76 +5914,64 @@ inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize(Napi //////////////////////////////////////////////////////////////////////////////// // Async Progress Worker class //////////////////////////////////////////////////////////////////////////////// -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback) - : AsyncProgressWorker(callback, "generic") { -} + : AsyncProgressWorker(callback, "generic") {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, - const char* resource_name) - : AsyncProgressWorker(callback, resource_name, Object::New(callback.Env())) { -} + const char* resource_name) + : AsyncProgressWorker( + callback, resource_name, Object::New(callback.Env())) {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, - const char* resource_name, - const Object& resource) - : AsyncProgressWorker(Object::New(callback.Env()), - callback, - resource_name, - resource) { -} + const char* resource_name, + const Object& resource) + : AsyncProgressWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback) - : AsyncProgressWorker(receiver, callback, "generic") { -} + : AsyncProgressWorker(receiver, callback, "generic") {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name) - : AsyncProgressWorker(receiver, - callback, - resource_name, - Object::New(callback.Env())) { -} + : AsyncProgressWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource) - : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), - _asyncdata(nullptr), - _asyncsize(0) { -} + : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) {} #if NAPI_VERSION > 4 -template +template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env) - : AsyncProgressWorker(env, "generic") { -} + : AsyncProgressWorker(env, "generic") {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, const char* resource_name) - : AsyncProgressWorker(env, resource_name, Object::New(env)) { -} + : AsyncProgressWorker(env, resource_name, Object::New(env)) {} -template +template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, const char* resource_name, const Object& resource) - : AsyncProgressWorkerBase(env, resource_name, resource), - _asyncdata(nullptr), - _asyncsize(0) { -} + : AsyncProgressWorkerBase(env, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) {} #endif -template +template inline AsyncProgressWorker::~AsyncProgressWorker() { { std::lock_guard lock(this->_mutex); @@ -5947,13 +5980,13 @@ inline AsyncProgressWorker::~AsyncProgressWorker() { } } -template +template inline void AsyncProgressWorker::Execute() { ExecutionProgress progress(this); Execute(progress); } -template +template inline void AsyncProgressWorker::OnWorkProgress(void*) { T* data; size_t size; @@ -5980,119 +6013,114 @@ inline void AsyncProgressWorker::OnWorkProgress(void*) { delete[] data; } -template +template inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { - T* new_data = new T[count]; - std::copy(data, data + count, new_data); - - T* old_data; - { - std::lock_guard lock(this->_mutex); - old_data = _asyncdata; - _asyncdata = new_data; - _asyncsize = count; - } - this->NonBlockingCall(nullptr); + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + T* old_data; + { + std::lock_guard lock(this->_mutex); + old_data = _asyncdata; + _asyncdata = new_data; + _asyncsize = count; + } + this->NonBlockingCall(nullptr); - delete[] old_data; + delete[] old_data; } -template +template inline void AsyncProgressWorker::Signal() const { this->NonBlockingCall(static_cast(nullptr)); } -template +template inline void AsyncProgressWorker::ExecutionProgress::Signal() const { _worker->Signal(); } -template -inline void AsyncProgressWorker::ExecutionProgress::Send(const T* data, size_t count) const { +template +inline void AsyncProgressWorker::ExecutionProgress::Send( + const T* data, size_t count) const { _worker->SendProgress_(data, count); } //////////////////////////////////////////////////////////////////////////////// // Async Progress Queue Worker class //////////////////////////////////////////////////////////////////////////////// -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback) - : AsyncProgressQueueWorker(callback, "generic") { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback) + : AsyncProgressQueueWorker(callback, "generic") {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback, - const char* resource_name) - : AsyncProgressQueueWorker(callback, resource_name, Object::New(callback.Env())) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + callback, resource_name, Object::New(callback.Env())) {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Function& callback, - const char* resource_name, - const Object& resource) - : AsyncProgressQueueWorker(Object::New(callback.Env()), - callback, - resource_name, - resource) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name, const Object& resource) + : AsyncProgressQueueWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, - const Function& callback) - : AsyncProgressQueueWorker(receiver, callback, "generic") { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback) + : AsyncProgressQueueWorker(receiver, callback, "generic") {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, - const Function& callback, - const char* resource_name) - : AsyncProgressQueueWorker(receiver, - callback, - resource_name, - Object::New(callback.Env())) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource) - : AsyncProgressWorkerBase>(receiver, callback, resource_name, resource, /** unlimited queue size */0) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase>( + receiver, + callback, + resource_name, + resource, + /** unlimited queue size */ 0) {} #if NAPI_VERSION > 4 -template +template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env) - : AsyncProgressQueueWorker(env, "generic") { -} + : AsyncProgressQueueWorker(env, "generic") {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env, - const char* resource_name) - : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name) + : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {} -template -inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env, - const char* resource_name, - const Object& resource) - : AsyncProgressWorkerBase>(env, resource_name, resource, /** unlimited queue size */0) { -} +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name, const Object& resource) + : AsyncProgressWorkerBase>( + env, resource_name, resource, /** unlimited queue size */ 0) {} #endif -template +template inline void AsyncProgressQueueWorker::Execute() { ExecutionProgress progress(this); Execute(progress); } -template -inline void AsyncProgressQueueWorker::OnWorkProgress(std::pair* datapair) { +template +inline void AsyncProgressQueueWorker::OnWorkProgress( + std::pair* datapair) { if (datapair == nullptr) { return; } - T *data = datapair->first; + T* data = datapair->first; size_t size = datapair->second; this->OnProgress(data, size); @@ -6100,33 +6128,36 @@ inline void AsyncProgressQueueWorker::OnWorkProgress(std::pair* d delete[] data; } -template -inline void AsyncProgressQueueWorker::SendProgress_(const T* data, size_t count) { - T* new_data = new T[count]; - std::copy(data, data + count, new_data); +template +inline void AsyncProgressQueueWorker::SendProgress_(const T* data, + size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); - auto pair = new std::pair(new_data, count); - this->NonBlockingCall(pair); + auto pair = new std::pair(new_data, count); + this->NonBlockingCall(pair); } -template +template inline void AsyncProgressQueueWorker::Signal() const { this->NonBlockingCall(nullptr); } -template -inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, napi_status status) { +template +inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, + napi_status status) { // Draining queued items in TSFN. AsyncProgressWorkerBase>::OnWorkComplete(env, status); } -template +template inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { _worker->Signal(); } -template -inline void AsyncProgressQueueWorker::ExecutionProgress::Send(const T* data, size_t count) const { +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Send( + const T* data, size_t count) const { _worker->SendProgress_(data, count); } #endif // NAPI_VERSION > 3 && !defined(__wasm32__) @@ -6135,9 +6166,11 @@ inline void AsyncProgressQueueWorker::ExecutionProgress::Send(const T* data, // Memory Management class //////////////////////////////////////////////////////////////////////////////// -inline int64_t MemoryManagement::AdjustExternalMemory(Env env, int64_t change_in_bytes) { +inline int64_t MemoryManagement::AdjustExternalMemory(Env env, + int64_t change_in_bytes) { int64_t result; - napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); + napi_status status = + napi_adjust_external_memory(env, change_in_bytes, &result); NAPI_THROW_IF_FAILED(env, status, 0); return result; } @@ -6178,24 +6211,20 @@ inline T* Addon::Unwrap(Object wrapper) { } template -inline void -Addon::DefineAddon(Object exports, - const std::initializer_list& props) { +inline void Addon::DefineAddon( + Object exports, const std::initializer_list& props) { DefineProperties(exports, props); entry_point_ = exports; } template -inline Napi::Object -Addon::DefineProperties(Object object, - const std::initializer_list& props) { +inline Napi::Object Addon::DefineProperties( + Object object, const std::initializer_list& props) { const napi_property_descriptor* properties = - reinterpret_cast(props.begin()); + reinterpret_cast(props.begin()); size_t size = props.size(); - napi_status status = napi_define_properties(object.Env(), - object, - size, - properties); + napi_status status = + napi_define_properties(object.Env(), object, size, properties); NAPI_THROW_IF_FAILED(object.Env(), status, object); for (size_t idx = 0; idx < size; idx++) T::AttachPropData(object.Env(), object, &properties[idx]); @@ -6254,6 +6283,6 @@ bool Env::CleanupHook::IsEmpty() const { } // namespace NAPI_CPP_CUSTOM_NAMESPACE #endif -} // namespace Napi +} // namespace Napi -#endif // SRC_NAPI_INL_H_ +#endif // SRC_NAPI_INL_H_ diff --git a/napi.h b/napi.h index c88ca3d45..0fd18c85f 100644 --- a/napi.h +++ b/napi.h @@ -9,29 +9,32 @@ #include #include -// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known good version) +// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known +// good version) #if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 #define NAPI_HAS_CONSTEXPR 1 #endif -// VS2013 does not support char16_t literal strings, so we'll work around it using wchar_t strings -// and casting them. This is safe as long as the character sizes are the same. +// VS2013 does not support char16_t literal strings, so we'll work around it +// using wchar_t strings and casting them. This is safe as long as the character +// sizes are the same. #if defined(_MSC_VER) && _MSC_VER <= 1800 -static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16_t and wchar_t"); -#define NAPI_WIDE_TEXT(x) reinterpret_cast(L ## x) +static_assert(sizeof(char16_t) == sizeof(wchar_t), + "Size mismatch between char16_t and wchar_t"); +#define NAPI_WIDE_TEXT(x) reinterpret_cast(L##x) #else -#define NAPI_WIDE_TEXT(x) u ## x +#define NAPI_WIDE_TEXT(x) u##x #endif // If C++ exceptions are not explicitly enabled or disabled, enable them // if exceptions were enabled in the compiler settings. #if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) - #if defined(_CPPUNWIND) || defined (__EXCEPTIONS) - #define NAPI_CPP_EXCEPTIONS - #else - #error Exception support not detected. \ +#if defined(_CPPUNWIND) || defined(__EXCEPTIONS) +#define NAPI_CPP_EXCEPTIONS +#else +#error Exception support not detected. \ Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. - #endif +#endif #endif // If C++ NAPI_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE should @@ -42,9 +45,9 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16 #endif #ifdef _NOEXCEPT - #define NAPI_NOEXCEPT _NOEXCEPT +#define NAPI_NOEXCEPT _NOEXCEPT #else - #define NAPI_NOEXCEPT noexcept +#define NAPI_NOEXCEPT noexcept #endif #ifdef NAPI_CPP_EXCEPTIONS @@ -55,16 +58,16 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16 // We need _VOID versions of the macros to avoid warnings resulting from // leaving the NAPI_THROW_* `...` argument empty. -#define NAPI_THROW(e, ...) throw e -#define NAPI_THROW_VOID(e) throw e +#define NAPI_THROW(e, ...) throw e +#define NAPI_THROW_VOID(e) throw e -#define NAPI_THROW_IF_FAILED(env, status, ...) \ +#define NAPI_THROW_IF_FAILED(env, status, ...) \ if ((status) != napi_ok) throw Napi::Error::New(env); -#define NAPI_THROW_IF_FAILED_VOID(env, status) \ +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ if ((status) != napi_ok) throw Napi::Error::New(env); -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS // When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, // which are pending until the callback returns to JS. The variadic parameter @@ -72,16 +75,16 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16 // We need _VOID versions of the macros to avoid warnings resulting from // leaving the NAPI_THROW_* `...` argument empty. -#define NAPI_THROW(e, ...) \ - do { \ - (e).ThrowAsJavaScriptException(); \ - return __VA_ARGS__; \ +#define NAPI_THROW(e, ...) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ } while (0) -#define NAPI_THROW_VOID(e) \ - do { \ - (e).ThrowAsJavaScriptException(); \ - return; \ +#define NAPI_THROW_VOID(e) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return; \ } while (0) #define NAPI_THROW_IF_FAILED(env, status, ...) \ @@ -96,7 +99,7 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16 return; \ } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS #ifdef NODE_ADDON_API_ENABLE_MAYBE #define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ @@ -114,12 +117,12 @@ static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16 return result; #endif -# define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; -# define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; +#define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +#define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; -#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ - NAPI_DISALLOW_ASSIGN(CLASS) \ - NAPI_DISALLOW_COPY(CLASS) +#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ + NAPI_DISALLOW_ASSIGN(CLASS) \ + NAPI_DISALLOW_COPY(CLASS) #define NAPI_CHECK(condition, location, message) \ do { \ @@ -152,2852 +155,2963 @@ using namespace NAPI_CPP_CUSTOM_NAMESPACE; namespace NAPI_CPP_CUSTOM_NAMESPACE { #endif - // Forward declarations - class Env; - class Value; - class Boolean; - class Number; +// Forward declarations +class Env; +class Value; +class Boolean; +class Number; #if NAPI_VERSION > 5 - class BigInt; +class BigInt; #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) - class Date; +class Date; #endif - class String; - class Object; - class Array; - class ArrayBuffer; - class Function; - class Error; - class PropertyDescriptor; - class CallbackInfo; - class TypedArray; - template class TypedArrayOf; - - using Int8Array = - TypedArrayOf; ///< Typed-array of signed 8-bit integers - using Uint8Array = - TypedArrayOf; ///< Typed-array of unsigned 8-bit integers - using Int16Array = - TypedArrayOf; ///< Typed-array of signed 16-bit integers - using Uint16Array = - TypedArrayOf; ///< Typed-array of unsigned 16-bit integers - using Int32Array = - TypedArrayOf; ///< Typed-array of signed 32-bit integers - using Uint32Array = - TypedArrayOf; ///< Typed-array of unsigned 32-bit integers - using Float32Array = - TypedArrayOf; ///< Typed-array of 32-bit floating-point values - using Float64Array = - TypedArrayOf; ///< Typed-array of 64-bit floating-point values +class String; +class Object; +class Array; +class ArrayBuffer; +class Function; +class Error; +class PropertyDescriptor; +class CallbackInfo; +class TypedArray; +template +class TypedArrayOf; + +using Int8Array = + TypedArrayOf; ///< Typed-array of signed 8-bit integers +using Uint8Array = + TypedArrayOf; ///< Typed-array of unsigned 8-bit integers +using Int16Array = + TypedArrayOf; ///< Typed-array of signed 16-bit integers +using Uint16Array = + TypedArrayOf; ///< Typed-array of unsigned 16-bit integers +using Int32Array = + TypedArrayOf; ///< Typed-array of signed 32-bit integers +using Uint32Array = + TypedArrayOf; ///< Typed-array of unsigned 32-bit integers +using Float32Array = + TypedArrayOf; ///< Typed-array of 32-bit floating-point values +using Float64Array = + TypedArrayOf; ///< Typed-array of 64-bit floating-point values #if NAPI_VERSION > 5 - using BigInt64Array = - TypedArrayOf; ///< Typed array of signed 64-bit integers - using BigUint64Array = - TypedArrayOf; ///< Typed array of unsigned 64-bit integers -#endif // NAPI_VERSION > 5 - - /// Defines the signature of a Node-API C++ module's registration callback - /// (init) function. - using ModuleRegisterCallback = Object (*)(Env env, Object exports); +using BigInt64Array = + TypedArrayOf; ///< Typed array of signed 64-bit integers +using BigUint64Array = + TypedArrayOf; ///< Typed array of unsigned 64-bit integers +#endif // NAPI_VERSION > 5 - class MemoryManagement; - - /// A simple Maybe type, representing an object which may or may not have a - /// value. - /// - /// If an API method returns a Maybe<>, the API method can potentially fail - /// either because an exception is thrown, or because an exception is pending, - /// e.g. because a previous API call threw an exception that hasn't been - /// caught yet. In that case, a "Nothing" value is returned. - template - class Maybe { - public: - bool IsNothing() const; - bool IsJust() const; - - /// Short-hand for Unwrap(), which doesn't return a value. Could be used - /// where the actual value of the Maybe is not needed like Object::Set. - /// If this Maybe is nothing (empty), node-addon-api will crash the - /// process. - void Check() const; - - /// Return the value of type T contained in the Maybe. If this Maybe is - /// nothing (empty), node-addon-api will crash the process. - T Unwrap() const; - - /// Return the value of type T contained in the Maybe, or using a default - /// value if this Maybe is nothing (empty). - T UnwrapOr(const T& default_value) const; - - /// Converts this Maybe to a value of type T in the out. If this Maybe is - /// nothing (empty), `false` is returned and `out` is left untouched. - bool UnwrapTo(T* out) const; - - bool operator==(const Maybe& other) const; - bool operator!=(const Maybe& other) const; - - private: - Maybe(); - explicit Maybe(const T& t); +/// Defines the signature of a Node-API C++ module's registration callback +/// (init) function. +using ModuleRegisterCallback = Object (*)(Env env, Object exports); - bool _has_value; - T _value; +class MemoryManagement; - template - friend Maybe Nothing(); - template - friend Maybe Just(const U& u); - }; - - template - inline Maybe Nothing(); - - template - inline Maybe Just(const T& t); +/// A simple Maybe type, representing an object which may or may not have a +/// value. +/// +/// If an API method returns a Maybe<>, the API method can potentially fail +/// either because an exception is thrown, or because an exception is pending, +/// e.g. because a previous API call threw an exception that hasn't been +/// caught yet. In that case, a "Nothing" value is returned. +template +class Maybe { + public: + bool IsNothing() const; + bool IsJust() const; + + /// Short-hand for Unwrap(), which doesn't return a value. Could be used + /// where the actual value of the Maybe is not needed like Object::Set. + /// If this Maybe is nothing (empty), node-addon-api will crash the + /// process. + void Check() const; + + /// Return the value of type T contained in the Maybe. If this Maybe is + /// nothing (empty), node-addon-api will crash the process. + T Unwrap() const; + + /// Return the value of type T contained in the Maybe, or using a default + /// value if this Maybe is nothing (empty). + T UnwrapOr(const T& default_value) const; + + /// Converts this Maybe to a value of type T in the out. If this Maybe is + /// nothing (empty), `false` is returned and `out` is left untouched. + bool UnwrapTo(T* out) const; + + bool operator==(const Maybe& other) const; + bool operator!=(const Maybe& other) const; + + private: + Maybe(); + explicit Maybe(const T& t); + + bool _has_value; + T _value; + + template + friend Maybe Nothing(); + template + friend Maybe Just(const U& u); +}; + +template +inline Maybe Nothing(); + +template +inline Maybe Just(const T& t); #if defined(NODE_ADDON_API_ENABLE_MAYBE) - template - using MaybeOrValue = Maybe; +template +using MaybeOrValue = Maybe; #else - template - using MaybeOrValue = T; +template +using MaybeOrValue = T; #endif - /// Environment for Node-API values and operations. - /// - /// All Node-API values and operations must be associated with an environment. - /// An environment instance is always provided to callback functions; that - /// environment must then be used for any creation of Node-API values or other - /// Node-API operations within the callback. (Many methods infer the - /// environment from the `this` instance that the method is called on.) - /// - /// In the future, multiple environments per process may be supported, - /// although current implementations only support one environment per process. - /// - /// In the V8 JavaScript engine, a Node-API environment approximately - /// corresponds to an Isolate. - class Env { - private: +/// Environment for Node-API values and operations. +/// +/// All Node-API values and operations must be associated with an environment. +/// An environment instance is always provided to callback functions; that +/// environment must then be used for any creation of Node-API values or other +/// Node-API operations within the callback. (Many methods infer the +/// environment from the `this` instance that the method is called on.) +/// +/// In the future, multiple environments per process may be supported, +/// although current implementations only support one environment per process. +/// +/// In the V8 JavaScript engine, a Node-API environment approximately +/// corresponds to an Isolate. +class Env { + private: #if NAPI_VERSION > 2 - template - class CleanupHook; + template + class CleanupHook; #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 5 - template static void DefaultFini(Env, T* data); - template - static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); + template + static void DefaultFini(Env, T* data); + template + static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); #endif // NAPI_VERSION > 5 - public: - Env(napi_env env); + public: + Env(napi_env env); - operator napi_env() const; + operator napi_env() const; - Object Global() const; - Value Undefined() const; - Value Null() const; + Object Global() const; + Value Undefined() const; + Value Null() const; - bool IsExceptionPending() const; - Error GetAndClearPendingException() const; + bool IsExceptionPending() const; + Error GetAndClearPendingException() const; - MaybeOrValue RunScript(const char* utf8script) const; - MaybeOrValue RunScript(const std::string& utf8script) const; - MaybeOrValue RunScript(String script) const; + MaybeOrValue RunScript(const char* utf8script) const; + MaybeOrValue RunScript(const std::string& utf8script) const; + MaybeOrValue RunScript(String script) const; #if NAPI_VERSION > 2 - template - CleanupHook AddCleanupHook(Hook hook); + template + CleanupHook AddCleanupHook(Hook hook); - template - CleanupHook AddCleanupHook(Hook hook, Arg* arg); + template + CleanupHook AddCleanupHook(Hook hook, Arg* arg); #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 5 - template - T* GetInstanceData() const; - - template using Finalizer = void (*)(Env, T*); - template fini = Env::DefaultFini> - void SetInstanceData(T* data) const; - - template - using FinalizerWithHint = void (*)(Env, DataType*, HintType*); - template fini = - Env::DefaultFiniWithHint> - void SetInstanceData(DataType* data, HintType* hint) const; + template + T* GetInstanceData() const; + + template + using Finalizer = void (*)(Env, T*); + template fini = Env::DefaultFini> + void SetInstanceData(T* data) const; + + template + using FinalizerWithHint = void (*)(Env, DataType*, HintType*); + template fini = + Env::DefaultFiniWithHint> + void SetInstanceData(DataType* data, HintType* hint) const; #endif // NAPI_VERSION > 5 - private: - napi_env _env; + private: + napi_env _env; #if NAPI_VERSION > 2 - template - class CleanupHook { - public: - CleanupHook(Env env, Hook hook, Arg* arg); - CleanupHook(Env env, Hook hook); - bool Remove(Env env); - bool IsEmpty() const; - - private: - static inline void Wrapper(void* data) NAPI_NOEXCEPT; - static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT; - - void (*wrapper)(void* arg); - struct CleanupData { - Hook hook; - Arg* arg; - } * data; - }; + template + class CleanupHook { + public: + CleanupHook(Env env, Hook hook, Arg* arg); + CleanupHook(Env env, Hook hook); + bool Remove(Env env); + bool IsEmpty() const; + + private: + static inline void Wrapper(void* data) NAPI_NOEXCEPT; + static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT; + + void (*wrapper)(void* arg); + struct CleanupData { + Hook hook; + Arg* arg; + } * data; }; +}; #endif // NAPI_VERSION > 2 - /// A JavaScript value of unknown type. - /// - /// For type-specific operations, convert to one of the Value subclasses using a `To*` or `As()` - /// method. The `To*` methods do type coercion; the `As()` method does not. +/// A JavaScript value of unknown type. +/// +/// For type-specific operations, convert to one of the Value subclasses using a +/// `To*` or `As()` method. The `To*` methods do type coercion; the `As()` +/// method does not. +/// +/// Napi::Value value = ... +/// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid +/// arg..."); Napi::String str = value.As(); // Cast to a +/// string value +/// +/// Napi::Value anotherValue = ... +/// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value +class Value { + public: + Value(); ///< Creates a new _empty_ Value instance. + Value(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Creates a JS value from a C++ primitive. /// - /// Napi::Value value = ... - /// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid arg..."); - /// Napi::String str = value.As(); // Cast to a string value + /// `value` may be any of: + /// - bool + /// - Any integer type + /// - Any floating point type + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + /// - napi::Value + /// - napi_value + template + static Value From(napi_env env, const T& value); + + /// Converts to a Node-API value primitive. /// - /// Napi::Value anotherValue = ... - /// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value - class Value { - public: - Value(); ///< Creates a new _empty_ Value instance. - Value(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + /// If the instance is _empty_, this returns `nullptr`. + operator napi_value() const; - /// Creates a JS value from a C++ primitive. - /// - /// `value` may be any of: - /// - bool - /// - Any integer type - /// - Any floating point type - /// - const char* (encoded using UTF-8, null-terminated) - /// - const char16_t* (encoded using UTF-16-LE, null-terminated) - /// - std::string (encoded using UTF-8) - /// - std::u16string - /// - napi::Value - /// - napi_value - template - static Value From(napi_env env, const T& value); - - /// Converts to a Node-API value primitive. - /// - /// If the instance is _empty_, this returns `nullptr`. - operator napi_value() const; - - /// Tests if this value strictly equals another value. - bool operator ==(const Value& other) const; - - /// Tests if this value does not strictly equal another value. - bool operator !=(const Value& other) const; - - /// Tests if this value strictly equals another value. - bool StrictEquals(const Value& other) const; - - /// Gets the environment the value is associated with. - Napi::Env Env() const; + /// Tests if this value strictly equals another value. + bool operator==(const Value& other) const; - /// Checks if the value is empty (uninitialized). - /// - /// An empty value is invalid, and most attempts to perform an operation on an empty value - /// will result in an exception. Note an empty value is distinct from JavaScript `null` or - /// `undefined`, which are valid values. - /// - /// When C++ exceptions are disabled at compile time, a method with a `Value` return type may - /// return an empty value to indicate a pending exception. So when not using C++ exceptions, - /// callers should check whether the value is empty before attempting to use it. - bool IsEmpty() const; + /// Tests if this value does not strictly equal another value. + bool operator!=(const Value& other) const; + + /// Tests if this value strictly equals another value. + bool StrictEquals(const Value& other) const; - napi_valuetype Type() const; ///< Gets the type of the value. + /// Gets the environment the value is associated with. + Napi::Env Env() const; - bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value. - bool IsNull() const; ///< Tests if a value is a null JavaScript value. - bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. - bool IsNumber() const; ///< Tests if a value is a JavaScript number. + /// Checks if the value is empty (uninitialized). + /// + /// An empty value is invalid, and most attempts to perform an operation on an + /// empty value will result in an exception. Note an empty value is distinct + /// from JavaScript `null` or `undefined`, which are valid values. + /// + /// When C++ exceptions are disabled at compile time, a method with a `Value` + /// return type may return an empty value to indicate a pending exception. So + /// when not using C++ exceptions, callers should check whether the value is + /// empty before attempting to use it. + bool IsEmpty() const; + + napi_valuetype Type() const; ///< Gets the type of the value. + + bool IsUndefined() + const; ///< Tests if a value is an undefined JavaScript value. + bool IsNull() const; ///< Tests if a value is a null JavaScript value. + bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. + bool IsNumber() const; ///< Tests if a value is a JavaScript number. #if NAPI_VERSION > 5 - bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. -#endif // NAPI_VERSION > 5 + bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. +#endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) - bool IsDate() const; ///< Tests if a value is a JavaScript date. + bool IsDate() const; ///< Tests if a value is a JavaScript date. #endif - bool IsString() const; ///< Tests if a value is a JavaScript string. - bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. - bool IsArray() const; ///< Tests if a value is a JavaScript array. - bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer. - bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. - bool IsObject() const; ///< Tests if a value is a JavaScript object. - bool IsFunction() const; ///< Tests if a value is a JavaScript function. - bool IsPromise() const; ///< Tests if a value is a JavaScript promise. - bool IsDataView() const; ///< Tests if a value is a JavaScript data view. - bool IsBuffer() const; ///< Tests if a value is a Node buffer. - bool IsExternal() const; ///< Tests if a value is a pointer to external data. - - /// Casts to another type of `Napi::Value`, when the actual type is known or assumed. - /// - /// This conversion does NOT coerce the type. Calling any methods inappropriate for the actual - /// value type will throw `Napi::Error`. - template T As() const; - - MaybeOrValue ToBoolean() - const; ///< Coerces a value to a JavaScript boolean. - MaybeOrValue ToNumber() - const; ///< Coerces a value to a JavaScript number. - MaybeOrValue ToString() - const; ///< Coerces a value to a JavaScript string. - MaybeOrValue ToObject() - const; ///< Coerces a value to a JavaScript object. - - protected: - /// !cond INTERNAL - napi_env _env; - napi_value _value; - /// !endcond - }; - - /// A JavaScript boolean value. - class Boolean : public Value { - public: - static Boolean New(napi_env env, ///< Node-API environment - bool value ///< Boolean value - ); - - Boolean(); ///< Creates a new _empty_ Boolean instance. - Boolean(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + bool IsString() const; ///< Tests if a value is a JavaScript string. + bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. + bool IsArray() const; ///< Tests if a value is a JavaScript array. + bool IsArrayBuffer() + const; ///< Tests if a value is a JavaScript array buffer. + bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. + bool IsObject() const; ///< Tests if a value is a JavaScript object. + bool IsFunction() const; ///< Tests if a value is a JavaScript function. + bool IsPromise() const; ///< Tests if a value is a JavaScript promise. + bool IsDataView() const; ///< Tests if a value is a JavaScript data view. + bool IsBuffer() const; ///< Tests if a value is a Node buffer. + bool IsExternal() const; ///< Tests if a value is a pointer to external data. + + /// Casts to another type of `Napi::Value`, when the actual type is known or + /// assumed. + /// + /// This conversion does NOT coerce the type. Calling any methods + /// inappropriate for the actual value type will throw `Napi::Error`. + template + T As() const; + + MaybeOrValue ToBoolean() + const; ///< Coerces a value to a JavaScript boolean. + MaybeOrValue ToNumber() + const; ///< Coerces a value to a JavaScript number. + MaybeOrValue ToString() + const; ///< Coerces a value to a JavaScript string. + MaybeOrValue ToObject() + const; ///< Coerces a value to a JavaScript object. + + protected: + /// !cond INTERNAL + napi_env _env; + napi_value _value; + /// !endcond +}; + +/// A JavaScript boolean value. +class Boolean : public Value { + public: + static Boolean New(napi_env env, ///< Node-API environment + bool value ///< Boolean value + ); + + Boolean(); ///< Creates a new _empty_ Boolean instance. + Boolean(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - operator bool() const; ///< Converts a Boolean value to a boolean primitive. - bool Value() const; ///< Converts a Boolean value to a boolean primitive. - }; + operator bool() const; ///< Converts a Boolean value to a boolean primitive. + bool Value() const; ///< Converts a Boolean value to a boolean primitive. +}; - /// A JavaScript number value. - class Number : public Value { - public: - static Number New(napi_env env, ///< Node-API environment - double value ///< Number value - ); +/// A JavaScript number value. +class Number : public Value { + public: + static Number New(napi_env env, ///< Node-API environment + double value ///< Number value + ); - Number(); ///< Creates a new _empty_ Number instance. - Number(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + Number(); ///< Creates a new _empty_ Number instance. + Number(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - operator int32_t() - const; ///< Converts a Number value to a 32-bit signed integer value. - operator uint32_t() - const; ///< Converts a Number value to a 32-bit unsigned integer value. - operator int64_t() - const; ///< Converts a Number value to a 64-bit signed integer value. - operator float() - const; ///< Converts a Number value to a 32-bit floating-point value. - operator double() - const; ///< Converts a Number value to a 64-bit floating-point value. - - int32_t Int32Value() - const; ///< Converts a Number value to a 32-bit signed integer value. - uint32_t Uint32Value() - const; ///< Converts a Number value to a 32-bit unsigned integer value. - int64_t Int64Value() - const; ///< Converts a Number value to a 64-bit signed integer value. - float FloatValue() - const; ///< Converts a Number value to a 32-bit floating-point value. - double DoubleValue() - const; ///< Converts a Number value to a 64-bit floating-point value. - }; + operator int32_t() + const; ///< Converts a Number value to a 32-bit signed integer value. + operator uint32_t() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + operator int64_t() + const; ///< Converts a Number value to a 64-bit signed integer value. + operator float() + const; ///< Converts a Number value to a 32-bit floating-point value. + operator double() + const; ///< Converts a Number value to a 64-bit floating-point value. + + int32_t Int32Value() + const; ///< Converts a Number value to a 32-bit signed integer value. + uint32_t Uint32Value() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + int64_t Int64Value() + const; ///< Converts a Number value to a 64-bit signed integer value. + float FloatValue() + const; ///< Converts a Number value to a 32-bit floating-point value. + double DoubleValue() + const; ///< Converts a Number value to a 64-bit floating-point value. +}; #if NAPI_VERSION > 5 - /// A JavaScript bigint value. - class BigInt : public Value { - public: - static BigInt New(napi_env env, ///< Node-API environment - int64_t value ///< Number value - ); - static BigInt New(napi_env env, ///< Node-API environment - uint64_t value ///< Number value - ); - - /// Creates a new BigInt object using a specified sign bit and a - /// specified list of digits/words. - /// The resulting number is calculated as: - /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) - static BigInt New(napi_env env, ///< Node-API environment - int sign_bit, ///< Sign bit. 1 if negative. - size_t word_count, ///< Number of words in array - const uint64_t* words ///< Array of words - ); - - BigInt(); ///< Creates a new _empty_ BigInt instance. - BigInt(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. +/// A JavaScript bigint value. +class BigInt : public Value { + public: + static BigInt New(napi_env env, ///< Node-API environment + int64_t value ///< Number value + ); + static BigInt New(napi_env env, ///< Node-API environment + uint64_t value ///< Number value + ); + + /// Creates a new BigInt object using a specified sign bit and a + /// specified list of digits/words. + /// The resulting number is calculated as: + /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) + static BigInt New(napi_env env, ///< Node-API environment + int sign_bit, ///< Sign bit. 1 if negative. + size_t word_count, ///< Number of words in array + const uint64_t* words ///< Array of words + ); + + BigInt(); ///< Creates a new _empty_ BigInt instance. + BigInt(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - int64_t Int64Value(bool* lossless) - const; ///< Converts a BigInt value to a 64-bit signed integer value. - uint64_t Uint64Value(bool* lossless) - const; ///< Converts a BigInt value to a 64-bit unsigned integer value. - - size_t WordCount() const; ///< The number of 64-bit words needed to store - ///< the result of ToWords(). - - /// Writes the contents of this BigInt to a specified memory location. - /// `sign_bit` must be provided and will be set to 1 if this BigInt is - /// negative. - /// `*word_count` has to be initialized to the length of the `words` array. - /// Upon return, it will be set to the actual number of words that would - /// be needed to store this BigInt (i.e. the return value of `WordCount()`). - void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); - }; + int64_t Int64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit signed integer value. + uint64_t Uint64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit unsigned integer value. + + size_t WordCount() const; ///< The number of 64-bit words needed to store + ///< the result of ToWords(). + + /// Writes the contents of this BigInt to a specified memory location. + /// `sign_bit` must be provided and will be set to 1 if this BigInt is + /// negative. + /// `*word_count` has to be initialized to the length of the `words` array. + /// Upon return, it will be set to the actual number of words that would + /// be needed to store this BigInt (i.e. the return value of `WordCount()`). + void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); +}; #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) - /// A JavaScript date value. - class Date : public Value { - public: - /// Creates a new Date value from a double primitive. - static Date New(napi_env env, ///< Node-API environment - double value ///< Number value - ); - - Date(); ///< Creates a new _empty_ Date instance. - Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. - operator double() const; ///< Converts a Date value to double primitive - - double ValueOf() const; ///< Converts a Date value to a double primitive. - }; - #endif +/// A JavaScript date value. +class Date : public Value { + public: + /// Creates a new Date value from a double primitive. + static Date New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + Date(); ///< Creates a new _empty_ Date instance. + Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. + operator double() const; ///< Converts a Date value to double primitive + + double ValueOf() const; ///< Converts a Date value to a double primitive. +}; +#endif + +/// A JavaScript string or symbol value (that can be used as a property name). +class Name : public Value { + public: + Name(); ///< Creates a new _empty_ Name instance. + Name(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; + +/// A JavaScript string value. +class String : public Name { + public: + /// Creates a new String value from a UTF-8 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::string& value ///< UTF-8 encoded C++ string + ); + + /// Creates a new String value from a UTF-16 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::u16string& value ///< UTF-16 encoded C++ string + ); + + /// Creates a new String value from a UTF-8 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char* value ///< UTF-8 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-16 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value ///< UTF-16 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-8 encoded C string with specified + /// length. + static String New(napi_env env, ///< Node-API environment + const char* value, ///< UTF-8 encoded C string (not + ///< necessarily null-terminated) + size_t length ///< length of the string in bytes + ); + + /// Creates a new String value from a UTF-16 encoded C string with specified + /// length. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value, ///< UTF-16 encoded C string (not necessarily + ///< null-terminated) + size_t length ///< Length of the string in 2-byte code units + ); + + /// Creates a new String based on the original object's type. + /// + /// `value` may be any of: + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + template + static String From(napi_env env, const T& value); - /// A JavaScript string or symbol value (that can be used as a property name). - class Name : public Value { - public: - Name(); ///< Creates a new _empty_ Name instance. - Name(napi_env env, + String(); ///< Creates a new _empty_ String instance. + String(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. - }; - /// A JavaScript string value. - class String : public Name { - public: - /// Creates a new String value from a UTF-8 encoded C++ string. - static String New(napi_env env, ///< Node-API environment - const std::string& value ///< UTF-8 encoded C++ string - ); - - /// Creates a new String value from a UTF-16 encoded C++ string. - static String New(napi_env env, ///< Node-API environment - const std::u16string& value ///< UTF-16 encoded C++ string - ); - - /// Creates a new String value from a UTF-8 encoded C string. - static String New( - napi_env env, ///< Node-API environment - const char* value ///< UTF-8 encoded null-terminated C string - ); - - /// Creates a new String value from a UTF-16 encoded C string. - static String New( - napi_env env, ///< Node-API environment - const char16_t* value ///< UTF-16 encoded null-terminated C string - ); - - /// Creates a new String value from a UTF-8 encoded C string with specified - /// length. - static String New(napi_env env, ///< Node-API environment - const char* value, ///< UTF-8 encoded C string (not - ///< necessarily null-terminated) - size_t length ///< length of the string in bytes - ); - - /// Creates a new String value from a UTF-16 encoded C string with specified - /// length. - static String New( - napi_env env, ///< Node-API environment - const char16_t* value, ///< UTF-16 encoded C string (not necessarily - ///< null-terminated) - size_t length ///< Length of the string in 2-byte code units - ); - - /// Creates a new String based on the original object's type. - /// - /// `value` may be any of: - /// - const char* (encoded using UTF-8, null-terminated) - /// - const char16_t* (encoded using UTF-16-LE, null-terminated) - /// - std::string (encoded using UTF-8) - /// - std::u16string - template - static String From(napi_env env, const T& value); - - String(); ///< Creates a new _empty_ String instance. - String(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + operator std::string() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + operator std::u16string() + const; ///< Converts a String value to a UTF-16 encoded C++ string. + std::string Utf8Value() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + std::u16string Utf16Value() + const; ///< Converts a String value to a UTF-16 encoded C++ string. +}; + +/// A JavaScript symbol value. +class Symbol : public Name { + public: + /// Creates a new Symbol value with an optional description. + static Symbol New( + napi_env env, ///< Node-API environment + const char* description = + nullptr ///< Optional UTF-8 encoded null-terminated C string + /// describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + const std::string& + description ///< UTF-8 encoded C++ string describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New(napi_env env, ///< Node-API environment + String description ///< String value describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + napi_value description ///< String value describing the symbol + ); + + /// Get a public Symbol (e.g. Symbol.iterator). + static MaybeOrValue WellKnown(napi_env, const std::string& name); + + // Create a symbol in the global registry, UTF-8 Encoded cpp string + static MaybeOrValue For(napi_env env, const std::string& description); + + // Create a symbol in the global registry, C style string (null terminated) + static MaybeOrValue For(napi_env env, const char* description); + + // Create a symbol in the global registry, String value describing the symbol + static MaybeOrValue For(napi_env env, String description); + + // Create a symbol in the global registry, napi_value describing the symbol + static MaybeOrValue For(napi_env env, napi_value description); + + Symbol(); ///< Creates a new _empty_ Symbol instance. + Symbol(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; - operator std::string() - const; ///< Converts a String value to a UTF-8 encoded C++ string. - operator std::u16string() - const; ///< Converts a String value to a UTF-16 encoded C++ string. - std::string Utf8Value() - const; ///< Converts a String value to a UTF-8 encoded C++ string. - std::u16string Utf16Value() - const; ///< Converts a String value to a UTF-16 encoded C++ string. - }; +/// A JavaScript object value. +class Object : public Value { + public: + /// Enables property and element assignments using indexing syntax. + /// + /// This is a convenient helper to get and set object properties. As + /// getting and setting object properties may throw with JavaScript + /// exceptions, it is notable that these operations may fail. + /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort + /// on JavaScript exceptions. + /// + /// Example: + /// + /// Napi::Value propertyValue = object1['A']; + /// object2['A'] = propertyValue; + /// Napi::Value elementValue = array[0]; + /// array[1] = elementValue; + template + class PropertyLValue { + public: + /// Converts an L-value to a value. + operator Value() const; - /// A JavaScript symbol value. - class Symbol : public Name { - public: - /// Creates a new Symbol value with an optional description. - static Symbol New( - napi_env env, ///< Node-API environment - const char* description = - nullptr ///< Optional UTF-8 encoded null-terminated C string - /// describing the symbol - ); - - /// Creates a new Symbol value with a description. - static Symbol New( - napi_env env, ///< Node-API environment - const std::string& - description ///< UTF-8 encoded C++ string describing the symbol - ); - - /// Creates a new Symbol value with a description. - static Symbol New(napi_env env, ///< Node-API environment - String description ///< String value describing the symbol - ); - - /// Creates a new Symbol value with a description. - static Symbol New( - napi_env env, ///< Node-API environment - napi_value description ///< String value describing the symbol - ); - - /// Get a public Symbol (e.g. Symbol.iterator). - static MaybeOrValue WellKnown(napi_env, const std::string& name); - - // Create a symbol in the global registry, UTF-8 Encoded cpp string - static MaybeOrValue For(napi_env env, - const std::string& description); - - // Create a symbol in the global registry, C style string (null terminated) - static MaybeOrValue For(napi_env env, const char* description); - - // Create a symbol in the global registry, String value describing the symbol - static MaybeOrValue For(napi_env env, String description); - - // Create a symbol in the global registry, napi_value describing the symbol - static MaybeOrValue For(napi_env env, napi_value description); - - Symbol(); ///< Creates a new _empty_ Symbol instance. - Symbol(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. - }; + /// Assigns a value to the property. The type of value can be + /// anything supported by `Object::Set`. + template + PropertyLValue& operator=(ValueType value); - /// A JavaScript object value. - class Object : public Value { - public: - /// Enables property and element assignments using indexing syntax. - /// - /// This is a convenient helper to get and set object properties. As - /// getting and setting object properties may throw with JavaScript - /// exceptions, it is notable that these operations may fail. - /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort - /// on JavaScript exceptions. - /// - /// Example: - /// - /// Napi::Value propertyValue = object1['A']; - /// object2['A'] = propertyValue; - /// Napi::Value elementValue = array[0]; - /// array[1] = elementValue; - template - class PropertyLValue { - public: - /// Converts an L-value to a value. - operator Value() const; - - /// Assigns a value to the property. The type of value can be - /// anything supported by `Object::Set`. - template - PropertyLValue& operator =(ValueType value); - - private: - PropertyLValue() = delete; - PropertyLValue(Object object, Key key); - napi_env _env; - napi_value _object; - Key _key; - - friend class Napi::Object; - }; - - /// Creates a new Object value. - static Object New(napi_env env ///< Node-API environment - ); - - Object(); ///< Creates a new _empty_ Object instance. - Object(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + private: + PropertyLValue() = delete; + PropertyLValue(Object object, Key key); + napi_env _env; + napi_value _object; + Key _key; - /// Gets or sets a named property. - PropertyLValue operator[]( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ); - - /// Gets or sets a named property. - PropertyLValue operator[]( - const std::string& utf8name ///< UTF-8 encoded property name - ); - - /// Gets or sets an indexed property or array element. - PropertyLValue operator[]( - uint32_t index /// Property / element index - ); - - /// Gets or sets an indexed property or array element. - PropertyLValue operator[](Value index /// Property / element index - ) const; - - /// Gets a named property. - MaybeOrValue operator[]( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Gets a named property. - MaybeOrValue operator[]( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Gets an indexed property or array element. - MaybeOrValue operator[](uint32_t index ///< Property / element index - ) const; - - /// Checks whether a property is present. - MaybeOrValue Has(napi_value key ///< Property key primitive - ) const; - - /// Checks whether a property is present. - MaybeOrValue Has(Value key ///< Property key - ) const; - - /// Checks whether a named property is present. - MaybeOrValue Has( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Checks whether a named property is present. - MaybeOrValue Has( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Checks whether a own property is present. - MaybeOrValue HasOwnProperty( - napi_value key ///< Property key primitive - ) const; - - /// Checks whether a own property is present. - MaybeOrValue HasOwnProperty(Value key ///< Property key - ) const; - - /// Checks whether a own property is present. - MaybeOrValue HasOwnProperty( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Checks whether a own property is present. - MaybeOrValue HasOwnProperty( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Gets a property. - MaybeOrValue Get(napi_value key ///< Property key primitive - ) const; - - /// Gets a property. - MaybeOrValue Get(Value key ///< Property key - ) const; - - /// Gets a named property. - MaybeOrValue Get( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Gets a named property. - MaybeOrValue Get( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Sets a property. - template - MaybeOrValue Set(napi_value key, ///< Property key primitive - const ValueType& value ///< Property value primitive - ) const; + friend class Napi::Object; + }; - /// Sets a property. - template - MaybeOrValue Set(Value key, ///< Property key - const ValueType& value ///< Property value - ) const; + /// Creates a new Object value. + static Object New(napi_env env ///< Node-API environment + ); - /// Sets a named property. - template - MaybeOrValue Set( - const char* utf8name, ///< UTF-8 encoded null-terminated property name - const ValueType& value) const; + Object(); ///< Creates a new _empty_ Object instance. + Object(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - /// Sets a named property. - template - MaybeOrValue Set( - const std::string& utf8name, ///< UTF-8 encoded property name - const ValueType& value ///< Property value primitive - ) const; - - /// Delete property. - MaybeOrValue Delete(napi_value key ///< Property key primitive - ) const; - - /// Delete property. - MaybeOrValue Delete(Value key ///< Property key - ) const; - - /// Delete property. - MaybeOrValue Delete( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Delete property. - MaybeOrValue Delete( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Checks whether an indexed property is present. - MaybeOrValue Has(uint32_t index ///< Property / element index - ) const; - - /// Gets an indexed property or array element. - MaybeOrValue Get(uint32_t index ///< Property / element index - ) const; - - /// Sets an indexed property or array element. - template - MaybeOrValue Set(uint32_t index, ///< Property / element index - const ValueType& value ///< Property value primitive - ) const; - - /// Deletes an indexed property or array element. - MaybeOrValue Delete(uint32_t index ///< Property / element index - ) const; - - /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and - /// Proxy.[[GetOwnProperty]] calling into JavaScript. See: - /// - - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys - /// - - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p - MaybeOrValue GetPropertyNames() const; ///< Get all property names - - /// Defines a property on the object. - /// - /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling - /// into JavaScript. See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc - MaybeOrValue DefineProperty( - const PropertyDescriptor& - property ///< Descriptor for the property to be defined - ) const; - - /// Defines properties on the object. - /// - /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling - /// into JavaScript. See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc - MaybeOrValue DefineProperties( - const std::initializer_list& properties - ///< List of descriptors for the properties to be defined - ) const; - - /// Defines properties on the object. - /// - /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling - /// into JavaScript. See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc - MaybeOrValue DefineProperties( - const std::vector& properties - ///< Vector of descriptors for the properties to be defined - ) const; - - /// Checks if an object is an instance created by a constructor function. - /// - /// This is equivalent to the JavaScript `instanceof` operator. - /// - /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into - /// JavaScript. - /// See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof - MaybeOrValue InstanceOf( - const Function& constructor ///< Constructor function - ) const; - - template - inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; - - template - inline void AddFinalizer(Finalizer finalizeCallback, - T* data, - Hint* finalizeHint) const; + /// Gets or sets a named property. + PropertyLValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Gets or sets a named property. + PropertyLValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[]( + uint32_t index /// Property / element index + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[](Value index /// Property / element index + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue operator[](uint32_t index ///< Property / element index + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(Value key ///< Property key + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(Value key ///< Property key + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets a property. + MaybeOrValue Get(napi_value key ///< Property key primitive + ) const; + + /// Gets a property. + MaybeOrValue Get(Value key ///< Property key + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Sets a property. + template + MaybeOrValue Set(napi_value key, ///< Property key primitive + const ValueType& value ///< Property value primitive + ) const; + + /// Sets a property. + template + MaybeOrValue Set(Value key, ///< Property key + const ValueType& value ///< Property value + ) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const char* utf8name, ///< UTF-8 encoded null-terminated property name + const ValueType& value) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const std::string& utf8name, ///< UTF-8 encoded property name + const ValueType& value ///< Property value primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(napi_value key ///< Property key primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(Value key ///< Property key + ) const; + + /// Delete property. + MaybeOrValue Delete( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Delete property. + MaybeOrValue Delete( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether an indexed property is present. + MaybeOrValue Has(uint32_t index ///< Property / element index + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue Get(uint32_t index ///< Property / element index + ) const; + + /// Sets an indexed property or array element. + template + MaybeOrValue Set(uint32_t index, ///< Property / element index + const ValueType& value ///< Property value primitive + ) const; + + /// Deletes an indexed property or array element. + MaybeOrValue Delete(uint32_t index ///< Property / element index + ) const; + + /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and + /// Proxy.[[GetOwnProperty]] calling into JavaScript. See: + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p + MaybeOrValue GetPropertyNames() const; ///< Get all property names + + /// Defines a property on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperty( + const PropertyDescriptor& + property ///< Descriptor for the property to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::initializer_list& properties + ///< List of descriptors for the properties to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::vector& properties + ///< Vector of descriptors for the properties to be defined + ) const; + + /// Checks if an object is an instance created by a constructor function. + /// + /// This is equivalent to the JavaScript `instanceof` operator. + /// + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue InstanceOf( + const Function& constructor ///< Constructor function + ) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) const; #ifdef NAPI_CPP_EXCEPTIONS - class const_iterator; + class const_iterator; - inline const_iterator begin() const; + inline const_iterator begin() const; - inline const_iterator end() const; + inline const_iterator end() const; - class iterator; + class iterator; - inline iterator begin(); + inline iterator begin(); - inline iterator end(); + inline iterator end(); #endif // NAPI_CPP_EXCEPTIONS #if NAPI_VERSION >= 8 - /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into - /// JavaScript. - /// See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof - MaybeOrValue Freeze() const; - /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into - /// JavaScript. - /// See - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof - MaybeOrValue Seal() const; + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Freeze() const; + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Seal() const; #endif // NAPI_VERSION >= 8 - }; +}; - template - class External : public Value { - public: - static External New(napi_env env, T* data); - - // Finalizer must implement `void operator()(Env env, T* data)`. - template - static External New(napi_env env, - T* data, - Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. - template - static External New(napi_env env, - T* data, - Finalizer finalizeCallback, - Hint* finalizeHint); - - External(); - External(napi_env env, napi_value value); - - T* Data() const; - }; +template +class External : public Value { + public: + static External New(napi_env env, T* data); - class Array : public Object { - public: - static Array New(napi_env env); - static Array New(napi_env env, size_t length); + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static External New(napi_env env, T* data, Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint); - Array(); - Array(napi_env env, napi_value value); + External(); + External(napi_env env, napi_value value); - uint32_t Length() const; - }; + T* Data() const; +}; + +class Array : public Object { + public: + static Array New(napi_env env); + static Array New(napi_env env, size_t length); + + Array(); + Array(napi_env env, napi_value value); + + uint32_t Length() const; +}; #ifdef NAPI_CPP_EXCEPTIONS - class Object::const_iterator { - private: - enum class Type { BEGIN, END }; +class Object::const_iterator { + private: + enum class Type { BEGIN, END }; - inline const_iterator(const Object* object, const Type type); + inline const_iterator(const Object* object, const Type type); - public: - inline const_iterator& operator++(); + public: + inline const_iterator& operator++(); - inline bool operator==(const const_iterator& other) const; + inline bool operator==(const const_iterator& other) const; - inline bool operator!=(const const_iterator& other) const; + inline bool operator!=(const const_iterator& other) const; - inline const std::pair> operator*() - const; + inline const std::pair> operator*() + const; - private: - const Napi::Object* _object; - Array _keys; - uint32_t _index; + private: + const Napi::Object* _object; + Array _keys; + uint32_t _index; - friend class Object; - }; + friend class Object; +}; - class Object::iterator { - private: - enum class Type { BEGIN, END }; +class Object::iterator { + private: + enum class Type { BEGIN, END }; - inline iterator(Object* object, const Type type); + inline iterator(Object* object, const Type type); - public: - inline iterator& operator++(); + public: + inline iterator& operator++(); - inline bool operator==(const iterator& other) const; + inline bool operator==(const iterator& other) const; - inline bool operator!=(const iterator& other) const; + inline bool operator!=(const iterator& other) const; - inline std::pair> operator*(); + inline std::pair> operator*(); - private: - Napi::Object* _object; - Array _keys; - uint32_t _index; + private: + Napi::Object* _object; + Array _keys; + uint32_t _index; - friend class Object; - }; + friend class Object; +}; #endif // NAPI_CPP_EXCEPTIONS - /// A JavaScript array buffer value. - class ArrayBuffer : public Object { - public: - /// Creates a new ArrayBuffer instance over a new automatically-allocated buffer. - static ArrayBuffer New( - napi_env env, ///< Node-API environment - size_t byteLength ///< Length of the buffer to be allocated, in bytes - ); - - /// Creates a new ArrayBuffer instance, using an external buffer with - /// specified byte length. - static ArrayBuffer New( - napi_env env, ///< Node-API environment - void* externalData, ///< Pointer to the external buffer to be used by - ///< the array - size_t byteLength ///< Length of the external buffer to be used by the - ///< array, in bytes - ); - - /// Creates a new ArrayBuffer instance, using an external buffer with - /// specified byte length. - template - static ArrayBuffer New( - napi_env env, ///< Node-API environment - void* externalData, ///< Pointer to the external buffer to be used by - ///< the array - size_t byteLength, ///< Length of the external buffer to be used by the - ///< array, - /// in bytes - Finalizer finalizeCallback ///< Function to be called when the array +/// A JavaScript array buffer value. +class ArrayBuffer : public Object { + public: + /// Creates a new ArrayBuffer instance over a new automatically-allocated + /// buffer. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + size_t byteLength ///< Length of the buffer to be allocated, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength ///< Length of the external buffer to be used by the + ///< array, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env env, + /// void* externalData)` + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback, ///< Function to be called when the array ///< buffer is destroyed; - /// must implement `void operator()(Env env, - /// void* externalData)` - ); - - /// Creates a new ArrayBuffer instance, using an external buffer with - /// specified byte length. - template - static ArrayBuffer New( - napi_env env, ///< Node-API environment - void* externalData, ///< Pointer to the external buffer to be used by - ///< the array - size_t byteLength, ///< Length of the external buffer to be used by the - ///< array, - /// in bytes - Finalizer finalizeCallback, ///< Function to be called when the array - ///< buffer is destroyed; - /// must implement `void operator()(Env - /// env, void* externalData, Hint* hint)` - Hint* finalizeHint ///< Hint (second parameter) to be passed to the - ///< finalize callback - ); - - ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. - ArrayBuffer(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. + /// must implement `void operator()(Env + /// env, void* externalData, Hint* hint)` + Hint* finalizeHint ///< Hint (second parameter) to be passed to the + ///< finalize callback + ); + + ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. + ArrayBuffer(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - void* Data(); ///< Gets a pointer to the data buffer. - size_t ByteLength(); ///< Gets the length of the array buffer in bytes. + void* Data(); ///< Gets a pointer to the data buffer. + size_t ByteLength(); ///< Gets the length of the array buffer in bytes. #if NAPI_VERSION >= 7 - bool IsDetached() const; - void Detach(); + bool IsDetached() const; + void Detach(); #endif // NAPI_VERSION >= 7 - }; +}; - /// A JavaScript typed-array value with unknown array type. - /// - /// For type-specific operations, cast to a `TypedArrayOf` instance using the `As()` - /// method: - /// - /// Napi::TypedArray array = ... - /// if (t.TypedArrayType() == napi_int32_array) { - /// Napi::Int32Array int32Array = t.As(); - /// } - class TypedArray : public Object { - public: - TypedArray(); ///< Creates a new _empty_ TypedArray instance. - TypedArray(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. +/// A JavaScript typed-array value with unknown array type. +/// +/// For type-specific operations, cast to a `TypedArrayOf` instance using the +/// `As()` method: +/// +/// Napi::TypedArray array = ... +/// if (t.TypedArrayType() == napi_int32_array) { +/// Napi::Int32Array int32Array = t.As(); +/// } +class TypedArray : public Object { + public: + TypedArray(); ///< Creates a new _empty_ TypedArray instance. + TypedArray(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + napi_typedarray_type TypedArrayType() + const; ///< Gets the type of this typed-array. + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. - uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array. - size_t ElementLength() const; ///< Gets the number of elements in the array. - size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. - size_t ByteLength() const; ///< Gets the length of the array in bytes. + uint8_t ElementSize() + const; ///< Gets the size in bytes of one element in the array. + size_t ElementLength() const; ///< Gets the number of elements in the array. + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. - protected: - /// !cond INTERNAL - napi_typedarray_type _type; - size_t _length; + protected: + /// !cond INTERNAL + napi_typedarray_type _type; + size_t _length; - TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length); + TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length); - static const napi_typedarray_type unknown_array_type = static_cast(-1); + static const napi_typedarray_type unknown_array_type = + static_cast(-1); - template - static + template + static #if defined(NAPI_HAS_CONSTEXPR) - constexpr + constexpr #endif - napi_typedarray_type TypedArrayTypeForPrimitiveType() { - return std::is_same::value ? napi_int8_array - : std::is_same::value ? napi_uint8_array - : std::is_same::value ? napi_int16_array - : std::is_same::value ? napi_uint16_array - : std::is_same::value ? napi_int32_array - : std::is_same::value ? napi_uint32_array - : std::is_same::value ? napi_float32_array - : std::is_same::value ? napi_float64_array + napi_typedarray_type + TypedArrayTypeForPrimitiveType() { + return std::is_same::value ? napi_int8_array + : std::is_same::value ? napi_uint8_array + : std::is_same::value ? napi_int16_array + : std::is_same::value ? napi_uint16_array + : std::is_same::value ? napi_int32_array + : std::is_same::value ? napi_uint32_array + : std::is_same::value ? napi_float32_array + : std::is_same::value ? napi_float64_array #if NAPI_VERSION > 5 - : std::is_same::value ? napi_bigint64_array - : std::is_same::value ? napi_biguint64_array + : std::is_same::value ? napi_bigint64_array + : std::is_same::value ? napi_biguint64_array #endif // NAPI_VERSION > 5 - : unknown_array_type; - } - /// !endcond - }; + : unknown_array_type; + } + /// !endcond +}; - /// A JavaScript typed-array value with known array type. +/// A JavaScript typed-array value with known array type. +/// +/// Note while it is possible to create and access Uint8 "clamped" arrays using +/// this class, the _clamping_ behavior is only applied in JavaScript. +template +class TypedArrayOf : public TypedArray { + public: + /// Creates a new TypedArray instance over a new automatically-allocated array + /// buffer. /// - /// Note while it is possible to create and access Uint8 "clamped" arrays using this class, - /// the _clamping_ behavior is only applied in JavaScript. - template - class TypedArrayOf : public TypedArray { - public: - /// Creates a new TypedArray instance over a new automatically-allocated array buffer. - /// - /// The array type parameter can normally be omitted (because it is inferred from the template - /// parameter T), except when creating a "clamped" array: - /// - /// Uint8Array::New(env, length, napi_uint8_clamped_array) - static TypedArrayOf New( - napi_env env, ///< Node-API environment - size_t elementLength, ///< Length of the created array, as a number of - ///< elements + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements #if defined(NAPI_HAS_CONSTEXPR) - napi_typedarray_type type = - TypedArray::TypedArrayTypeForPrimitiveType() + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() #else - napi_typedarray_type type + napi_typedarray_type type #endif - ///< Type of array, if different from the default array type for the - ///< template parameter T. - ); - - /// Creates a new TypedArray instance over a provided array buffer. - /// - /// The array type parameter can normally be omitted (because it is inferred from the template - /// parameter T), except when creating a "clamped" array: - /// - /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) - static TypedArrayOf New( - napi_env env, ///< Node-API environment - size_t elementLength, ///< Length of the created array, as a number of - ///< elements - Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use - size_t bufferOffset, ///< Offset into the array buffer where the - ///< typed-array starts + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + /// Creates a new TypedArray instance over a provided array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts #if defined(NAPI_HAS_CONSTEXPR) - napi_typedarray_type type = - TypedArray::TypedArrayTypeForPrimitiveType() + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() #else - napi_typedarray_type type + napi_typedarray_type type #endif - ///< Type of array, if different from the default array type for the - ///< template parameter T. - ); - - TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. - TypedArrayOf(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. - - T& operator [](size_t index); ///< Gets or sets an element in the array. - const T& operator [](size_t index) const; ///< Gets an element in the array. - - /// Gets a pointer to the array's backing buffer. - /// - /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the - /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. - T* Data(); - - /// Gets a pointer to the array's backing buffer. - /// - /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the - /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. - const T* Data() const; - - private: - T* _data; - - TypedArrayOf(napi_env env, - napi_value value, - napi_typedarray_type type, - size_t length, - T* data); - }; - - /// The DataView provides a low-level interface for reading/writing multiple - /// number types in an ArrayBuffer irrespective of the platform's endianness. - class DataView : public Object { - public: - static DataView New(napi_env env, - Napi::ArrayBuffer arrayBuffer); - static DataView New(napi_env env, - Napi::ArrayBuffer arrayBuffer, - size_t byteOffset); - static DataView New(napi_env env, - Napi::ArrayBuffer arrayBuffer, - size_t byteOffset, - size_t byteLength); - - DataView(); ///< Creates a new _empty_ DataView instance. - DataView(napi_env env, - napi_value value); ///< Wraps a Node-API value primitive. - - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. - size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. - size_t ByteLength() const; ///< Gets the length of the array in bytes. - - void* Data() const; - - float GetFloat32(size_t byteOffset) const; - double GetFloat64(size_t byteOffset) const; - int8_t GetInt8(size_t byteOffset) const; - int16_t GetInt16(size_t byteOffset) const; - int32_t GetInt32(size_t byteOffset) const; - uint8_t GetUint8(size_t byteOffset) const; - uint16_t GetUint16(size_t byteOffset) const; - uint32_t GetUint32(size_t byteOffset) const; - - void SetFloat32(size_t byteOffset, float value) const; - void SetFloat64(size_t byteOffset, double value) const; - void SetInt8(size_t byteOffset, int8_t value) const; - void SetInt16(size_t byteOffset, int16_t value) const; - void SetInt32(size_t byteOffset, int32_t value) const; - void SetUint8(size_t byteOffset, uint8_t value) const; - void SetUint16(size_t byteOffset, uint16_t value) const; - void SetUint32(size_t byteOffset, uint32_t value) const; - - private: - template - T ReadData(size_t byteOffset) const; - - template - void WriteData(size_t byteOffset, T value) const; - - void* _data; - size_t _length; - }; - - class Function : public Object { - public: - using VoidCallback = void (*)(const CallbackInfo& info); - using Callback = Value (*)(const CallbackInfo& info); - - template - static Function New(napi_env env, - const char* utf8name = nullptr, - void* data = nullptr); - - template - static Function New(napi_env env, - const char* utf8name = nullptr, - void* data = nullptr); - - template - static Function New(napi_env env, - const std::string& utf8name, - void* data = nullptr); - - template - static Function New(napi_env env, - const std::string& utf8name, - void* data = nullptr); - - /// Callable must implement operator() accepting a const CallbackInfo& - /// and return either void or Value. - template - static Function New(napi_env env, - Callable cb, - const char* utf8name = nullptr, - void* data = nullptr); - /// Callable must implement operator() accepting a const CallbackInfo& - /// and return either void or Value. - template - static Function New(napi_env env, - Callable cb, - const std::string& utf8name, - void* data = nullptr); - - Function(); - Function(napi_env env, napi_value value); - - MaybeOrValue operator()( - const std::initializer_list& args) const; - - MaybeOrValue Call( - const std::initializer_list& args) const; - MaybeOrValue Call(const std::vector& args) const; - MaybeOrValue Call(const std::vector& args) const; - MaybeOrValue Call(size_t argc, const napi_value* args) const; - MaybeOrValue Call( - napi_value recv, const std::initializer_list& args) const; - MaybeOrValue Call(napi_value recv, - const std::vector& args) const; - MaybeOrValue Call(napi_value recv, - const std::vector& args) const; - MaybeOrValue Call(napi_value recv, - size_t argc, - const napi_value* args) const; - - MaybeOrValue MakeCallback( - napi_value recv, - const std::initializer_list& args, - napi_async_context context = nullptr) const; - MaybeOrValue MakeCallback(napi_value recv, - const std::vector& args, - napi_async_context context = nullptr) const; - MaybeOrValue MakeCallback(napi_value recv, - size_t argc, - const napi_value* args, - napi_async_context context = nullptr) const; - - MaybeOrValue New( - const std::initializer_list& args) const; - MaybeOrValue New(const std::vector& args) const; - MaybeOrValue New(size_t argc, const napi_value* args) const; - }; - - class Promise : public Object { - public: - class Deferred { - public: - static Deferred New(napi_env env); - Deferred(napi_env env); + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); - Napi::Promise Promise() const; - Napi::Env Env() const; + TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. + TypedArrayOf(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. - void Resolve(napi_value value) const; - void Reject(napi_value value) const; + T& operator[](size_t index); ///< Gets or sets an element in the array. + const T& operator[](size_t index) const; ///< Gets an element in the array. - private: - napi_env _env; - napi_deferred _deferred; - napi_value _promise; - }; + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + T* Data(); - Promise(napi_env env, napi_value value); - }; + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + const T* Data() const; + + private: + T* _data; + + TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data); +}; + +/// The DataView provides a low-level interface for reading/writing multiple +/// number types in an ArrayBuffer irrespective of the platform's endianness. +class DataView : public Object { + public: + static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); + + DataView(); ///< Creates a new _empty_ DataView instance. + DataView(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + void* Data() const; + + float GetFloat32(size_t byteOffset) const; + double GetFloat64(size_t byteOffset) const; + int8_t GetInt8(size_t byteOffset) const; + int16_t GetInt16(size_t byteOffset) const; + int32_t GetInt32(size_t byteOffset) const; + uint8_t GetUint8(size_t byteOffset) const; + uint16_t GetUint16(size_t byteOffset) const; + uint32_t GetUint32(size_t byteOffset) const; + + void SetFloat32(size_t byteOffset, float value) const; + void SetFloat64(size_t byteOffset, double value) const; + void SetInt8(size_t byteOffset, int8_t value) const; + void SetInt16(size_t byteOffset, int16_t value) const; + void SetInt32(size_t byteOffset, int32_t value) const; + void SetUint8(size_t byteOffset, uint8_t value) const; + void SetUint16(size_t byteOffset, uint16_t value) const; + void SetUint32(size_t byteOffset, uint32_t value) const; + + private: template - class Buffer : public Uint8Array { - public: - static Buffer New(napi_env env, size_t length); - static Buffer New(napi_env env, T* data, size_t length); - - // Finalizer must implement `void operator()(Env env, T* data)`. - template - static Buffer New(napi_env env, T* data, - size_t length, - Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. - template - static Buffer New(napi_env env, T* data, - size_t length, - Finalizer finalizeCallback, - Hint* finalizeHint); - - static Buffer Copy(napi_env env, const T* data, size_t length); - - Buffer(); - Buffer(napi_env env, napi_value value); - size_t Length() const; - T* Data() const; - - private: - mutable size_t _length; - mutable T* _data; - - Buffer(napi_env env, napi_value value, size_t length, T* data); - void EnsureInfo() const; - }; + T ReadData(size_t byteOffset) const; - /// Holds a counted reference to a value; initially a weak reference unless otherwise specified, - /// may be changed to/from a strong reference by adjusting the refcount. - /// - /// The referenced value is not immediately destroyed when the reference count is zero; it is - /// merely then eligible for garbage-collection if there are no other references to the value. template - class Reference { - public: - static Reference New(const T& value, uint32_t initialRefcount = 0); - - Reference(); - Reference(napi_env env, napi_ref ref); - ~Reference(); + void WriteData(size_t byteOffset, T value) const; + + void* _data; + size_t _length; +}; + +class Function : public Object { + public: + using VoidCallback = void (*)(const CallbackInfo& info); + using Callback = Value (*)(const CallbackInfo& info); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const char* utf8name = nullptr, + void* data = nullptr); + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data = nullptr); + + Function(); + Function(napi_env env, napi_value value); + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call(const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(size_t argc, const napi_value* args) const; + MaybeOrValue Call(napi_value recv, + const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; - // A reference can be moved but cannot be copied. - Reference(Reference&& other); - Reference& operator =(Reference&& other); - NAPI_DISALLOW_ASSIGN(Reference) + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; + MaybeOrValue New(size_t argc, const napi_value* args) const; +}; - operator napi_ref() const; - bool operator ==(const Reference &other) const; - bool operator !=(const Reference &other) const; +class Promise : public Object { + public: + class Deferred { + public: + static Deferred New(napi_env env); + Deferred(napi_env env); + Napi::Promise Promise() const; Napi::Env Env() const; - bool IsEmpty() const; - - // Note when getting the value of a Reference it is usually correct to do so - // within a HandleScope so that the value handle gets cleaned up efficiently. - T Value() const; - uint32_t Ref() const; - uint32_t Unref() const; - void Reset(); - void Reset(const T& value, uint32_t refcount = 0); + void Resolve(napi_value value) const; + void Reject(napi_value value) const; - // Call this on a reference that is declared as static data, to prevent its - // destructor from running at program shutdown time, which would attempt to - // reset the reference when the environment is no longer valid. Avoid using - // this if at all possible. If you do need to use static data, MAKE SURE to - // warn your users that your addon is NOT threadsafe. - void SuppressDestruct(); - - protected: - Reference(const Reference&); - - /// !cond INTERNAL + private: napi_env _env; - napi_ref _ref; - /// !endcond - - private: - bool _suppressDestruct; + napi_deferred _deferred; + napi_value _promise; }; - class ObjectReference: public Reference { - public: - ObjectReference(); - ObjectReference(napi_env env, napi_ref ref); - - // A reference can be moved but cannot be copied. - ObjectReference(Reference&& other); - ObjectReference& operator =(Reference&& other); - ObjectReference(ObjectReference&& other); - ObjectReference& operator =(ObjectReference&& other); - NAPI_DISALLOW_ASSIGN(ObjectReference) - - MaybeOrValue Get(const char* utf8name) const; - MaybeOrValue Get(const std::string& utf8name) const; - MaybeOrValue Set(const char* utf8name, napi_value value) const; - MaybeOrValue Set(const char* utf8name, Napi::Value value) const; - MaybeOrValue Set(const char* utf8name, const char* utf8value) const; - MaybeOrValue Set(const char* utf8name, bool boolValue) const; - MaybeOrValue Set(const char* utf8name, double numberValue) const; - MaybeOrValue Set(const std::string& utf8name, napi_value value) const; - MaybeOrValue Set(const std::string& utf8name, - Napi::Value value) const; - MaybeOrValue Set(const std::string& utf8name, - std::string& utf8value) const; - MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; - MaybeOrValue Set(const std::string& utf8name, - double numberValue) const; - - MaybeOrValue Get(uint32_t index) const; - MaybeOrValue Set(uint32_t index, const napi_value value) const; - MaybeOrValue Set(uint32_t index, const Napi::Value value) const; - MaybeOrValue Set(uint32_t index, const char* utf8value) const; - MaybeOrValue Set(uint32_t index, const std::string& utf8value) const; - MaybeOrValue Set(uint32_t index, bool boolValue) const; - MaybeOrValue Set(uint32_t index, double numberValue) const; - - protected: - ObjectReference(const ObjectReference&); - }; - - class FunctionReference: public Reference { - public: - FunctionReference(); - FunctionReference(napi_env env, napi_ref ref); - - // A reference can be moved but cannot be copied. - FunctionReference(Reference&& other); - FunctionReference& operator =(Reference&& other); - FunctionReference(FunctionReference&& other); - FunctionReference& operator =(FunctionReference&& other); - NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) - - MaybeOrValue operator()( - const std::initializer_list& args) const; - - MaybeOrValue Call( - const std::initializer_list& args) const; - MaybeOrValue Call(const std::vector& args) const; - MaybeOrValue Call( - napi_value recv, const std::initializer_list& args) const; - MaybeOrValue Call(napi_value recv, - const std::vector& args) const; - MaybeOrValue Call(napi_value recv, - size_t argc, - const napi_value* args) const; - - MaybeOrValue MakeCallback( - napi_value recv, - const std::initializer_list& args, - napi_async_context context = nullptr) const; - MaybeOrValue MakeCallback( - napi_value recv, - const std::vector& args, - napi_async_context context = nullptr) const; - MaybeOrValue MakeCallback( - napi_value recv, - size_t argc, - const napi_value* args, - napi_async_context context = nullptr) const; - - MaybeOrValue New( - const std::initializer_list& args) const; - MaybeOrValue New(const std::vector& args) const; - }; - - // Shortcuts to creating a new reference with inferred type and refcount = 0. - template Reference Weak(T value); - ObjectReference Weak(Object value); - FunctionReference Weak(Function value); - - // Shortcuts to creating a new reference with inferred type and refcount = 1. - template Reference Persistent(T value); - ObjectReference Persistent(Object value); - FunctionReference Persistent(Function value); - - /// A persistent reference to a JavaScript error object. Use of this class - /// depends somewhat on whether C++ exceptions are enabled at compile time. - /// - /// ### Handling Errors With C++ Exceptions - /// - /// If C++ exceptions are enabled, then the `Error` class extends - /// `std::exception` and enables integrated error-handling for C++ exceptions - /// and JavaScript exceptions. - /// - /// If a Node-API call fails without executing any JavaScript code (for - /// example due to an invalid argument), then the Node-API wrapper - /// automatically converts and throws the error as a C++ exception of type - /// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API - /// throws a JavaScript exception, then the Node-API wrapper automatically - /// converts and throws it as a C++ exception of type `Napi::Error`. - /// - /// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ - /// callback, then the Node-API wrapper automatically converts and throws it - /// as a JavaScript exception. Therefore, catching a C++ exception of type - /// `Napi::Error` prevents a JavaScript exception from being thrown. - /// - /// #### Example 1A - Throwing a C++ exception: - /// - /// Napi::Env env = ... - /// throw Napi::Error::New(env, "Example exception"); - /// - /// Following C++ statements will not be executed. The exception will bubble - /// up as a C++ exception of type `Napi::Error`, until it is either caught - /// while still in C++, or else automatically propataged as a JavaScript - /// exception when the callback returns to JavaScript. - /// - /// #### Example 2A - Propagating a Node-API C++ exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As(); - /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); - /// - /// Following C++ statements will not be executed. The exception will bubble - /// up as a C++ exception of type `Napi::Error`, until it is either caught - /// while still in C++, or else automatically propagated as a JavaScript - /// exception when the callback returns to JavaScript. - /// - /// #### Example 3A - Handling a Node-API C++ exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As(); - /// Napi::Value result; - /// try { - /// result = jsFunctionThatThrows({ arg1, arg2 }); - /// } catch (const Napi::Error& e) { - /// cerr << "Caught JavaScript exception: " + e.what(); - /// } - /// - /// Since the exception was caught here, it will not be propagated as a - /// JavaScript exception. - /// - /// ### Handling Errors Without C++ Exceptions - /// - /// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) - /// then this class does not extend `std::exception`, and APIs in the `Napi` - /// namespace do not throw C++ exceptions when they fail. Instead, they raise - /// _pending_ JavaScript exceptions and return _empty_ `Value`s. Calling code - /// should check `Value::IsEmpty()` before attempting to use a returned value, - /// and may use methods on the `Env` class to check for, get, and clear a - /// pending JavaScript exception. If the pending exception is not cleared, it - /// will be thrown when the native callback returns to JavaScript. - /// - /// #### Example 1B - Throwing a JS exception - /// - /// Napi::Env env = ... - /// Napi::Error::New(env, "Example - /// exception").ThrowAsJavaScriptException(); return; - /// - /// After throwing a JS exception, the code should generally return - /// immediately from the native callback, after performing any necessary - /// cleanup. - /// - /// #### Example 2B - Propagating a Node-API JS exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As(); - /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); - /// if (result.IsEmpty()) return; - /// - /// An empty value result from a Node-API call indicates an error occurred, - /// and a JavaScript exception is pending. To let the exception propagate, the - /// code should generally return immediately from the native callback, after - /// performing any necessary cleanup. - /// - /// #### Example 3B - Handling a Node-API JS exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As(); - /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); - /// if (result.IsEmpty()) { - /// Napi::Error e = env.GetAndClearPendingException(); - /// cerr << "Caught JavaScript exception: " + e.Message(); - /// } - /// - /// Since the exception was cleared here, it will not be propagated as a - /// JavaScript exception after the native callback returns. - class Error : public ObjectReference + Promise(napi_env env, napi_value value); +}; + +template +class Buffer : public Uint8Array { + public: + static Buffer New(napi_env env, size_t length); + static Buffer New(napi_env env, T* data, size_t length); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static Buffer Copy(napi_env env, const T* data, size_t length); + + Buffer(); + Buffer(napi_env env, napi_value value); + size_t Length() const; + T* Data() const; + + private: + mutable size_t _length; + mutable T* _data; + + Buffer(napi_env env, napi_value value, size_t length, T* data); + void EnsureInfo() const; +}; + +/// Holds a counted reference to a value; initially a weak reference unless +/// otherwise specified, may be changed to/from a strong reference by adjusting +/// the refcount. +/// +/// The referenced value is not immediately destroyed when the reference count +/// is zero; it is merely then eligible for garbage-collection if there are no +/// other references to the value. +template +class Reference { + public: + static Reference New(const T& value, uint32_t initialRefcount = 0); + + Reference(); + Reference(napi_env env, napi_ref ref); + ~Reference(); + + // A reference can be moved but cannot be copied. + Reference(Reference&& other); + Reference& operator=(Reference&& other); + NAPI_DISALLOW_ASSIGN(Reference) + + operator napi_ref() const; + bool operator==(const Reference& other) const; + bool operator!=(const Reference& other) const; + + Napi::Env Env() const; + bool IsEmpty() const; + + // Note when getting the value of a Reference it is usually correct to do so + // within a HandleScope so that the value handle gets cleaned up efficiently. + T Value() const; + + uint32_t Ref() const; + uint32_t Unref() const; + void Reset(); + void Reset(const T& value, uint32_t refcount = 0); + + // Call this on a reference that is declared as static data, to prevent its + // destructor from running at program shutdown time, which would attempt to + // reset the reference when the environment is no longer valid. Avoid using + // this if at all possible. If you do need to use static data, MAKE SURE to + // warn your users that your addon is NOT threadsafe. + void SuppressDestruct(); + + protected: + Reference(const Reference&); + + /// !cond INTERNAL + napi_env _env; + napi_ref _ref; + /// !endcond + + private: + bool _suppressDestruct; +}; + +class ObjectReference : public Reference { + public: + ObjectReference(); + ObjectReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + ObjectReference(Reference&& other); + ObjectReference& operator=(Reference&& other); + ObjectReference(ObjectReference&& other); + ObjectReference& operator=(ObjectReference&& other); + NAPI_DISALLOW_ASSIGN(ObjectReference) + + MaybeOrValue Get(const char* utf8name) const; + MaybeOrValue Get(const std::string& utf8name) const; + MaybeOrValue Set(const char* utf8name, napi_value value) const; + MaybeOrValue Set(const char* utf8name, Napi::Value value) const; + MaybeOrValue Set(const char* utf8name, const char* utf8value) const; + MaybeOrValue Set(const char* utf8name, bool boolValue) const; + MaybeOrValue Set(const char* utf8name, double numberValue) const; + MaybeOrValue Set(const std::string& utf8name, napi_value value) const; + MaybeOrValue Set(const std::string& utf8name, Napi::Value value) const; + MaybeOrValue Set(const std::string& utf8name, + std::string& utf8value) const; + MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; + MaybeOrValue Set(const std::string& utf8name, double numberValue) const; + + MaybeOrValue Get(uint32_t index) const; + MaybeOrValue Set(uint32_t index, const napi_value value) const; + MaybeOrValue Set(uint32_t index, const Napi::Value value) const; + MaybeOrValue Set(uint32_t index, const char* utf8value) const; + MaybeOrValue Set(uint32_t index, const std::string& utf8value) const; + MaybeOrValue Set(uint32_t index, bool boolValue) const; + MaybeOrValue Set(uint32_t index, double numberValue) const; + + protected: + ObjectReference(const ObjectReference&); +}; + +class FunctionReference : public Reference { + public: + FunctionReference(); + FunctionReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + FunctionReference(Reference&& other); + FunctionReference& operator=(Reference&& other); + FunctionReference(FunctionReference&& other); + FunctionReference& operator=(FunctionReference&& other); + NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call( + const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call( + napi_value recv, const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; +}; + +// Shortcuts to creating a new reference with inferred type and refcount = 0. +template +Reference Weak(T value); +ObjectReference Weak(Object value); +FunctionReference Weak(Function value); + +// Shortcuts to creating a new reference with inferred type and refcount = 1. +template +Reference Persistent(T value); +ObjectReference Persistent(Object value); +FunctionReference Persistent(Function value); + +/// A persistent reference to a JavaScript error object. Use of this class +/// depends somewhat on whether C++ exceptions are enabled at compile time. +/// +/// ### Handling Errors With C++ Exceptions +/// +/// If C++ exceptions are enabled, then the `Error` class extends +/// `std::exception` and enables integrated error-handling for C++ exceptions +/// and JavaScript exceptions. +/// +/// If a Node-API call fails without executing any JavaScript code (for +/// example due to an invalid argument), then the Node-API wrapper +/// automatically converts and throws the error as a C++ exception of type +/// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API +/// throws a JavaScript exception, then the Node-API wrapper automatically +/// converts and throws it as a C++ exception of type `Napi::Error`. +/// +/// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ +/// callback, then the Node-API wrapper automatically converts and throws it +/// as a JavaScript exception. Therefore, catching a C++ exception of type +/// `Napi::Error` prevents a JavaScript exception from being thrown. +/// +/// #### Example 1A - Throwing a C++ exception: +/// +/// Napi::Env env = ... +/// throw Napi::Error::New(env, "Example exception"); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propataged as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 2A - Propagating a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propagated as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 3A - Handling a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result; +/// try { +/// result = jsFunctionThatThrows({ arg1, arg2 }); +/// } catch (const Napi::Error& e) { +/// cerr << "Caught JavaScript exception: " + e.what(); +/// } +/// +/// Since the exception was caught here, it will not be propagated as a +/// JavaScript exception. +/// +/// ### Handling Errors Without C++ Exceptions +/// +/// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) +/// then this class does not extend `std::exception`, and APIs in the `Napi` +/// namespace do not throw C++ exceptions when they fail. Instead, they raise +/// _pending_ JavaScript exceptions and return _empty_ `Value`s. Calling code +/// should check `Value::IsEmpty()` before attempting to use a returned value, +/// and may use methods on the `Env` class to check for, get, and clear a +/// pending JavaScript exception. If the pending exception is not cleared, it +/// will be thrown when the native callback returns to JavaScript. +/// +/// #### Example 1B - Throwing a JS exception +/// +/// Napi::Env env = ... +/// Napi::Error::New(env, "Example +/// exception").ThrowAsJavaScriptException(); return; +/// +/// After throwing a JS exception, the code should generally return +/// immediately from the native callback, after performing any necessary +/// cleanup. +/// +/// #### Example 2B - Propagating a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) return; +/// +/// An empty value result from a Node-API call indicates an error occurred, +/// and a JavaScript exception is pending. To let the exception propagate, the +/// code should generally return immediately from the native callback, after +/// performing any necessary cleanup. +/// +/// #### Example 3B - Handling a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) { +/// Napi::Error e = env.GetAndClearPendingException(); +/// cerr << "Caught JavaScript exception: " + e.Message(); +/// } +/// +/// Since the exception was cleared here, it will not be propagated as a +/// JavaScript exception after the native callback returns. +class Error : public ObjectReference #ifdef NAPI_CPP_EXCEPTIONS - , public std::exception -#endif // NAPI_CPP_EXCEPTIONS - { - public: - static Error New(napi_env env); - static Error New(napi_env env, const char* message); - static Error New(napi_env env, const std::string& message); + , + public std::exception +#endif // NAPI_CPP_EXCEPTIONS +{ + public: + static Error New(napi_env env); + static Error New(napi_env env, const char* message); + static Error New(napi_env env, const std::string& message); - static NAPI_NO_RETURN void Fatal(const char* location, const char* message); + static NAPI_NO_RETURN void Fatal(const char* location, const char* message); - Error(); - Error(napi_env env, napi_value value); + Error(); + Error(napi_env env, napi_value value); - // An error can be moved or copied. - Error(Error&& other); - Error& operator =(Error&& other); - Error(const Error&); - Error& operator =(const Error&); + // An error can be moved or copied. + Error(Error&& other); + Error& operator=(Error&& other); + Error(const Error&); + Error& operator=(const Error&); - const std::string& Message() const NAPI_NOEXCEPT; - void ThrowAsJavaScriptException() const; + const std::string& Message() const NAPI_NOEXCEPT; + void ThrowAsJavaScriptException() const; - Object Value() const; + Object Value() const; #ifdef NAPI_CPP_EXCEPTIONS - const char* what() const NAPI_NOEXCEPT override; -#endif // NAPI_CPP_EXCEPTIONS - - protected: - /// !cond INTERNAL - using create_error_fn = napi_status (*)(napi_env envb, - napi_value code, - napi_value msg, - napi_value* result); - - template - static TError New(napi_env env, - const char* message, - size_t length, - create_error_fn create_error); - /// !endcond - - private: - static inline const char* ERROR_WRAP_VALUE() NAPI_NOEXCEPT; - mutable std::string _message; - }; - - class TypeError : public Error { - public: - static TypeError New(napi_env env, const char* message); - static TypeError New(napi_env env, const std::string& message); - - TypeError(); - TypeError(napi_env env, napi_value value); - }; - - class RangeError : public Error { - public: - static RangeError New(napi_env env, const char* message); - static RangeError New(napi_env env, const std::string& message); - - RangeError(); - RangeError(napi_env env, napi_value value); - }; - - class CallbackInfo { - public: - CallbackInfo(napi_env env, napi_callback_info info); - ~CallbackInfo(); - - // Disallow copying to prevent multiple free of _dynamicArgs - NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) - - Napi::Env Env() const; - Value NewTarget() const; - bool IsConstructCall() const; - size_t Length() const; - const Value operator [](size_t index) const; - Value This() const; - void* Data() const; - void SetData(void* data); - - private: - const size_t _staticArgCount = 6; - napi_env _env; - napi_callback_info _info; - napi_value _this; - size_t _argc; - napi_value* _argv; - napi_value _staticArgs[6]; - napi_value* _dynamicArgs; - void* _data; - }; + const char* what() const NAPI_NOEXCEPT override; +#endif // NAPI_CPP_EXCEPTIONS - class PropertyDescriptor { - public: - using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); - using SetterCallback = void (*)(const Napi::CallbackInfo& info); + protected: + /// !cond INTERNAL + using create_error_fn = napi_status (*)(napi_env envb, + napi_value code, + napi_value msg, + napi_value* result); + + template + static TError New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error); + /// !endcond + + private: + static inline const char* ERROR_WRAP_VALUE() NAPI_NOEXCEPT; + mutable std::string _message; +}; + +class TypeError : public Error { + public: + static TypeError New(napi_env env, const char* message); + static TypeError New(napi_env env, const std::string& message); + + TypeError(); + TypeError(napi_env env, napi_value value); +}; + +class RangeError : public Error { + public: + static RangeError New(napi_env env, const char* message); + static RangeError New(napi_env env, const std::string& message); + + RangeError(); + RangeError(napi_env env, napi_value value); +}; + +class CallbackInfo { + public: + CallbackInfo(napi_env env, napi_callback_info info); + ~CallbackInfo(); + + // Disallow copying to prevent multiple free of _dynamicArgs + NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) + + Napi::Env Env() const; + Value NewTarget() const; + bool IsConstructCall() const; + size_t Length() const; + const Value operator[](size_t index) const; + Value This() const; + void* Data() const; + void SetData(void* data); + + private: + const size_t _staticArgCount = 6; + napi_env _env; + napi_callback_info _info; + napi_value _this; + size_t _argc; + napi_value* _argv; + napi_value _staticArgs[6]; + napi_value* _dynamicArgs; + void* _data; +}; + +class PropertyDescriptor { + public: + using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); + using SetterCallback = void (*)(const Napi::CallbackInfo& info); #ifndef NODE_ADDON_API_DISABLE_DEPRECATED - template - static PropertyDescriptor Accessor(const char* utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(const std::string& utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(napi_value name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Name name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(const std::string& utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(napi_value name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(const char* utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(const std::string& utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(napi_value name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(Name name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED - - template - static PropertyDescriptor Accessor(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(const std::string& utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(Name name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(const std::string& utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(Name name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(Napi::Env env, - Napi::Object object, - const char* utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(Napi::Env env, - Napi::Object object, - const std::string& utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor Function(Napi::Env env, - Napi::Object object, - Name name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor Value(const char* utf8name, - napi_value value, - napi_property_attributes attributes = napi_default); - static PropertyDescriptor Value(const std::string& utf8name, - napi_value value, - napi_property_attributes attributes = napi_default); - static PropertyDescriptor Value(napi_value name, - napi_value value, - napi_property_attributes attributes = napi_default); - static PropertyDescriptor Value(Name name, - Napi::Value value, - napi_property_attributes attributes = napi_default); - - PropertyDescriptor(napi_property_descriptor desc); - - operator napi_property_descriptor&(); - operator const napi_property_descriptor&() const; - - private: - napi_property_descriptor _desc; - }; - - /// Property descriptor for use with `ObjectWrap::DefineClass()`. - /// - /// This is different from the standalone `PropertyDescriptor` because it is specific to each - /// `ObjectWrap` subclass. This prevents using descriptors from a different class when - /// defining a new class (preventing the callbacks from having incorrect `this` pointers). - template - class ClassPropertyDescriptor { - public: - ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} - - operator napi_property_descriptor&() { return _desc; } - operator const napi_property_descriptor&() const { return _desc; } - - private: - napi_property_descriptor _desc; - }; - - template - struct MethodCallbackData { - TCallback callback; - void* data; - }; - - template - struct AccessorCallbackData { - TGetterCallback getterCallback; - TSetterCallback setterCallback; - void* data; - }; - - template - class InstanceWrap { - public: - using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); - using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); - using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); - using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, - const Napi::Value& value); - - using PropertyDescriptor = ClassPropertyDescriptor; - - static PropertyDescriptor InstanceMethod(const char* utf8name, - InstanceVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceMethod(const char* utf8name, - InstanceMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceMethod(Symbol name, - InstanceVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceMethod(Symbol name, - InstanceMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceMethod(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceMethod(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceMethod(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceMethod(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceAccessor(const char* utf8name, - InstanceGetterCallback getter, - InstanceSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceAccessor(Symbol name, - InstanceGetterCallback getter, - InstanceSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceAccessor(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor InstanceAccessor(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor InstanceValue(const char* utf8name, - Napi::Value value, - napi_property_attributes attributes = napi_default); - static PropertyDescriptor InstanceValue(Symbol name, - Napi::Value value, - napi_property_attributes attributes = napi_default); - - protected: - static void AttachPropData(napi_env env, napi_value value, const napi_property_descriptor* prop); - - private: - using This = InstanceWrap; - - using InstanceVoidMethodCallbackData = - MethodCallbackData; - using InstanceMethodCallbackData = - MethodCallbackData; - using InstanceAccessorCallbackData = - AccessorCallbackData; - - static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value InstanceMethodCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value InstanceGetterCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value InstanceSetterCallbackWrapper(napi_env env, napi_callback_info info); - - template - static napi_value WrappedMethod(napi_env env, - napi_callback_info info) NAPI_NOEXCEPT; - - template struct SetterTag {}; - - template - static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { - return &This::WrappedMethod; - } - static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { - return nullptr; - } - }; + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + napi_value name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + napi_value name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + Name name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + PropertyDescriptor(napi_property_descriptor desc); + + operator napi_property_descriptor&(); + operator const napi_property_descriptor&() const; + + private: + napi_property_descriptor _desc; +}; + +/// Property descriptor for use with `ObjectWrap::DefineClass()`. +/// +/// This is different from the standalone `PropertyDescriptor` because it is +/// specific to each `ObjectWrap` subclass. This prevents using descriptors +/// from a different class when defining a new class (preventing the callbacks +/// from having incorrect `this` pointers). +template +class ClassPropertyDescriptor { + public: + ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} + + operator napi_property_descriptor&() { return _desc; } + operator const napi_property_descriptor&() const { return _desc; } + + private: + napi_property_descriptor _desc; +}; + +template +struct MethodCallbackData { + TCallback callback; + void* data; +}; + +template +struct AccessorCallbackData { + TGetterCallback getterCallback; + TSetterCallback setterCallback; + void* data; +}; + +template +class InstanceWrap { + public: + using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); + using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + protected: + static void AttachPropData(napi_env env, + napi_value value, + const napi_property_descriptor* prop); + + private: + using This = InstanceWrap; + + using InstanceVoidMethodCallbackData = + MethodCallbackData; + using InstanceMethodCallbackData = + MethodCallbackData; + using InstanceAccessorCallbackData = + AccessorCallbackData; + + static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceSetterCallbackWrapper(napi_env env, + napi_callback_info info); + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct SetterTag {}; + + template + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return nullptr; + } +}; - /// Base class to be extended by C++ classes exposed to JavaScript; each C++ class instance gets - /// "wrapped" by a JavaScript object that is managed by this class. - /// - /// At initialization time, the `DefineClass()` method must be used to - /// hook up the accessor and method callbacks. It takes a list of - /// property descriptors, which can be constructed via the various - /// static methods on the base class. - /// - /// #### Example: - /// - /// class Example: public Napi::ObjectWrap { - /// public: - /// static void Initialize(Napi::Env& env, Napi::Object& target) { - /// Napi::Function constructor = DefineClass(env, "Example", { - /// InstanceAccessor<&Example::GetSomething, &Example::SetSomething>("value"), - /// InstanceMethod<&Example::DoSomething>("doSomething"), - /// }); - /// target.Set("Example", constructor); - /// } - /// - /// Example(const Napi::CallbackInfo& info); // Constructor - /// Napi::Value GetSomething(const Napi::CallbackInfo& info); - /// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& value); - /// Napi::Value DoSomething(const Napi::CallbackInfo& info); - /// } - template - class ObjectWrap : public InstanceWrap, public Reference { - public: - ObjectWrap(const CallbackInfo& callbackInfo); - virtual ~ObjectWrap(); - - static T* Unwrap(Object wrapper); - - // Methods exposed to JavaScript must conform to one of these callback signatures. - using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); - using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); - using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); - using StaticSetterCallback = void (*)(const CallbackInfo& info, - const Napi::Value& value); - - using PropertyDescriptor = ClassPropertyDescriptor; - - static Function DefineClass(Napi::Env env, - const char* utf8name, - const std::initializer_list& properties, - void* data = nullptr); - static Function DefineClass(Napi::Env env, - const char* utf8name, - const std::vector& properties, - void* data = nullptr); - static PropertyDescriptor StaticMethod(const char* utf8name, - StaticVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticMethod(const char* utf8name, - StaticMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticMethod(Symbol name, - StaticVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticMethod(Symbol name, - StaticMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticMethod(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticMethod(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticMethod(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticMethod(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticAccessor(const char* utf8name, - StaticGetterCallback getter, - StaticSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticAccessor(Symbol name, - StaticGetterCallback getter, - StaticSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticAccessor(const char* utf8name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template - static PropertyDescriptor StaticAccessor(Symbol name, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - static PropertyDescriptor StaticValue(const char* utf8name, - Napi::Value value, - napi_property_attributes attributes = napi_default); - static PropertyDescriptor StaticValue(Symbol name, - Napi::Value value, - napi_property_attributes attributes = napi_default); - static Napi::Value OnCalledAsFunction( - const Napi::CallbackInfo& callbackInfo); - virtual void Finalize(Napi::Env env); - - private: - using This = ObjectWrap; - - static napi_value ConstructorCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value StaticVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value StaticMethodCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value StaticGetterCallbackWrapper(napi_env env, napi_callback_info info); - static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info); - static void FinalizeCallback(napi_env env, void* data, void* hint); - static Function DefineClass(Napi::Env env, - const char* utf8name, - const size_t props_count, - const napi_property_descriptor* props, - void* data = nullptr); - - using StaticVoidMethodCallbackData = - MethodCallbackData; - using StaticMethodCallbackData = - MethodCallbackData; - - using StaticAccessorCallbackData = - AccessorCallbackData; - - template - static napi_value WrappedMethod(napi_env env, - napi_callback_info info) NAPI_NOEXCEPT; - - template struct StaticSetterTag {}; - - template - static napi_callback WrapStaticSetter(StaticSetterTag) - NAPI_NOEXCEPT { - return &This::WrappedMethod; - } - static napi_callback WrapStaticSetter(StaticSetterTag) - NAPI_NOEXCEPT { - return nullptr; - } +/// Base class to be extended by C++ classes exposed to JavaScript; each C++ +/// class instance gets "wrapped" by a JavaScript object that is managed by this +/// class. +/// +/// At initialization time, the `DefineClass()` method must be used to +/// hook up the accessor and method callbacks. It takes a list of +/// property descriptors, which can be constructed via the various +/// static methods on the base class. +/// +/// #### Example: +/// +/// class Example: public Napi::ObjectWrap { +/// public: +/// static void Initialize(Napi::Env& env, Napi::Object& target) { +/// Napi::Function constructor = DefineClass(env, "Example", { +/// InstanceAccessor<&Example::GetSomething, +/// &Example::SetSomething>("value"), +/// InstanceMethod<&Example::DoSomething>("doSomething"), +/// }); +/// target.Set("Example", constructor); +/// } +/// +/// Example(const Napi::CallbackInfo& info); // Constructor +/// Napi::Value GetSomething(const Napi::CallbackInfo& info); +/// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& +/// value); Napi::Value DoSomething(const Napi::CallbackInfo& info); +/// } +template +class ObjectWrap : public InstanceWrap, public Reference { + public: + ObjectWrap(const CallbackInfo& callbackInfo); + virtual ~ObjectWrap(); + + static T* Unwrap(Object wrapper); + + // Methods exposed to JavaScript must conform to one of these callback + // signatures. + using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); + using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticSetterCallback = void (*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static Function DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list& properties, + void* data = nullptr); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::vector& properties, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor StaticValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& callbackInfo); + virtual void Finalize(Napi::Env env); + + private: + using This = ObjectWrap; + + static napi_value ConstructorCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticSetterCallbackWrapper(napi_env env, + napi_callback_info info); + static void FinalizeCallback(napi_env env, void* data, void* hint); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* props, + void* data = nullptr); + + using StaticVoidMethodCallbackData = + MethodCallbackData; + using StaticMethodCallbackData = MethodCallbackData; + + using StaticAccessorCallbackData = + AccessorCallbackData; + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct StaticSetterTag {}; + + template + static napi_callback WrapStaticSetter(StaticSetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapStaticSetter(StaticSetterTag) + NAPI_NOEXCEPT { + return nullptr; + } - bool _construction_failed = true; - }; + bool _construction_failed = true; +}; - class HandleScope { - public: - HandleScope(napi_env env, napi_handle_scope scope); - explicit HandleScope(Napi::Env env); - ~HandleScope(); +class HandleScope { + public: + HandleScope(napi_env env, napi_handle_scope scope); + explicit HandleScope(Napi::Env env); + ~HandleScope(); - // Disallow copying to prevent double close of napi_handle_scope - NAPI_DISALLOW_ASSIGN_COPY(HandleScope) + // Disallow copying to prevent double close of napi_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(HandleScope) - operator napi_handle_scope() const; + operator napi_handle_scope() const; - Napi::Env Env() const; + Napi::Env Env() const; - private: - napi_env _env; - napi_handle_scope _scope; - }; + private: + napi_env _env; + napi_handle_scope _scope; +}; - class EscapableHandleScope { - public: - EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); - explicit EscapableHandleScope(Napi::Env env); - ~EscapableHandleScope(); +class EscapableHandleScope { + public: + EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); + explicit EscapableHandleScope(Napi::Env env); + ~EscapableHandleScope(); - // Disallow copying to prevent double close of napi_escapable_handle_scope - NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) + // Disallow copying to prevent double close of napi_escapable_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) - operator napi_escapable_handle_scope() const; + operator napi_escapable_handle_scope() const; - Napi::Env Env() const; - Value Escape(napi_value escapee); + Napi::Env Env() const; + Value Escape(napi_value escapee); - private: - napi_env _env; - napi_escapable_handle_scope _scope; - }; + private: + napi_env _env; + napi_escapable_handle_scope _scope; +}; #if (NAPI_VERSION > 2) - class CallbackScope { - public: - CallbackScope(napi_env env, napi_callback_scope scope); - CallbackScope(napi_env env, napi_async_context context); - virtual ~CallbackScope(); +class CallbackScope { + public: + CallbackScope(napi_env env, napi_callback_scope scope); + CallbackScope(napi_env env, napi_async_context context); + virtual ~CallbackScope(); - // Disallow copying to prevent double close of napi_callback_scope - NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) + // Disallow copying to prevent double close of napi_callback_scope + NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) - operator napi_callback_scope() const; + operator napi_callback_scope() const; - Napi::Env Env() const; + Napi::Env Env() const; - private: - napi_env _env; - napi_callback_scope _scope; - }; + private: + napi_env _env; + napi_callback_scope _scope; +}; #endif - class AsyncContext { - public: - explicit AsyncContext(napi_env env, const char* resource_name); - explicit AsyncContext(napi_env env, const char* resource_name, const Object& resource); - virtual ~AsyncContext(); - - AsyncContext(AsyncContext&& other); - AsyncContext& operator =(AsyncContext&& other); - NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) - - operator napi_async_context() const; - - Napi::Env Env() const; - - private: - napi_env _env; - napi_async_context _context; - }; - - class AsyncWorker { - public: - virtual ~AsyncWorker(); - - // An async worker can be moved but cannot be copied. - AsyncWorker(AsyncWorker&& other); - AsyncWorker& operator =(AsyncWorker&& other); - NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) - - operator napi_async_work() const; - - Napi::Env Env() const; - - void Queue(); - void Cancel(); - void SuppressDestruct(); - - ObjectReference& Receiver(); - FunctionReference& Callback(); - - virtual void OnExecute(Napi::Env env); - virtual void OnWorkComplete(Napi::Env env, - napi_status status); - - protected: - explicit AsyncWorker(const Function& callback); - explicit AsyncWorker(const Function& callback, - const char* resource_name); - explicit AsyncWorker(const Function& callback, - const char* resource_name, - const Object& resource); - explicit AsyncWorker(const Object& receiver, - const Function& callback); - explicit AsyncWorker(const Object& receiver, - const Function& callback, - const char* resource_name); - explicit AsyncWorker(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource); - - explicit AsyncWorker(Napi::Env env); - explicit AsyncWorker(Napi::Env env, - const char* resource_name); - explicit AsyncWorker(Napi::Env env, - const char* resource_name, - const Object& resource); - - virtual void Execute() = 0; - virtual void OnOK(); - virtual void OnError(const Error& e); - virtual void Destroy(); - virtual std::vector GetResult(Napi::Env env); - - void SetError(const std::string& error); - - private: - static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); - static inline void OnAsyncWorkComplete(napi_env env, - napi_status status, - void* asyncworker); - - napi_env _env; - napi_async_work _work; - ObjectReference _receiver; - FunctionReference _callback; - std::string _error; - bool _suppress_destruct; - }; - - #if (NAPI_VERSION > 3 && !defined(__wasm32__)) - class ThreadSafeFunction { - public: - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback, - FinalizerDataType* data); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - Finalizer finalizeCallback, - FinalizerDataType* data); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback); - - // This API may only be called from the main thread. - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data); - - ThreadSafeFunction(); - ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); - - operator napi_threadsafe_function() const; - - // This API may be called from any thread. - napi_status BlockingCall() const; - - // This API may be called from any thread. - template - napi_status BlockingCall(Callback callback) const; - - // This API may be called from any thread. - template - napi_status BlockingCall(DataType* data, Callback callback) const; - - // This API may be called from any thread. - napi_status NonBlockingCall() const; - - // This API may be called from any thread. - template - napi_status NonBlockingCall(Callback callback) const; - - // This API may be called from any thread. - template - napi_status NonBlockingCall(DataType* data, Callback callback) const; - - // This API may only be called from the main thread. - void Ref(napi_env env) const; - - // This API may only be called from the main thread. - void Unref(napi_env env) const; - - // This API may be called from any thread. - napi_status Acquire() const; - - // This API may be called from any thread. - napi_status Release() const; - - // This API may be called from any thread. - napi_status Abort() const; - - struct ConvertibleContext - { - template - operator T*() { return static_cast(context); } - void* context; - }; - - // This API may be called from any thread. - ConvertibleContext GetContext() const; - - private: - using CallbackWrapper = std::function; - - template - static ThreadSafeFunction New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data, - napi_finalize wrapper); - - napi_status CallInternal(CallbackWrapper* callbackWrapper, - napi_threadsafe_function_call_mode mode) const; - - static void CallJS(napi_env env, - napi_value jsCallback, - void* context, - void* data); - - napi_threadsafe_function _tsfn; +class AsyncContext { + public: + explicit AsyncContext(napi_env env, const char* resource_name); + explicit AsyncContext(napi_env env, + const char* resource_name, + const Object& resource); + virtual ~AsyncContext(); + + AsyncContext(AsyncContext&& other); + AsyncContext& operator=(AsyncContext&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) + + operator napi_async_context() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_async_context _context; +}; + +class AsyncWorker { + public: + virtual ~AsyncWorker(); + + // An async worker can be moved but cannot be copied. + AsyncWorker(AsyncWorker&& other); + AsyncWorker& operator=(AsyncWorker&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) + + operator napi_async_work() const; + + Napi::Env Env() const; + + void Queue(); + void Cancel(); + void SuppressDestruct(); + + ObjectReference& Receiver(); + FunctionReference& Callback(); + + virtual void OnExecute(Napi::Env env); + virtual void OnWorkComplete(Napi::Env env, napi_status status); + + protected: + explicit AsyncWorker(const Function& callback); + explicit AsyncWorker(const Function& callback, const char* resource_name); + explicit AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncWorker(const Object& receiver, const Function& callback); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + + explicit AsyncWorker(Napi::Env env); + explicit AsyncWorker(Napi::Env env, const char* resource_name); + explicit AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource); + + virtual void Execute() = 0; + virtual void OnOK(); + virtual void OnError(const Error& e); + virtual void Destroy(); + virtual std::vector GetResult(Napi::Env env); + + void SetError(const std::string& error); + + private: + static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); + static inline void OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker); + + napi_env _env; + napi_async_work _work; + ObjectReference _receiver; + FunctionReference _callback; + std::string _error; + bool _suppress_destruct; +}; + +#if (NAPI_VERSION > 3 && !defined(__wasm32__)) +class ThreadSafeFunction { + public: + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + ThreadSafeFunction(); + ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall() const; + + // This API may be called from any thread. + template + napi_status BlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status BlockingCall(DataType* data, Callback callback) const; + + // This API may be called from any thread. + napi_status NonBlockingCall() const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(DataType* data, Callback callback) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + struct ConvertibleContext { + template + operator T*() { + return static_cast(context); + } + void* context; }; - // A TypedThreadSafeFunction by default has no context (nullptr) and can - // accept any type (void) to its CallJs. - template - class TypedThreadSafeFunction { - public: - // This API may only be called from the main thread. - // Helper function that returns nullptr if running Node-API 5+, otherwise a - // non-empty, no-op Function. This provides the ability to specify at - // compile-time a callback parameter to `New` that safely does no action - // when targeting _any_ Node-API version. + // This API may be called from any thread. + ConvertibleContext GetContext() const; + + private: + using CallbackWrapper = std::function; + + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + napi_status CallInternal(CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const; + + static void CallJS(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + napi_threadsafe_function _tsfn; +}; + +// A TypedThreadSafeFunction by default has no context (nullptr) and can +// accept any type (void) to its CallJs. +template +class TypedThreadSafeFunction { + public: + // This API may only be called from the main thread. + // Helper function that returns nullptr if running Node-API 5+, otherwise a + // non-empty, no-op Function. This provides the ability to specify at + // compile-time a callback parameter to `New` that safely does no action + // when targeting _any_ Node-API version. #if NAPI_VERSION > 4 - static std::nullptr_t EmptyFunctionFactory(Napi::Env env); + static std::nullptr_t EmptyFunctionFactory(Napi::Env env); #else - static Napi::Function EmptyFunctionFactory(Napi::Env env); + static Napi::Function EmptyFunctionFactory(Napi::Env env); #endif - static Napi::Function FunctionOrEmpty(Napi::Env env, - Napi::Function& callback); + static Napi::Function FunctionOrEmpty(Napi::Env env, + Napi::Function& callback); #if NAPI_VERSION > 4 - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [missing] Resource [missing] Finalizer [missing] - template - static TypedThreadSafeFunction New( - napi_env env, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [missing] Resource [passed] Finalizer [missing] - template - static TypedThreadSafeFunction New( - napi_env env, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [missing] Resource [missing] Finalizer [passed] - template - static TypedThreadSafeFunction New( - napi_env env, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [missing] Resource [passed] Finalizer [passed] - template - static TypedThreadSafeFunction New( - napi_env env, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data = nullptr); + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); #endif - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [passed] Resource [missing] Finalizer [missing] - template - static TypedThreadSafeFunction New( - napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [passed] Resource [passed] Finalizer [missing] - template - static TypedThreadSafeFunction New( - napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [passed] Resource [missing] Finalizer [passed] - template - static TypedThreadSafeFunction New( - napi_env env, - const Function& callback, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data = nullptr); - - // This API may only be called from the main thread. - // Creates a new threadsafe function with: - // Callback [passed] Resource [passed] Finalizer [passed] - template - static TypedThreadSafeFunction New( - napi_env env, - CallbackType callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data = nullptr); - - TypedThreadSafeFunction(); - TypedThreadSafeFunction(napi_threadsafe_function tsFunctionValue); - - operator napi_threadsafe_function() const; - - // This API may be called from any thread. - napi_status BlockingCall(DataType* data = nullptr) const; - - // This API may be called from any thread. - napi_status NonBlockingCall(DataType* data = nullptr) const; - - // This API may only be called from the main thread. - void Ref(napi_env env) const; - - // This API may only be called from the main thread. - void Unref(napi_env env) const; - - // This API may be called from any thread. - napi_status Acquire() const; - - // This API may be called from any thread. - napi_status Release() const; - - // This API may be called from any thread. - napi_status Abort() const; - - // This API may be called from any thread. - ContextType* GetContext() const; + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + TypedThreadSafeFunction(); + TypedThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall(DataType* data = nullptr) const; + + // This API may be called from any thread. + napi_status NonBlockingCall(DataType* data = nullptr) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + // This API may be called from any thread. + ContextType* GetContext() const; + + private: + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + static void CallJsInternal(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + protected: + napi_threadsafe_function _tsfn; +}; +template +class AsyncProgressWorkerBase : public AsyncWorker { + public: + virtual void OnWorkProgress(DataType* data) = 0; + class ThreadSafeData { + public: + ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) + : _asyncprogressworker(asyncprogressworker), _data(data) {} + + AsyncProgressWorkerBase* asyncprogressworker() { + return _asyncprogressworker; + }; + DataType* data() { return _data; }; private: - template - static TypedThreadSafeFunction New( - napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data, - napi_finalize wrapper); - - static void CallJsInternal(napi_env env, - napi_value jsCallback, - void* context, - void* data); - - protected: - napi_threadsafe_function _tsfn; + AsyncProgressWorkerBase* _asyncprogressworker; + DataType* _data; }; - template - class AsyncProgressWorkerBase : public AsyncWorker { - public: - virtual void OnWorkProgress(DataType* data) = 0; - class ThreadSafeData { - public: - ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) - : _asyncprogressworker(asyncprogressworker), _data(data) {} - - AsyncProgressWorkerBase* asyncprogressworker() { return _asyncprogressworker; }; - DataType* data() { return _data; }; - - private: - AsyncProgressWorkerBase* _asyncprogressworker; - DataType* _data; - }; - void OnWorkComplete(Napi::Env env, napi_status status) override; - protected: - explicit AsyncProgressWorkerBase(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource, - size_t queue_size = 1); - virtual ~AsyncProgressWorkerBase(); - -// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. -// Refs: https://github.com/nodejs/node/pull/27791 + void OnWorkComplete(Napi::Env env, napi_status status) override; + + protected: + explicit AsyncProgressWorkerBase(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); + virtual ~AsyncProgressWorkerBase(); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 #if NAPI_VERSION > 4 - explicit AsyncProgressWorkerBase(Napi::Env env, - const char* resource_name, - const Object& resource, - size_t queue_size = 1); + explicit AsyncProgressWorkerBase(Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); #endif - static inline void OnAsyncWorkProgress(Napi::Env env, - Napi::Function jsCallback, - void* data); + static inline void OnAsyncWorkProgress(Napi::Env env, + Napi::Function jsCallback, + void* data); - napi_status NonBlockingCall(DataType* data); + napi_status NonBlockingCall(DataType* data); - private: - ThreadSafeFunction _tsfn; - bool _work_completed = false; - napi_status _complete_status; - static inline void OnThreadSafeFunctionFinalize(Napi::Env env, void* data, AsyncProgressWorkerBase* context); - }; + private: + ThreadSafeFunction _tsfn; + bool _work_completed = false; + napi_status _complete_status; + static inline void OnThreadSafeFunctionFinalize( + Napi::Env env, void* data, AsyncProgressWorkerBase* context); +}; - template - class AsyncProgressWorker : public AsyncProgressWorkerBase { - public: - virtual ~AsyncProgressWorker(); - - class ExecutionProgress { - friend class AsyncProgressWorker; - public: - void Signal() const; - void Send(const T* data, size_t count) const; - private: - explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} - AsyncProgressWorker* const _worker; - }; - - void OnWorkProgress(void*) override; - - protected: - explicit AsyncProgressWorker(const Function& callback); - explicit AsyncProgressWorker(const Function& callback, - const char* resource_name); - explicit AsyncProgressWorker(const Function& callback, - const char* resource_name, - const Object& resource); - explicit AsyncProgressWorker(const Object& receiver, - const Function& callback); - explicit AsyncProgressWorker(const Object& receiver, - const Function& callback, - const char* resource_name); - explicit AsyncProgressWorker(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource); - -// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. -// Refs: https://github.com/nodejs/node/pull/27791 -#if NAPI_VERSION > 4 - explicit AsyncProgressWorker(Napi::Env env); - explicit AsyncProgressWorker(Napi::Env env, - const char* resource_name); - explicit AsyncProgressWorker(Napi::Env env, - const char* resource_name, - const Object& resource); -#endif - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void OnProgress(const T* data, size_t count) = 0; +template +class AsyncProgressWorker : public AsyncProgressWorkerBase { + public: + virtual ~AsyncProgressWorker(); - private: - void Execute() override; - void Signal() const; - void SendProgress_(const T* data, size_t count); + class ExecutionProgress { + friend class AsyncProgressWorker; - std::mutex _mutex; - T* _asyncdata; - size_t _asyncsize; + public: + void Signal() const; + void Send(const T* data, size_t count) const; + + private: + explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} + AsyncProgressWorker* const _worker; }; - template - class AsyncProgressQueueWorker : public AsyncProgressWorkerBase> { - public: - virtual ~AsyncProgressQueueWorker() {}; - - class ExecutionProgress { - friend class AsyncProgressQueueWorker; - public: - void Signal() const; - void Send(const T* data, size_t count) const; - private: - explicit ExecutionProgress(AsyncProgressQueueWorker* worker) : _worker(worker) {} - AsyncProgressQueueWorker* const _worker; - }; - - void OnWorkComplete(Napi::Env env, napi_status status) override; - void OnWorkProgress(std::pair*) override; - - protected: - explicit AsyncProgressQueueWorker(const Function& callback); - explicit AsyncProgressQueueWorker(const Function& callback, - const char* resource_name); - explicit AsyncProgressQueueWorker(const Function& callback, - const char* resource_name, - const Object& resource); - explicit AsyncProgressQueueWorker(const Object& receiver, - const Function& callback); - explicit AsyncProgressQueueWorker(const Object& receiver, - const Function& callback, - const char* resource_name); - explicit AsyncProgressQueueWorker(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource); - -// Optional callback of Napi::ThreadSafeFunction only available after NAPI_VERSION 4. -// Refs: https://github.com/nodejs/node/pull/27791 + void OnWorkProgress(void*) override; + + protected: + explicit AsyncProgressWorker(const Function& callback); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 #if NAPI_VERSION > 4 - explicit AsyncProgressQueueWorker(Napi::Env env); - explicit AsyncProgressQueueWorker(Napi::Env env, - const char* resource_name); - explicit AsyncProgressQueueWorker(Napi::Env env, - const char* resource_name, - const Object& resource); + explicit AsyncProgressWorker(Napi::Env env); + explicit AsyncProgressWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource); #endif - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void OnProgress(const T* data, size_t count) = 0; + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; - private: - void Execute() override; - void Signal() const; - void SendProgress_(const T* data, size_t count); - }; - #endif // NAPI_VERSION > 3 && !defined(__wasm32__) + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); - // Memory management. - class MemoryManagement { - public: - static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); - }; + std::mutex _mutex; + T* _asyncdata; + size_t _asyncsize; +}; - // Version management - class VersionManagement { - public: - static uint32_t GetNapiVersion(Env env); - static const napi_node_version* GetNodeVersion(Env env); - }; +template +class AsyncProgressQueueWorker + : public AsyncProgressWorkerBase> { + public: + virtual ~AsyncProgressQueueWorker(){}; -#if NAPI_VERSION > 5 - template - class Addon : public InstanceWrap { - public: - static inline Object Init(Env env, Object exports); - static T* Unwrap(Object wrapper); + class ExecutionProgress { + friend class AsyncProgressQueueWorker; - protected: - using AddonProp = ClassPropertyDescriptor; - void DefineAddon(Object exports, - const std::initializer_list& props); - Napi::Object DefineProperties(Object object, - const std::initializer_list& props); + public: + void Signal() const; + void Send(const T* data, size_t count) const; private: - Object entry_point_; + explicit ExecutionProgress(AsyncProgressQueueWorker* worker) + : _worker(worker) {} + AsyncProgressQueueWorker* const _worker; }; + + void OnWorkComplete(Napi::Env env, napi_status status) override; + void OnWorkProgress(std::pair*) override; + + protected: + explicit AsyncProgressQueueWorker(const Function& callback); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressQueueWorker(Napi::Env env); + explicit AsyncProgressQueueWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); +}; +#endif // NAPI_VERSION > 3 && !defined(__wasm32__) + +// Memory management. +class MemoryManagement { + public: + static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); +}; + +// Version management +class VersionManagement { + public: + static uint32_t GetNapiVersion(Env env); + static const napi_node_version* GetNodeVersion(Env env); +}; + +#if NAPI_VERSION > 5 +template +class Addon : public InstanceWrap { + public: + static inline Object Init(Env env, Object exports); + static T* Unwrap(Object wrapper); + + protected: + using AddonProp = ClassPropertyDescriptor; + void DefineAddon(Object exports, + const std::initializer_list& props); + Napi::Object DefineProperties(Object object, + const std::initializer_list& props); + + private: + Object entry_point_; +}; #endif // NAPI_VERSION > 5 #ifdef NAPI_CPP_CUSTOM_NAMESPACE - } // namespace NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE #endif -} // namespace Napi +} // namespace Napi // Inline implementations of all the above class methods are included here. #include "napi-inl.h" -#endif // SRC_NAPI_H_ +#endif // SRC_NAPI_H_ diff --git a/test/addon.cc b/test/addon.cc index 9652f9aa4..6940edb6f 100644 --- a/test/addon.cc +++ b/test/addon.cc @@ -7,12 +7,14 @@ namespace { class TestAddon : public Napi::Addon { public: inline TestAddon(Napi::Env env, Napi::Object exports) { - DefineAddon(exports, { - InstanceMethod("increment", &TestAddon::Increment), - InstanceValue("subObject", DefineProperties(Napi::Object::New(env), { - InstanceMethod("decrement", &TestAddon::Decrement) - })) - }); + DefineAddon( + exports, + {InstanceMethod("increment", &TestAddon::Increment), + InstanceValue( + "subObject", + DefineProperties( + Napi::Object::New(env), + {InstanceMethod("decrement", &TestAddon::Decrement)}))}); } private: diff --git a/test/addon_build/tpl/addon.cc b/test/addon_build/tpl/addon.cc index 1a86799c4..32b000d79 100644 --- a/test/addon_build/tpl/addon.cc +++ b/test/addon_build/tpl/addon.cc @@ -3,7 +3,8 @@ Napi::Value Echo(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() != 1) { - Napi::TypeError::New(env, "Wrong number of arguments. One argument expected.") + Napi::TypeError::New(env, + "Wrong number of arguments. One argument expected.") .ThrowAsJavaScriptException(); } return info[0].As(); diff --git a/test/addon_data.cc b/test/addon_data.cc index bcbfc4eee..c721aa608 100644 --- a/test/addon_data.cc +++ b/test/addon_data.cc @@ -17,11 +17,10 @@ class Addon { public: class VerboseIndicator : public Napi::ObjectWrap { public: - VerboseIndicator(const Napi::CallbackInfo& info): - Napi::ObjectWrap(info) { - info.This().As()["verbose"] = - Napi::Boolean::New(info.Env(), - info.Env().GetInstanceData()->verbose); + VerboseIndicator(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { + info.This().As()["verbose"] = Napi::Boolean::New( + info.Env(), info.Env().GetInstanceData()->verbose); } Napi::Value Getter(const Napi::CallbackInfo& info) { @@ -34,11 +33,11 @@ class Addon { } static Napi::FunctionReference Init(Napi::Env env) { - return Napi::Persistent(DefineClass(env, "VerboseIndicator", { - InstanceAccessor< - &VerboseIndicator::Getter, - &VerboseIndicator::Setter>("verbose") - })); + return Napi::Persistent(DefineClass( + env, + "VerboseIndicator", + {InstanceAccessor<&VerboseIndicator::Getter, + &VerboseIndicator::Setter>("verbose")})); } }; @@ -51,7 +50,7 @@ class Addon { info.Env().GetInstanceData()->verbose = info[0].As(); } - Addon(Napi::Env env): VerboseIndicator(VerboseIndicator::Init(env)) {} + Addon(Napi::Env env) : VerboseIndicator(VerboseIndicator::Init(env)) {} ~Addon() { if (verbose) { fprintf(stderr, "addon_data: Addon::~Addon\n"); @@ -76,7 +75,7 @@ class Addon { new uint32_t(hint)); Napi::Object result = Napi::Object::New(env); result.DefineProperties({ - Napi::PropertyDescriptor::Accessor("verbose"), + Napi::PropertyDescriptor::Accessor("verbose"), }); return result; diff --git a/test/basic_types/boolean.cc b/test/basic_types/boolean.cc index 4abacece4..9e67eed25 100644 --- a/test/basic_types/boolean.cc +++ b/test/basic_types/boolean.cc @@ -31,8 +31,10 @@ Object InitBasicTypesBoolean(Env env) { exports["createBoolean"] = Function::New(env, CreateBoolean); exports["createEmptyBoolean"] = Function::New(env, CreateEmptyBoolean); - exports["createBooleanFromExistingValue"] = Function::New(env, CreateBooleanFromExistingValue); - exports["createBooleanFromPrimitive"] = Function::New(env, CreateBooleanFromPrimitive); + exports["createBooleanFromExistingValue"] = + Function::New(env, CreateBooleanFromExistingValue); + exports["createBooleanFromPrimitive"] = + Function::New(env, CreateBooleanFromPrimitive); exports["operatorBool"] = Function::New(env, OperatorBool); return exports; } diff --git a/test/basic_types/number.cc b/test/basic_types/number.cc index 4ccb844b5..ee5c815ef 100644 --- a/test/basic_types/number.cc +++ b/test/basic_types/number.cc @@ -43,27 +43,32 @@ Value MaxDouble(const CallbackInfo& info) { Value OperatorInt32(const CallbackInfo& info) { Number number = info[0].As(); - return Boolean::New(info.Env(), number.Int32Value() == static_cast(number)); + return Boolean::New(info.Env(), + number.Int32Value() == static_cast(number)); } Value OperatorUint32(const CallbackInfo& info) { Number number = info[0].As(); - return Boolean::New(info.Env(), number.Uint32Value() == static_cast(number)); + return Boolean::New(info.Env(), + number.Uint32Value() == static_cast(number)); } Value OperatorInt64(const CallbackInfo& info) { Number number = info[0].As(); - return Boolean::New(info.Env(), number.Int64Value() == static_cast(number)); + return Boolean::New(info.Env(), + number.Int64Value() == static_cast(number)); } Value OperatorFloat(const CallbackInfo& info) { Number number = info[0].As(); - return Boolean::New(info.Env(), number.FloatValue() == static_cast(number)); + return Boolean::New(info.Env(), + number.FloatValue() == static_cast(number)); } Value OperatorDouble(const CallbackInfo& info) { Number number = info[0].As(); - return Boolean::New(info.Env(), number.DoubleValue() == static_cast(number)); + return Boolean::New(info.Env(), + number.DoubleValue() == static_cast(number)); } Value CreateEmptyNumber(const CallbackInfo& info) { @@ -93,7 +98,8 @@ Object InitBasicTypesNumber(Env env) { exports["operatorFloat"] = Function::New(env, OperatorFloat); exports["operatorDouble"] = Function::New(env, OperatorDouble); exports["createEmptyNumber"] = Function::New(env, CreateEmptyNumber); - exports["createNumberFromExistingValue"] = Function::New(env, CreateNumberFromExistingValue); + exports["createNumberFromExistingValue"] = + Function::New(env, CreateNumberFromExistingValue); return exports; } diff --git a/test/basic_types/value.cc b/test/basic_types/value.cc index 59de71202..8e3735998 100644 --- a/test/basic_types/value.cc +++ b/test/basic_types/value.cc @@ -12,7 +12,7 @@ Value CreateExternal(const CallbackInfo& info) { return External::New(info.Env(), &testData); } -} // end anonymous namespace +} // end anonymous namespace static Value IsEmpty(const CallbackInfo& info) { Value value; diff --git a/test/bigint.cc b/test/bigint.cc index e8e6e9cb4..9032e4aae 100644 --- a/test/bigint.cc +++ b/test/bigint.cc @@ -59,7 +59,8 @@ Value TestWords(const CallbackInfo& info) { big.ToWords(&sign_bit, &word_count, words); if (word_count != expected_word_count) { - Error::New(info.Env(), "word count did not match").ThrowAsJavaScriptException(); + Error::New(info.Env(), "word count did not match") + .ThrowAsJavaScriptException(); return BigInt(); } diff --git a/test/binding.cc b/test/binding.cc index f7a96e9b3..b3d9265d4 100644 --- a/test/binding.cc +++ b/test/binding.cc @@ -43,7 +43,7 @@ Object InitName(Env env); Object InitObject(Env env); #ifndef NODE_ADDON_API_DISABLE_DEPRECATED Object InitObjectDeprecated(Env env); -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED Object InitPromise(Env env); Object InitRunScript(Env env); #if (NAPI_VERSION > 3) @@ -126,13 +126,14 @@ Object Init(Env env, Object exports) { exports.Set("object", InitObject(env)); #ifndef NODE_ADDON_API_DISABLE_DEPRECATED exports.Set("object_deprecated", InitObjectDeprecated(env)); -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED exports.Set("promise", InitPromise(env)); exports.Set("run_script", InitRunScript(env)); exports.Set("symbol", InitSymbol(env)); #if (NAPI_VERSION > 3) exports.Set("threadsafe_function_ctx", InitThreadSafeFunctionCtx(env)); - exports.Set("threadsafe_function_existing_tsfn", InitThreadSafeFunctionExistingTsfn(env)); + exports.Set("threadsafe_function_existing_tsfn", + InitThreadSafeFunctionExistingTsfn(env)); exports.Set("threadsafe_function_ptr", InitThreadSafeFunctionPtr(env)); exports.Set("threadsafe_function_sum", InitThreadSafeFunctionSum(env)); exports.Set("threadsafe_function_unref", InitThreadSafeFunctionUnref(env)); @@ -152,10 +153,11 @@ Object Init(Env env, Object exports) { exports.Set("typedarray", InitTypedArray(env)); exports.Set("objectwrap", InitObjectWrap(env)); exports.Set("objectwrapConstructorException", - InitObjectWrapConstructorException(env)); + InitObjectWrapConstructorException(env)); exports.Set("objectwrap_function", InitObjectWrapFunction(env)); exports.Set("objectwrap_removewrap", InitObjectWrapRemoveWrap(env)); - exports.Set("objectwrap_multiple_inheritance", InitObjectWrapMultipleInheritance(env)); + exports.Set("objectwrap_multiple_inheritance", + InitObjectWrapMultipleInheritance(env)); exports.Set("objectreference", InitObjectReference(env)); exports.Set("reference", InitReference(env)); exports.Set("version_management", InitVersionManagement(env)); diff --git a/test/buffer.cc b/test/buffer.cc index c92c6fbf6..20ff20f46 100644 --- a/test/buffer.cc +++ b/test/buffer.cc @@ -29,7 +29,8 @@ Value CreateBuffer(const CallbackInfo& info) { Buffer buffer = Buffer::New(info.Env(), testLength); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return Value(); } @@ -40,18 +41,18 @@ Value CreateBuffer(const CallbackInfo& info) { Value CreateExternalBuffer(const CallbackInfo& info) { finalizeCount = 0; - Buffer buffer = Buffer::New( - info.Env(), - testData, - testLength); + Buffer buffer = + Buffer::New(info.Env(), testData, testLength); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return Value(); } if (buffer.Data() != testData) { - Error::New(info.Env(), "Incorrect buffer data.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); return Value(); } @@ -65,21 +66,20 @@ Value CreateExternalBufferWithFinalize(const CallbackInfo& info) { uint16_t* data = new uint16_t[testLength]; Buffer buffer = Buffer::New( - info.Env(), - data, - testLength, - [](Env /*env*/, uint16_t* finalizeData) { - delete[] finalizeData; - finalizeCount++; - }); + info.Env(), data, testLength, [](Env /*env*/, uint16_t* finalizeData) { + delete[] finalizeData; + finalizeCount++; + }); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return Value(); } if (buffer.Data() != data) { - Error::New(info.Env(), "Incorrect buffer data.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); return Value(); } @@ -94,22 +94,24 @@ Value CreateExternalBufferWithFinalizeHint(const CallbackInfo& info) { char* hint = nullptr; Buffer buffer = Buffer::New( - info.Env(), - data, - testLength, - [](Env /*env*/, uint16_t* finalizeData, char* /*finalizeHint*/) { - delete[] finalizeData; - finalizeCount++; - }, - hint); + info.Env(), + data, + testLength, + [](Env /*env*/, uint16_t* finalizeData, char* /*finalizeHint*/) { + delete[] finalizeData; + finalizeCount++; + }, + hint); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return Value(); } if (buffer.Data() != data) { - Error::New(info.Env(), "Incorrect buffer data.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); return Value(); } @@ -120,21 +122,24 @@ Value CreateExternalBufferWithFinalizeHint(const CallbackInfo& info) { Value CreateBufferCopy(const CallbackInfo& info) { InitData(testData, testLength); - Buffer buffer = Buffer::Copy( - info.Env(), testData, testLength); + Buffer buffer = + Buffer::Copy(info.Env(), testData, testLength); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return Value(); } if (buffer.Data() == testData) { - Error::New(info.Env(), "Copy should have different memory.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Copy should have different memory.") + .ThrowAsJavaScriptException(); return Value(); } if (!VerifyData(buffer.Data(), buffer.Length())) { - Error::New(info.Env(), "Copy data is incorrect.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Copy data is incorrect.") + .ThrowAsJavaScriptException(); return Value(); } @@ -143,28 +148,31 @@ Value CreateBufferCopy(const CallbackInfo& info) { void CheckBuffer(const CallbackInfo& info) { if (!info[0].IsBuffer()) { - Error::New(info.Env(), "A buffer was expected.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "A buffer was expected.") + .ThrowAsJavaScriptException(); return; } Buffer buffer = info[0].As>(); if (buffer.Length() != testLength) { - Error::New(info.Env(), "Incorrect buffer length.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer length.") + .ThrowAsJavaScriptException(); return; } if (!VerifyData(buffer.Data(), testLength)) { - Error::New(info.Env(), "Incorrect buffer data.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Incorrect buffer data.") + .ThrowAsJavaScriptException(); return; } } Value GetFinalizeCount(const CallbackInfo& info) { - return Number::New(info.Env(), finalizeCount); + return Number::New(info.Env(), finalizeCount); } -} // end anonymous namespace +} // end anonymous namespace Object InitBuffer(Env env) { Object exports = Object::New(env); @@ -172,9 +180,9 @@ Object InitBuffer(Env env) { exports["createBuffer"] = Function::New(env, CreateBuffer); exports["createExternalBuffer"] = Function::New(env, CreateExternalBuffer); exports["createExternalBufferWithFinalize"] = - Function::New(env, CreateExternalBufferWithFinalize); + Function::New(env, CreateExternalBufferWithFinalize); exports["createExternalBufferWithFinalizeHint"] = - Function::New(env, CreateExternalBufferWithFinalizeHint); + Function::New(env, CreateExternalBufferWithFinalizeHint); exports["createBufferCopy"] = Function::New(env, CreateBufferCopy); exports["checkBuffer"] = Function::New(env, CheckBuffer); exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); diff --git a/test/callbackscope.cc b/test/callbackscope.cc index 70b68fe60..5cfa96a87 100644 --- a/test/callbackscope.cc +++ b/test/callbackscope.cc @@ -12,7 +12,7 @@ static void RunInCallbackScope(const CallbackInfo& info) { callback.Call({}); } -} // end anonymous namespace +} // end anonymous namespace Object InitCallbackScope(Env env) { Object exports = Object::New(env); diff --git a/test/date.cc b/test/date.cc index c6e0dad21..efd433af4 100644 --- a/test/date.cc +++ b/test/date.cc @@ -26,7 +26,8 @@ Value ValueOf(const CallbackInfo& info) { Value OperatorValue(const CallbackInfo& info) { Date input = info[0].As(); - return Boolean::New(info.Env(), input.ValueOf() == static_cast(input)); + return Boolean::New(info.Env(), + input.ValueOf() == static_cast(input)); } } // anonymous namespace diff --git a/test/error.cc b/test/error.cc index 5b470a957..f6a43984a 100644 --- a/test/error.cc +++ b/test/error.cc @@ -140,7 +140,7 @@ void CatchAndRethrowErrorThatEscapesScope(const CallbackInfo& info) { } } -#else // NAPI_CPP_EXCEPTIONS +#else // NAPI_CPP_EXCEPTIONS void ThrowJSError(const CallbackInfo& info) { std::string message = info[0].As().Utf8Value(); @@ -219,7 +219,7 @@ void CatchAndRethrowErrorThatEscapesScope(const CallbackInfo& info) { } } -#endif // NAPI_CPP_EXCEPTIONS +#endif // NAPI_CPP_EXCEPTIONS void ThrowFatalError(const CallbackInfo& /*info*/) { Error::Fatal("Error::ThrowFatalError", "This is a fatal error"); @@ -261,7 +261,7 @@ void ThrowDefaultError(const CallbackInfo& info) { NAPI_THROW_IF_FAILED_VOID(env, status); } -} // end anonymous namespace +} // end anonymous namespace Object InitError(Env env) { Object exports = Object::New(env); @@ -275,9 +275,10 @@ Object InitError(Env env) { exports["catchErrorMessage"] = Function::New(env, CatchErrorMessage); exports["doNotCatch"] = Function::New(env, DoNotCatch); exports["catchAndRethrowError"] = Function::New(env, CatchAndRethrowError); - exports["throwErrorThatEscapesScope"] = Function::New(env, ThrowErrorThatEscapesScope); + exports["throwErrorThatEscapesScope"] = + Function::New(env, ThrowErrorThatEscapesScope); exports["catchAndRethrowErrorThatEscapesScope"] = - Function::New(env, CatchAndRethrowErrorThatEscapesScope); + Function::New(env, CatchAndRethrowErrorThatEscapesScope); exports["throwFatalError"] = Function::New(env, ThrowFatalError); exports["throwDefaultError"] = Function::New(env, ThrowDefaultError); exports["resetPromises"] = Function::New(env, ResetPromises); diff --git a/test/external.cc b/test/external.cc index 9c22dcbe8..255b17f19 100644 --- a/test/external.cc +++ b/test/external.cc @@ -14,66 +14,70 @@ Value CreateExternal(const CallbackInfo& info) { Value CreateExternalWithFinalize(const CallbackInfo& info) { finalizeCount = 0; - return External::New(info.Env(), new int(1), - [](Env /*env*/, int* data) { - delete data; - finalizeCount++; - }); + return External::New(info.Env(), new int(1), [](Env /*env*/, int* data) { + delete data; + finalizeCount++; + }); } Value CreateExternalWithFinalizeHint(const CallbackInfo& info) { finalizeCount = 0; char* hint = nullptr; - return External::New(info.Env(), new int(1), - [](Env /*env*/, int* data, char* /*hint*/) { - delete data; - finalizeCount++; - }, - hint); + return External::New( + info.Env(), + new int(1), + [](Env /*env*/, int* data, char* /*hint*/) { + delete data; + finalizeCount++; + }, + hint); } void CheckExternal(const CallbackInfo& info) { - Value arg = info[0]; - if (arg.Type() != napi_external) { - Error::New(info.Env(), "An external argument was expected.").ThrowAsJavaScriptException(); - return; - } + Value arg = info[0]; + if (arg.Type() != napi_external) { + Error::New(info.Env(), "An external argument was expected.") + .ThrowAsJavaScriptException(); + return; + } - External external = arg.As>(); - int* externalData = external.Data(); - if (externalData == nullptr || *externalData != 1) { - Error::New(info.Env(), "An external value of 1 was expected.").ThrowAsJavaScriptException(); - return; - } + External external = arg.As>(); + int* externalData = external.Data(); + if (externalData == nullptr || *externalData != 1) { + Error::New(info.Env(), "An external value of 1 was expected.") + .ThrowAsJavaScriptException(); + return; + } } Value GetFinalizeCount(const CallbackInfo& info) { - return Number::New(info.Env(), finalizeCount); + return Number::New(info.Env(), finalizeCount); } Value CreateExternalWithFinalizeException(const CallbackInfo& info) { - return External::New(info.Env(), new int(1), - [](Env env, int* data) { - Error error = Error::New(env, "Finalizer exception"); - delete data; + return External::New(info.Env(), new int(1), [](Env env, int* data) { + Error error = Error::New(env, "Finalizer exception"); + delete data; #ifdef NAPI_CPP_EXCEPTIONS - throw error; + throw error; #else error.ThrowAsJavaScriptException(); #endif - }); + }); } -} // end anonymous namespace +} // end anonymous namespace Object InitExternal(Env env) { Object exports = Object::New(env); exports["createExternal"] = Function::New(env, CreateExternal); - exports["createExternalWithFinalize"] = Function::New(env, CreateExternalWithFinalize); + exports["createExternalWithFinalize"] = + Function::New(env, CreateExternalWithFinalize); exports["createExternalWithFinalizeException"] = Function::New(env, CreateExternalWithFinalizeException); - exports["createExternalWithFinalizeHint"] = Function::New(env, CreateExternalWithFinalizeHint); + exports["createExternalWithFinalizeHint"] = + Function::New(env, CreateExternalWithFinalizeHint); exports["checkExternal"] = Function::New(env, CheckExternal); exports["getFinalizeCount"] = Function::New(env, GetFinalizeCount); diff --git a/test/function.cc b/test/function.cc index 0c1a2e703..be5b3b9d6 100644 --- a/test/function.cc +++ b/test/function.cc @@ -60,13 +60,13 @@ Value CallWithArgs(const CallbackInfo& info) { } Value CallWithVector(const CallbackInfo& info) { - Function func = info[0].As(); - std::vector args; - args.reserve(3); - args.push_back(info[1]); - args.push_back(info[2]); - args.push_back(info[3]); - return MaybeUnwrap(func.Call(args)); + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.Call(args)); } Value CallWithVectorUsingCppWrapper(const CallbackInfo& info) { @@ -101,21 +101,21 @@ Value CallWithReceiverAndCStyleArray(const CallbackInfo& info) { } Value CallWithReceiverAndArgs(const CallbackInfo& info) { - Function func = info[0].As(); - Value receiver = info[1]; - return MaybeUnwrap(func.Call( - receiver, std::initializer_list{info[2], info[3], info[4]})); + Function func = info[0].As(); + Value receiver = info[1]; + return MaybeUnwrap(func.Call( + receiver, std::initializer_list{info[2], info[3], info[4]})); } Value CallWithReceiverAndVector(const CallbackInfo& info) { - Function func = info[0].As(); - Value receiver = info[1]; - std::vector args; - args.reserve(3); - args.push_back(info[2]); - args.push_back(info[3]); - args.push_back(info[4]); - return MaybeUnwrap(func.Call(receiver, args)); + Function func = info[0].As(); + Value receiver = info[1]; + std::vector args; + args.reserve(3); + args.push_back(info[2]); + args.push_back(info[3]); + args.push_back(info[4]); + return MaybeUnwrap(func.Call(receiver, args)); } Value CallWithReceiverAndVectorUsingCppWrapper(const CallbackInfo& info) { @@ -130,25 +130,25 @@ Value CallWithReceiverAndVectorUsingCppWrapper(const CallbackInfo& info) { } Value CallWithInvalidReceiver(const CallbackInfo& info) { - Function func = info[0].As(); - return MaybeUnwrapOr(func.Call(Value(), std::initializer_list{}), - Value()); + Function func = info[0].As(); + return MaybeUnwrapOr(func.Call(Value(), std::initializer_list{}), + Value()); } Value CallConstructorWithArgs(const CallbackInfo& info) { - Function func = info[0].As(); - return MaybeUnwrap( - func.New(std::initializer_list{info[1], info[2], info[3]})); + Function func = info[0].As(); + return MaybeUnwrap( + func.New(std::initializer_list{info[1], info[2], info[3]})); } Value CallConstructorWithVector(const CallbackInfo& info) { - Function func = info[0].As(); - std::vector args; - args.reserve(3); - args.push_back(info[1]); - args.push_back(info[2]); - args.push_back(info[3]); - return MaybeUnwrap(func.New(args)); + Function func = info[0].As(); + std::vector args; + args.reserve(3); + args.push_back(info[1]); + args.push_back(info[2]); + args.push_back(info[3]); + return MaybeUnwrap(func.New(args)); } Value CallConstructorWithCStyleArray(const CallbackInfo& info) { @@ -162,9 +162,9 @@ Value CallConstructorWithCStyleArray(const CallbackInfo& info) { } void IsConstructCall(const CallbackInfo& info) { - Function callback = info[0].As(); - bool isConstructCall = info.IsConstructCall(); - callback({Napi::Boolean::New(info.Env(), isConstructCall)}); + Function callback = info[0].As(); + bool isConstructCall = info.IsConstructCall(); + callback({Napi::Boolean::New(info.Env(), isConstructCall)}); } void MakeCallbackWithArgs(const CallbackInfo& info) { @@ -220,18 +220,19 @@ Value CallWithFunctionOperator(const CallbackInfo& info) { return MaybeUnwrap(func({info[1], info[2], info[3]})); } -} // end anonymous namespace +} // end anonymous namespace Object InitFunction(Env env) { Object result = Object::New(env); Object exports = Object::New(env); exports["emptyConstructor"] = Function::New(env, EmptyConstructor); exports["voidCallback"] = Function::New(env, VoidCallback, "voidCallback"); - exports["valueCallback"] = Function::New(env, ValueCallback, std::string("valueCallback")); + exports["valueCallback"] = + Function::New(env, ValueCallback, std::string("valueCallback")); exports["voidCallbackWithData"] = - Function::New(env, VoidCallbackWithData, nullptr, &testData); + Function::New(env, VoidCallbackWithData, nullptr, &testData); exports["valueCallbackWithData"] = - Function::New(env, ValueCallbackWithData, nullptr, &testData); + Function::New(env, ValueCallbackWithData, nullptr, &testData); exports["callWithArgs"] = Function::New(env, CallWithArgs); exports["callWithVector"] = Function::New(env, CallWithVector); exports["callWithVectorUsingCppWrapper"] = @@ -239,13 +240,18 @@ Object InitFunction(Env env) { exports["callWithCStyleArray"] = Function::New(env, CallWithCStyleArray); exports["callWithReceiverAndCStyleArray"] = Function::New(env, CallWithReceiverAndCStyleArray); - exports["callWithReceiverAndArgs"] = Function::New(env, CallWithReceiverAndArgs); - exports["callWithReceiverAndVector"] = Function::New(env, CallWithReceiverAndVector); + exports["callWithReceiverAndArgs"] = + Function::New(env, CallWithReceiverAndArgs); + exports["callWithReceiverAndVector"] = + Function::New(env, CallWithReceiverAndVector); exports["callWithReceiverAndVectorUsingCppWrapper"] = Function::New(env, CallWithReceiverAndVectorUsingCppWrapper); - exports["callWithInvalidReceiver"] = Function::New(env, CallWithInvalidReceiver); - exports["callConstructorWithArgs"] = Function::New(env, CallConstructorWithArgs); - exports["callConstructorWithVector"] = Function::New(env, CallConstructorWithVector); + exports["callWithInvalidReceiver"] = + Function::New(env, CallWithInvalidReceiver); + exports["callConstructorWithArgs"] = + Function::New(env, CallConstructorWithArgs); + exports["callConstructorWithVector"] = + Function::New(env, CallConstructorWithVector); exports["callConstructorWithCStyleArray"] = Function::New(env, CallConstructorWithCStyleArray); exports["isConstructCall"] = Function::New(env, IsConstructCall); diff --git a/test/handlescope.cc b/test/handlescope.cc index 9c958850d..1c7bda393 100644 --- a/test/handlescope.cc +++ b/test/handlescope.cc @@ -1,7 +1,7 @@ -#include "napi.h" -#include "string.h" #include #include +#include "napi.h" +#include "string.h" using namespace Napi; @@ -31,7 +31,7 @@ Value stressEscapeFromScope(const CallbackInfo& info) { snprintf(buffer, 128, "%d", i); std::string name = std::string("inner-scope") + std::string(buffer); Value newValue = String::New(info.Env(), name.c_str()); - if (i == (LOOP_MAX -1)) { + if (i == (LOOP_MAX - 1)) { result = scope.Escape(newValue); } } diff --git a/test/memory_management.cc b/test/memory_management.cc index a42357539..48bc389d4 100644 --- a/test/memory_management.cc +++ b/test/memory_management.cc @@ -3,15 +3,16 @@ using namespace Napi; Value externalAllocatedMemory(const CallbackInfo& info) { - int64_t kSize = 1024 * 1024; - int64_t baseline = MemoryManagement::AdjustExternalMemory(info.Env(), 0); - int64_t tmp = MemoryManagement::AdjustExternalMemory(info.Env(), kSize); - tmp = MemoryManagement::AdjustExternalMemory(info.Env(), -kSize); - return Boolean::New(info.Env(), tmp == baseline); + int64_t kSize = 1024 * 1024; + int64_t baseline = MemoryManagement::AdjustExternalMemory(info.Env(), 0); + int64_t tmp = MemoryManagement::AdjustExternalMemory(info.Env(), kSize); + tmp = MemoryManagement::AdjustExternalMemory(info.Env(), -kSize); + return Boolean::New(info.Env(), tmp == baseline); } Object InitMemoryManagement(Env env) { - Object exports = Object::New(env); - exports["externalAllocatedMemory"] = Function::New(env, externalAllocatedMemory); - return exports; + Object exports = Object::New(env); + exports["externalAllocatedMemory"] = + Function::New(env, externalAllocatedMemory); + return exports; } diff --git a/test/object/finalizer.cc b/test/object/finalizer.cc index 3518ae99d..6122e5eb9 100644 --- a/test/object/finalizer.cc +++ b/test/object/finalizer.cc @@ -7,23 +7,24 @@ static int dummy; Value AddFinalizer(const CallbackInfo& info) { ObjectReference* ref = new ObjectReference; *ref = Persistent(Object::New(info.Env())); - info[0] - .As() - .AddFinalizer([](Napi::Env /*env*/, ObjectReference* ref) { - ref->Set("finalizerCalled", true); - delete ref; - }, ref); + info[0].As().AddFinalizer( + [](Napi::Env /*env*/, ObjectReference* ref) { + ref->Set("finalizerCalled", true); + delete ref; + }, + ref); return ref->Value(); } Value AddFinalizerWithHint(const CallbackInfo& info) { ObjectReference* ref = new ObjectReference; *ref = Persistent(Object::New(info.Env())); - info[0] - .As() - .AddFinalizer([](Napi::Env /*env*/, ObjectReference* ref, int* dummy_p) { - ref->Set("finalizerCalledWithCorrectHint", dummy_p == &dummy); - delete ref; - }, ref, &dummy); + info[0].As().AddFinalizer( + [](Napi::Env /*env*/, ObjectReference* ref, int* dummy_p) { + ref->Set("finalizerCalledWithCorrectHint", dummy_p == &dummy); + delete ref; + }, + ref, + &dummy); return ref->Value(); } diff --git a/test/object/object.cc b/test/object/object.cc index 934aacd3b..f6f0bd98b 100644 --- a/test/object/object.cc +++ b/test/object/object.cc @@ -56,11 +56,11 @@ struct UserDataHolder { }; Value TestGetter(const CallbackInfo& info) { - return Boolean::New(info.Env(), testValue); + return Boolean::New(info.Env(), testValue); } void TestSetter(const CallbackInfo& info) { - testValue = info[0].As(); + testValue = info[0].As(); } Value TestGetterWithUserData(const CallbackInfo& info) { @@ -74,7 +74,7 @@ void TestSetterWithUserData(const CallbackInfo& info) { } Value TestFunction(const CallbackInfo& info) { - return Boolean::New(info.Env(), true); + return Boolean::New(info.Env(), true); } Value TestFunctionWithUserData(const CallbackInfo& info) { @@ -112,36 +112,56 @@ void DefineProperties(const CallbackInfo& info) { if (nameType.Utf8Value() == "literal") { obj.DefineProperties({ - PropertyDescriptor::Accessor(env, obj, "readonlyAccessor", TestGetter), - PropertyDescriptor::Accessor(env, obj, "readwriteAccessor", TestGetter, TestSetter), - PropertyDescriptor::Accessor(env, obj, "readonlyAccessorWithUserData", TestGetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - PropertyDescriptor::Accessor(env, obj, "readwriteAccessorWithUserData", TestGetterWithUserData, TestSetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - - PropertyDescriptor::Accessor("readonlyAccessorT"), - PropertyDescriptor::Accessor( - "readwriteAccessorT"), - PropertyDescriptor::Accessor( - "readonlyAccessorWithUserDataT", - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - PropertyDescriptor::Accessor< - TestGetterWithUserData, - TestSetterWithUserData>("readwriteAccessorWithUserDataT", - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - - PropertyDescriptor::Value("readonlyValue", trueValue), - PropertyDescriptor::Value("readwriteValue", trueValue, napi_writable), - PropertyDescriptor::Value("enumerableValue", trueValue, napi_enumerable), - PropertyDescriptor::Value("configurableValue", trueValue, napi_configurable), - PropertyDescriptor::Function(env, obj, "function", TestFunction), - PropertyDescriptor::Function(env, obj, "functionWithUserData", TestFunctionWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, obj, "readonlyAccessor", TestGetter), + PropertyDescriptor::Accessor( + env, obj, "readwriteAccessor", TestGetter, TestSetter), + PropertyDescriptor::Accessor(env, + obj, + "readonlyAccessorWithUserData", + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, + obj, + "readwriteAccessorWithUserData", + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor("readonlyAccessorT"), + PropertyDescriptor::Accessor( + "readwriteAccessorT"), + PropertyDescriptor::Accessor( + "readonlyAccessorWithUserDataT", + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + "readwriteAccessorWithUserDataT", + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value("readonlyValue", trueValue), + PropertyDescriptor::Value("readwriteValue", trueValue, napi_writable), + PropertyDescriptor::Value( + "enumerableValue", trueValue, napi_enumerable), + PropertyDescriptor::Value( + "configurableValue", trueValue, napi_configurable), + PropertyDescriptor::Function(env, obj, "function", TestFunction), + PropertyDescriptor::Function(env, + obj, + "functionWithUserData", + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), }); } else if (nameType.Utf8Value() == "string") { - // VS2013 has lifetime issues when passing temporary objects into the constructor of another - // object. It generates code to destruct the object as soon as the constructor call returns. - // Since this isn't a common case for using std::string objects, I'm refactoring the test to - // work around the issue. + // VS2013 has lifetime issues when passing temporary objects into the + // constructor of another object. It generates code to destruct the object + // as soon as the constructor call returns. Since this isn't a common case + // for using std::string objects, I'm refactoring the test to work around + // the issue. std::string str1("readonlyAccessor"); std::string str2("readwriteAccessor"); std::string str1a("readonlyAccessorWithUserData"); @@ -160,66 +180,105 @@ void DefineProperties(const CallbackInfo& info) { std::string str8("functionWithUserData"); obj.DefineProperties({ - PropertyDescriptor::Accessor(env, obj, str1, TestGetter), - PropertyDescriptor::Accessor(env, obj, str2, TestGetter, TestSetter), - PropertyDescriptor::Accessor(env, obj, str1a, TestGetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - PropertyDescriptor::Accessor(env, obj, str2a, TestGetterWithUserData, TestSetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - - PropertyDescriptor::Accessor(str1t), - PropertyDescriptor::Accessor(str2t), - PropertyDescriptor::Accessor(str1at, - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - PropertyDescriptor::Accessor< - TestGetterWithUserData, - TestSetterWithUserData>(str2at, - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - - PropertyDescriptor::Value(str3, trueValue), - PropertyDescriptor::Value(str4, trueValue, napi_writable), - PropertyDescriptor::Value(str5, trueValue, napi_enumerable), - PropertyDescriptor::Value(str6, trueValue, napi_configurable), - PropertyDescriptor::Function(env, obj, str7, TestFunction), - PropertyDescriptor::Function(env, obj, str8, TestFunctionWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, obj, str1, TestGetter), + PropertyDescriptor::Accessor(env, obj, str2, TestGetter, TestSetter), + PropertyDescriptor::Accessor(env, + obj, + str1a, + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor(env, + obj, + str2a, + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor(str1t), + PropertyDescriptor::Accessor(str2t), + PropertyDescriptor::Accessor( + str1at, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + str2at, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value(str3, trueValue), + PropertyDescriptor::Value(str4, trueValue, napi_writable), + PropertyDescriptor::Value(str5, trueValue, napi_enumerable), + PropertyDescriptor::Value(str6, trueValue, napi_configurable), + PropertyDescriptor::Function(env, obj, str7, TestFunction), + PropertyDescriptor::Function(env, + obj, + str8, + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), }); } else if (nameType.Utf8Value() == "value") { obj.DefineProperties({ - PropertyDescriptor::Accessor(env, obj, - Napi::String::New(env, "readonlyAccessor"), TestGetter), - PropertyDescriptor::Accessor(env, obj, - Napi::String::New(env, "readwriteAccessor"), TestGetter, TestSetter), - PropertyDescriptor::Accessor(env, obj, - Napi::String::New(env, "readonlyAccessorWithUserData"), TestGetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - PropertyDescriptor::Accessor(env, obj, - Napi::String::New(env, "readwriteAccessorWithUserData"), TestGetterWithUserData, TestSetterWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), - - PropertyDescriptor::Accessor( - Napi::String::New(env, "readonlyAccessorT")), - PropertyDescriptor::Accessor( - Napi::String::New(env, "readwriteAccessorT")), - PropertyDescriptor::Accessor( - Napi::String::New(env, "readonlyAccessorWithUserDataT"), - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - PropertyDescriptor::Accessor< - TestGetterWithUserData, TestSetterWithUserData>( - Napi::String::New(env, "readwriteAccessorWithUserDataT"), - napi_property_attributes::napi_default, - reinterpret_cast(holder)), - - PropertyDescriptor::Value( - Napi::String::New(env, "readonlyValue"), trueValue), - PropertyDescriptor::Value( - Napi::String::New(env, "readwriteValue"), trueValue, napi_writable), - PropertyDescriptor::Value( - Napi::String::New(env, "enumerableValue"), trueValue, napi_enumerable), - PropertyDescriptor::Value( - Napi::String::New(env, "configurableValue"), trueValue, napi_configurable), - PropertyDescriptor::Function(env, obj, - Napi::String::New(env, "function"), TestFunction), - PropertyDescriptor::Function(env, obj, - Napi::String::New(env, "functionWithUserData"), TestFunctionWithUserData, napi_property_attributes::napi_default, reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + env, obj, Napi::String::New(env, "readonlyAccessor"), TestGetter), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readwriteAccessor"), + TestGetter, + TestSetter), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readonlyAccessorWithUserData"), + TestGetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + env, + obj, + Napi::String::New(env, "readwriteAccessorWithUserData"), + TestGetterWithUserData, + TestSetterWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Accessor( + Napi::String::New(env, "readonlyAccessorT")), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessorT")), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readonlyAccessorWithUserDataT"), + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessorWithUserDataT"), + napi_property_attributes::napi_default, + reinterpret_cast(holder)), + + PropertyDescriptor::Value(Napi::String::New(env, "readonlyValue"), + trueValue), + PropertyDescriptor::Value( + Napi::String::New(env, "readwriteValue"), trueValue, napi_writable), + PropertyDescriptor::Value(Napi::String::New(env, "enumerableValue"), + trueValue, + napi_enumerable), + PropertyDescriptor::Value(Napi::String::New(env, "configurableValue"), + trueValue, + napi_configurable), + PropertyDescriptor::Function( + env, obj, Napi::String::New(env, "function"), TestFunction), + PropertyDescriptor::Function( + env, + obj, + Napi::String::New(env, "functionWithUserData"), + TestFunctionWithUserData, + napi_property_attributes::napi_default, + reinterpret_cast(holder)), }); } } @@ -295,36 +354,57 @@ Object InitObject(Env env) { exports["defineValueProperty"] = Function::New(env, DefineValueProperty); exports["getPropertyWithUint32"] = Function::New(env, GetPropertyWithUint32); - exports["getPropertyWithNapiValue"] = Function::New(env, GetPropertyWithNapiValue); - exports["getPropertyWithNapiWrapperValue"] = Function::New(env, GetPropertyWithNapiWrapperValue); - exports["getPropertyWithCStyleString"] = Function::New(env, GetPropertyWithCStyleString); - exports["getPropertyWithCppStyleString"] = Function::New(env, GetPropertyWithCppStyleString); + exports["getPropertyWithNapiValue"] = + Function::New(env, GetPropertyWithNapiValue); + exports["getPropertyWithNapiWrapperValue"] = + Function::New(env, GetPropertyWithNapiWrapperValue); + exports["getPropertyWithCStyleString"] = + Function::New(env, GetPropertyWithCStyleString); + exports["getPropertyWithCppStyleString"] = + Function::New(env, GetPropertyWithCppStyleString); exports["setPropertyWithUint32"] = Function::New(env, SetPropertyWithUint32); - exports["setPropertyWithNapiValue"] = Function::New(env, SetPropertyWithNapiValue); - exports["setPropertyWithNapiWrapperValue"] = Function::New(env, SetPropertyWithNapiWrapperValue); - exports["setPropertyWithCStyleString"] = Function::New(env, SetPropertyWithCStyleString); - exports["setPropertyWithCppStyleString"] = Function::New(env, SetPropertyWithCppStyleString); + exports["setPropertyWithNapiValue"] = + Function::New(env, SetPropertyWithNapiValue); + exports["setPropertyWithNapiWrapperValue"] = + Function::New(env, SetPropertyWithNapiWrapperValue); + exports["setPropertyWithCStyleString"] = + Function::New(env, SetPropertyWithCStyleString); + exports["setPropertyWithCppStyleString"] = + Function::New(env, SetPropertyWithCppStyleString); exports["deletePropertyWithUint32"] = Function::New(env, DeletePropertyWithUint32); - exports["deletePropertyWithNapiValue"] = Function::New(env, DeletePropertyWithNapiValue); - exports["deletePropertyWithNapiWrapperValue"] = Function::New(env, DeletePropertyWithNapiWrapperValue); - exports["deletePropertyWithCStyleString"] = Function::New(env, DeletePropertyWithCStyleString); - exports["deletePropertyWithCppStyleString"] = Function::New(env, DeletePropertyWithCppStyleString); - - exports["hasOwnPropertyWithNapiValue"] = Function::New(env, HasOwnPropertyWithNapiValue); - exports["hasOwnPropertyWithNapiWrapperValue"] = Function::New(env, HasOwnPropertyWithNapiWrapperValue); - exports["hasOwnPropertyWithCStyleString"] = Function::New(env, HasOwnPropertyWithCStyleString); - exports["hasOwnPropertyWithCppStyleString"] = Function::New(env, HasOwnPropertyWithCppStyleString); + exports["deletePropertyWithNapiValue"] = + Function::New(env, DeletePropertyWithNapiValue); + exports["deletePropertyWithNapiWrapperValue"] = + Function::New(env, DeletePropertyWithNapiWrapperValue); + exports["deletePropertyWithCStyleString"] = + Function::New(env, DeletePropertyWithCStyleString); + exports["deletePropertyWithCppStyleString"] = + Function::New(env, DeletePropertyWithCppStyleString); + + exports["hasOwnPropertyWithNapiValue"] = + Function::New(env, HasOwnPropertyWithNapiValue); + exports["hasOwnPropertyWithNapiWrapperValue"] = + Function::New(env, HasOwnPropertyWithNapiWrapperValue); + exports["hasOwnPropertyWithCStyleString"] = + Function::New(env, HasOwnPropertyWithCStyleString); + exports["hasOwnPropertyWithCppStyleString"] = + Function::New(env, HasOwnPropertyWithCppStyleString); exports["hasPropertyWithUint32"] = Function::New(env, HasPropertyWithUint32); - exports["hasPropertyWithNapiValue"] = Function::New(env, HasPropertyWithNapiValue); - exports["hasPropertyWithNapiWrapperValue"] = Function::New(env, HasPropertyWithNapiWrapperValue); - exports["hasPropertyWithCStyleString"] = Function::New(env, HasPropertyWithCStyleString); - exports["hasPropertyWithCppStyleString"] = Function::New(env, HasPropertyWithCppStyleString); - - exports["createObjectUsingMagic"] = Function::New(env, CreateObjectUsingMagic); + exports["hasPropertyWithNapiValue"] = + Function::New(env, HasPropertyWithNapiValue); + exports["hasPropertyWithNapiWrapperValue"] = + Function::New(env, HasPropertyWithNapiWrapperValue); + exports["hasPropertyWithCStyleString"] = + Function::New(env, HasPropertyWithCStyleString); + exports["hasPropertyWithCppStyleString"] = + Function::New(env, HasPropertyWithCppStyleString); + + exports["createObjectUsingMagic"] = + Function::New(env, CreateObjectUsingMagic); #ifdef NAPI_CPP_EXCEPTIONS exports["sum"] = Function::New(env, Sum); exports["increment"] = Function::New(env, Increment); diff --git a/test/object/object_deprecated.cc b/test/object/object_deprecated.cc index 2ec16e579..e5b9f01b7 100644 --- a/test/object/object_deprecated.cc +++ b/test/object/object_deprecated.cc @@ -7,15 +7,15 @@ static bool testValue = true; namespace { Value TestGetter(const CallbackInfo& info) { - return Boolean::New(info.Env(), testValue); + return Boolean::New(info.Env(), testValue); } void TestSetter(const CallbackInfo& info) { - testValue = info[0].As(); + testValue = info[0].As(); } Value TestFunction(const CallbackInfo& info) { - return Boolean::New(info.Env(), true); + return Boolean::New(info.Env(), true); } void DefineProperties(const CallbackInfo& info) { @@ -25,37 +25,41 @@ void DefineProperties(const CallbackInfo& info) { if (nameType.Utf8Value() == "literal") { obj.DefineProperties({ - PropertyDescriptor::Accessor("readonlyAccessor", TestGetter), - PropertyDescriptor::Accessor("readwriteAccessor", TestGetter, TestSetter), - PropertyDescriptor::Function("function", TestFunction), + PropertyDescriptor::Accessor("readonlyAccessor", TestGetter), + PropertyDescriptor::Accessor( + "readwriteAccessor", TestGetter, TestSetter), + PropertyDescriptor::Function("function", TestFunction), }); } else if (nameType.Utf8Value() == "string") { - // VS2013 has lifetime issues when passing temporary objects into the constructor of another - // object. It generates code to destruct the object as soon as the constructor call returns. - // Since this isn't a common case for using std::string objects, I'm refactoring the test to - // work around the issue. + // VS2013 has lifetime issues when passing temporary objects into the + // constructor of another object. It generates code to destruct the object + // as soon as the constructor call returns. Since this isn't a common case + // for using std::string objects, I'm refactoring the test to work around + // the issue. std::string str1("readonlyAccessor"); std::string str2("readwriteAccessor"); std::string str7("function"); obj.DefineProperties({ - PropertyDescriptor::Accessor(str1, TestGetter), - PropertyDescriptor::Accessor(str2, TestGetter, TestSetter), - PropertyDescriptor::Function(str7, TestFunction), + PropertyDescriptor::Accessor(str1, TestGetter), + PropertyDescriptor::Accessor(str2, TestGetter, TestSetter), + PropertyDescriptor::Function(str7, TestFunction), }); } else if (nameType.Utf8Value() == "value") { obj.DefineProperties({ - PropertyDescriptor::Accessor( - Napi::String::New(env, "readonlyAccessor"), TestGetter), - PropertyDescriptor::Accessor( - Napi::String::New(env, "readwriteAccessor"), TestGetter, TestSetter), - PropertyDescriptor::Function( - Napi::String::New(env, "function"), TestFunction), + PropertyDescriptor::Accessor(Napi::String::New(env, "readonlyAccessor"), + TestGetter), + PropertyDescriptor::Accessor( + Napi::String::New(env, "readwriteAccessor"), + TestGetter, + TestSetter), + PropertyDescriptor::Function(Napi::String::New(env, "function"), + TestFunction), }); } } -} // end of anonymous namespace +} // end of anonymous namespace Object InitObjectDeprecated(Env env) { Object exports = Object::New(env); diff --git a/test/objectwrap.cc b/test/objectwrap.cc index 65727a3df..aa9389678 100644 --- a/test/objectwrap.cc +++ b/test/objectwrap.cc @@ -7,7 +7,8 @@ Napi::Value StaticGetter(const Napi::CallbackInfo& /*info*/) { return MaybeUnwrap(testStaticContextRef.Value().Get("value")); } -void StaticSetter(const Napi::CallbackInfo& /*info*/, const Napi::Value& value) { +void StaticSetter(const Napi::CallbackInfo& /*info*/, + const Napi::Value& value) { testStaticContextRef.Value().Set("value", value); } @@ -22,11 +23,9 @@ Napi::Value TestStaticMethodInternal(const Napi::CallbackInfo& info) { } class Test : public Napi::ObjectWrap { -public: - Test(const Napi::CallbackInfo& info) : - Napi::ObjectWrap(info) { - - if(info.Length() > 0) { + public: + Test(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) { + if (info.Length() > 0) { finalizeCb_ = Napi::Persistent(info[0].As()); } // Create an own instance property. @@ -35,20 +34,19 @@ class Test : public Napi::ObjectWrap { info.This().As(), "ownProperty", OwnPropertyGetter, - napi_enumerable, this)); + napi_enumerable, + this)); // Create an own instance property with a templated function. info.This().As().DefineProperty( - Napi::PropertyDescriptor::Accessor("ownPropertyT", - napi_enumerable, this)); + Napi::PropertyDescriptor::Accessor( + "ownPropertyT", napi_enumerable, this)); bufref_ = Napi::Persistent(Napi::Buffer::New( Env(), static_cast(malloc(1)), 1, - [](Napi::Env, uint8_t* bufaddr) { - free(bufaddr); - })); + [](Napi::Env, uint8_t* bufaddr) { free(bufaddr); })); } static Napi::Value OwnPropertyGetter(const Napi::CallbackInfo& info) { @@ -88,16 +86,16 @@ class Test : public Napi::ObjectWrap { .Call(array, {})); } - void TestVoidMethodT(const Napi::CallbackInfo &info) { + void TestVoidMethodT(const Napi::CallbackInfo& info) { value_ = MaybeUnwrap(info[0].ToString()); } - Napi::Value TestMethodT(const Napi::CallbackInfo &info) { - return Napi::String::New(info.Env(), value_); + Napi::Value TestMethodT(const Napi::CallbackInfo& info) { + return Napi::String::New(info.Env(), value_); } static Napi::Value TestStaticMethodT(const Napi::CallbackInfo& info) { - return Napi::String::New(info.Env(), s_staticMethodText); + return Napi::String::New(info.Env(), s_staticMethodText); } static void TestStaticVoidMethodT(const Napi::CallbackInfo& info) { @@ -105,20 +103,31 @@ class Test : public Napi::ObjectWrap { } static void Initialize(Napi::Env env, Napi::Object exports) { - - Napi::Symbol kTestStaticValueInternal = Napi::Symbol::New(env, "kTestStaticValueInternal"); - Napi::Symbol kTestStaticAccessorInternal = Napi::Symbol::New(env, "kTestStaticAccessorInternal"); - Napi::Symbol kTestStaticAccessorTInternal = Napi::Symbol::New(env, "kTestStaticAccessorTInternal"); - Napi::Symbol kTestStaticMethodInternal = Napi::Symbol::New(env, "kTestStaticMethodInternal"); - Napi::Symbol kTestStaticMethodTInternal = Napi::Symbol::New(env, "kTestStaticMethodTInternal"); - Napi::Symbol kTestStaticVoidMethodTInternal = Napi::Symbol::New(env, "kTestStaticVoidMethodTInternal"); - - Napi::Symbol kTestValueInternal = Napi::Symbol::New(env, "kTestValueInternal"); - Napi::Symbol kTestAccessorInternal = Napi::Symbol::New(env, "kTestAccessorInternal"); - Napi::Symbol kTestAccessorTInternal = Napi::Symbol::New(env, "kTestAccessorTInternal"); - Napi::Symbol kTestMethodInternal = Napi::Symbol::New(env, "kTestMethodInternal"); - Napi::Symbol kTestMethodTInternal = Napi::Symbol::New(env, "kTestMethodTInternal"); - Napi::Symbol kTestVoidMethodTInternal = Napi::Symbol::New(env, "kTestVoidMethodTInternal"); + Napi::Symbol kTestStaticValueInternal = + Napi::Symbol::New(env, "kTestStaticValueInternal"); + Napi::Symbol kTestStaticAccessorInternal = + Napi::Symbol::New(env, "kTestStaticAccessorInternal"); + Napi::Symbol kTestStaticAccessorTInternal = + Napi::Symbol::New(env, "kTestStaticAccessorTInternal"); + Napi::Symbol kTestStaticMethodInternal = + Napi::Symbol::New(env, "kTestStaticMethodInternal"); + Napi::Symbol kTestStaticMethodTInternal = + Napi::Symbol::New(env, "kTestStaticMethodTInternal"); + Napi::Symbol kTestStaticVoidMethodTInternal = + Napi::Symbol::New(env, "kTestStaticVoidMethodTInternal"); + + Napi::Symbol kTestValueInternal = + Napi::Symbol::New(env, "kTestValueInternal"); + Napi::Symbol kTestAccessorInternal = + Napi::Symbol::New(env, "kTestAccessorInternal"); + Napi::Symbol kTestAccessorTInternal = + Napi::Symbol::New(env, "kTestAccessorTInternal"); + Napi::Symbol kTestMethodInternal = + Napi::Symbol::New(env, "kTestMethodInternal"); + Napi::Symbol kTestMethodTInternal = + Napi::Symbol::New(env, "kTestMethodTInternal"); + Napi::Symbol kTestVoidMethodTInternal = + Napi::Symbol::New(env, "kTestVoidMethodTInternal"); exports.Set( "Test", @@ -237,17 +246,15 @@ class Test : public Napi::ObjectWrap { } void Finalize(Napi::Env env) { - - if(finalizeCb_.IsEmpty()) { + if (finalizeCb_.IsEmpty()) { return; } finalizeCb_.Call(env.Global(), {Napi::Boolean::New(env, true)}); finalizeCb_.Unref(); - } -private: + private: std::string value_; Napi::FunctionReference finalizeCb_; diff --git a/test/objectwrap_constructor_exception.cc b/test/objectwrap_constructor_exception.cc index d7e1bd517..266135547 100644 --- a/test/objectwrap_constructor_exception.cc +++ b/test/objectwrap_constructor_exception.cc @@ -1,10 +1,10 @@ #include -class ConstructorExceptionTest : - public Napi::ObjectWrap { -public: - ConstructorExceptionTest(const Napi::CallbackInfo& info) : - Napi::ObjectWrap(info) { +class ConstructorExceptionTest + : public Napi::ObjectWrap { + public: + ConstructorExceptionTest(const Napi::CallbackInfo& info) + : Napi::ObjectWrap(info) { Napi::Error error = Napi::Error::New(info.Env(), "an exception"); #ifdef NAPI_DISABLE_CPP_EXCEPTIONS error.ThrowAsJavaScriptException(); diff --git a/test/objectwrap_multiple_inheritance.cc b/test/objectwrap_multiple_inheritance.cc index 67913eb4e..30daaba43 100644 --- a/test/objectwrap_multiple_inheritance.cc +++ b/test/objectwrap_multiple_inheritance.cc @@ -1,25 +1,25 @@ #include class TestMIBase { -public: + public: TestMIBase() : test(0) {} virtual void dummy() {} uint32_t test; }; class TestMI : public TestMIBase, public Napi::ObjectWrap { -public: - TestMI(const Napi::CallbackInfo& info) : - Napi::ObjectWrap(info) {} + public: + TestMI(const Napi::CallbackInfo& info) : Napi::ObjectWrap(info) {} Napi::Value GetTest(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), test); } static void Initialize(Napi::Env env, Napi::Object exports) { - exports.Set("TestMI", DefineClass(env, "TestMI", { - InstanceAccessor<&TestMI::GetTest>("test") - })); + exports.Set( + "TestMI", + DefineClass( + env, "TestMI", {InstanceAccessor<&TestMI::GetTest>("test")})); } }; diff --git a/test/reference.cc b/test/reference.cc index f93263295..9b8f81563 100644 --- a/test/reference.cc +++ b/test/reference.cc @@ -4,7 +4,7 @@ using namespace Napi; static Reference> weak; -void CreateWeakArray(const CallbackInfo& info) { +void CreateWeakArray(const CallbackInfo& info) { weak = Weak(Buffer::New(info.Env(), 1)); weak.SuppressDestruct(); } diff --git a/test/run_script.cc b/test/run_script.cc index 507164cad..cc7a74b71 100644 --- a/test/run_script.cc +++ b/test/run_script.cc @@ -42,7 +42,7 @@ Value RunWithContext(const CallbackInfo& info) { return MaybeUnwrap(fn.Call(args)); } -} // end anonymous namespace +} // end anonymous namespace Object InitRunScript(Env env) { Object exports = Object::New(env); diff --git a/test/threadsafe_function/threadsafe_function.cc b/test/threadsafe_function/threadsafe_function.cc index 6886eef47..c6eddc4de 100644 --- a/test/threadsafe_function/threadsafe_function.cc +++ b/test/threadsafe_function/threadsafe_function.cc @@ -15,11 +15,7 @@ static std::thread threads[2]; static ThreadSafeFunction tsfn; struct ThreadSafeFunctionInfo { - enum CallType { - DEFAULT, - BLOCKING, - NON_BLOCKING - } type; + enum CallType { DEFAULT, BLOCKING, NON_BLOCKING } type; bool abort; bool startSecondary; FunctionReference jsFinalizeCallback; @@ -55,7 +51,7 @@ static void DataSourceThread() { for (int index = ARRAY_LENGTH - 1; index > -1 && !queueWasClosing; index--) { napi_status status = napi_generic_failure; auto callback = [](Env env, Function jsCallback, int* data) { - jsCallback.Call({ Number::New(env, *data) }); + jsCallback.Call({Number::New(env, *data)}); }; switch (info->type) { @@ -80,20 +76,20 @@ static void DataSourceThread() { } switch (status) { - case napi_queue_full: - queueWasFull = true; - index++; - // fall through + case napi_queue_full: + queueWasFull = true; + index++; + // fall through - case napi_ok: - continue; + case napi_ok: + continue; - case napi_closing: - queueWasClosing = true; - break; + case napi_closing: + queueWasClosing = true; + break; - default: - Error::Fatal("DataSourceThread", "ThreadSafeFunction.*Call() failed"); + default: + Error::Fatal("DataSourceThread", "ThreadSafeFunction.*Call() failed"); } } @@ -140,15 +136,21 @@ static void JoinTheThreads(Env /* env */, } static Value StartThreadInternal(const CallbackInfo& info, - ThreadSafeFunctionInfo::CallType type) { + ThreadSafeFunctionInfo::CallType type) { tsfnInfo.type = type; tsfnInfo.abort = info[1].As(); tsfnInfo.startSecondary = info[2].As(); tsfnInfo.maxQueueSize = info[3].As().Uint32Value(); tsfnInfo.closeCalledFromJs = false; - tsfn = ThreadSafeFunction::New(info.Env(), info[0].As(), - "Test", tsfnInfo.maxQueueSize, 2, &tsfnInfo, JoinTheThreads, threads); + tsfn = ThreadSafeFunction::New(info.Env(), + info[0].As(), + "Test", + tsfnInfo.maxQueueSize, + 2, + &tsfnInfo, + JoinTheThreads, + threads); threads[0] = std::thread(DataSourceThread); diff --git a/test/threadsafe_function/threadsafe_function_ctx.cc b/test/threadsafe_function/threadsafe_function_ctx.cc index bae83baa0..470de12fd 100644 --- a/test/threadsafe_function/threadsafe_function_ctx.cc +++ b/test/threadsafe_function/threadsafe_function_ctx.cc @@ -7,30 +7,31 @@ using namespace Napi; namespace { class TSFNWrap : public ObjectWrap { -public: + public: static Object Init(Napi::Env env, Object exports); - TSFNWrap(const CallbackInfo &info); + TSFNWrap(const CallbackInfo& info); - Napi::Value GetContext(const CallbackInfo & /*info*/) { - Reference *ctx = _tsfn.GetContext(); + Napi::Value GetContext(const CallbackInfo& /*info*/) { + Reference* ctx = _tsfn.GetContext(); return ctx->Value(); }; - Napi::Value Release(const CallbackInfo &info) { + Napi::Value Release(const CallbackInfo& info) { Napi::Env env = info.Env(); _deferred = std::unique_ptr(new Promise::Deferred(env)); _tsfn.Release(); return _deferred->Promise(); }; -private: + private: ThreadSafeFunction _tsfn; std::unique_ptr _deferred; }; Object TSFNWrap::Init(Napi::Env env, Object exports) { Function func = - DefineClass(env, "TSFNWrap", + DefineClass(env, + "TSFNWrap", {InstanceMethod("getContext", &TSFNWrap::GetContext), InstanceMethod("release", &TSFNWrap::Release)}); @@ -38,23 +39,28 @@ Object TSFNWrap::Init(Napi::Env env, Object exports) { return exports; } -TSFNWrap::TSFNWrap(const CallbackInfo &info) : ObjectWrap(info) { +TSFNWrap::TSFNWrap(const CallbackInfo& info) : ObjectWrap(info) { Napi::Env env = info.Env(); - Reference *_ctx = new Reference; + Reference* _ctx = new Reference; *_ctx = Persistent(info[0]); _tsfn = ThreadSafeFunction::New( - info.Env(), Function::New(env, [](const CallbackInfo & /*info*/) {}), - Object::New(env), "Test", 1, 1, _ctx, - [this](Napi::Env env, Reference *ctx) { + info.Env(), + Function::New(env, [](const CallbackInfo& /*info*/) {}), + Object::New(env), + "Test", + 1, + 1, + _ctx, + [this](Napi::Env env, Reference* ctx) { _deferred->Resolve(env.Undefined()); ctx->Reset(); delete ctx; }); } -} // namespace +} // namespace Object InitThreadSafeFunctionCtx(Env env) { return TSFNWrap::Init(env, Object::New(env)); diff --git a/test/threadsafe_function/threadsafe_function_existing_tsfn.cc b/test/threadsafe_function/threadsafe_function_existing_tsfn.cc index 9307b22f1..226493703 100644 --- a/test/threadsafe_function/threadsafe_function_existing_tsfn.cc +++ b/test/threadsafe_function/threadsafe_function_existing_tsfn.cc @@ -9,21 +9,20 @@ using namespace Napi; namespace { struct TestContext { - TestContext(Promise::Deferred &&deferred) + TestContext(Promise::Deferred&& deferred) : deferred(std::move(deferred)), callData(nullptr){}; napi_threadsafe_function tsfn; Promise::Deferred deferred; - double *callData; + double* callData; ~TestContext() { - if (callData != nullptr) - delete callData; + if (callData != nullptr) delete callData; }; }; -void FinalizeCB(napi_env env, void * /*finalizeData */, void *context) { - TestContext *testContext = static_cast(context); +void FinalizeCB(napi_env env, void* /*finalizeData */, void* context) { + TestContext* testContext = static_cast(context); if (testContext->callData != nullptr) { testContext->deferred.Resolve(Number::New(env, *testContext->callData)); } else { @@ -32,10 +31,12 @@ void FinalizeCB(napi_env env, void * /*finalizeData */, void *context) { delete testContext; } -void CallJSWithData(napi_env env, napi_value /* callback */, void *context, - void *data) { - TestContext *testContext = static_cast(context); - testContext->callData = static_cast(data); +void CallJSWithData(napi_env env, + napi_value /* callback */, + void* context, + void* data) { + TestContext* testContext = static_cast(context); + testContext->callData = static_cast(data); napi_status status = napi_release_threadsafe_function(testContext->tsfn, napi_tsfn_release); @@ -43,9 +44,11 @@ void CallJSWithData(napi_env env, napi_value /* callback */, void *context, NAPI_THROW_IF_FAILED_VOID(env, status); } -void CallJSNoData(napi_env env, napi_value /* callback */, void *context, - void * /*data*/) { - TestContext *testContext = static_cast(context); +void CallJSNoData(napi_env env, + napi_value /* callback */, + void* context, + void* /*data*/) { + TestContext* testContext = static_cast(context); testContext->callData = nullptr; napi_status status = @@ -54,7 +57,7 @@ void CallJSNoData(napi_env env, napi_value /* callback */, void *context, NAPI_THROW_IF_FAILED_VOID(env, status); } -static Value TestCall(const CallbackInfo &info) { +static Value TestCall(const CallbackInfo& info) { Napi::Env env = info.Env(); bool isBlocking = false; bool hasData = false; @@ -71,15 +74,22 @@ static Value TestCall(const CallbackInfo &info) { } // Allow optional callback passed from JS. Useful for testing. - Function cb = Function::New(env, [](const CallbackInfo & /*info*/) {}); + Function cb = Function::New(env, [](const CallbackInfo& /*info*/) {}); - TestContext *testContext = new TestContext(Napi::Promise::Deferred(env)); + TestContext* testContext = new TestContext(Napi::Promise::Deferred(env)); - napi_status status = napi_create_threadsafe_function( - env, cb, Object::New(env), String::New(env, "Test"), 0, 1, - nullptr, /*finalize data*/ - FinalizeCB, testContext, hasData ? CallJSWithData : CallJSNoData, - &testContext->tsfn); + napi_status status = + napi_create_threadsafe_function(env, + cb, + Object::New(env), + String::New(env, "Test"), + 0, + 1, + nullptr, /*finalize data*/ + FinalizeCB, + testContext, + hasData ? CallJSWithData : CallJSNoData, + &testContext->tsfn); NAPI_THROW_IF_FAILED(env, status, Value()); @@ -88,22 +98,22 @@ static Value TestCall(const CallbackInfo &info) { // Test the four napi_threadsafe_function direct-accessing calls if (isBlocking) { if (hasData) { - wrapped.BlockingCall(static_cast(new double(std::rand()))); + wrapped.BlockingCall(static_cast(new double(std::rand()))); } else { - wrapped.BlockingCall(static_cast(nullptr)); + wrapped.BlockingCall(static_cast(nullptr)); } } else { if (hasData) { - wrapped.NonBlockingCall(static_cast(new double(std::rand()))); + wrapped.NonBlockingCall(static_cast(new double(std::rand()))); } else { - wrapped.NonBlockingCall(static_cast(nullptr)); + wrapped.NonBlockingCall(static_cast(nullptr)); } } return testContext->deferred.Promise(); } -} // namespace +} // namespace Object InitThreadSafeFunctionExistingTsfn(Env env) { Object exports = Object::New(env); diff --git a/test/threadsafe_function/threadsafe_function_ptr.cc b/test/threadsafe_function/threadsafe_function_ptr.cc index 00e8559b8..4a1df1487 100644 --- a/test/threadsafe_function/threadsafe_function_ptr.cc +++ b/test/threadsafe_function/threadsafe_function_ptr.cc @@ -9,12 +9,13 @@ namespace { static Value Test(const CallbackInfo& info) { Object resource = info[0].As(); Function cb = info[1].As(); - ThreadSafeFunction tsfn = ThreadSafeFunction::New(info.Env(), cb, resource, "Test", 1, 1); + ThreadSafeFunction tsfn = + ThreadSafeFunction::New(info.Env(), cb, resource, "Test", 1, 1); tsfn.Release(); return info.Env().Undefined(); } -} +} // namespace Object InitThreadSafeFunctionPtr(Env env) { Object exports = Object::New(env); diff --git a/test/threadsafe_function/threadsafe_function_sum.cc b/test/threadsafe_function/threadsafe_function_sum.cc index 019b0cea7..68e72fb7c 100644 --- a/test/threadsafe_function/threadsafe_function_sum.cc +++ b/test/threadsafe_function/threadsafe_function_sum.cc @@ -1,8 +1,8 @@ -#include "napi.h" -#include -#include #include +#include #include +#include +#include "napi.h" #if (NAPI_VERSION > 3) @@ -11,9 +11,8 @@ using namespace Napi; namespace { struct TestData { + TestData(Promise::Deferred&& deferred) : deferred(std::move(deferred)){}; - TestData(Promise::Deferred&& deferred) : deferred(std::move(deferred)) {}; - // Native Promise returned to JavaScript Promise::Deferred deferred; @@ -28,7 +27,7 @@ struct TestData { size_t expected_calls = 0; }; -void FinalizerCallback(Napi::Env env, TestData* finalizeData){ +void FinalizerCallback(Napi::Env env, TestData* finalizeData) { for (size_t i = 0; i < finalizeData->threads.size(); ++i) { finalizeData->threads[i].join(); } @@ -42,8 +41,8 @@ void FinalizerCallback(Napi::Env env, TestData* finalizeData){ void entryWithTSFN(ThreadSafeFunction tsfn, int threadId) { std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); - tsfn.BlockingCall( [=](Napi::Env env, Function callback) { - callback.Call( { Number::New(env, static_cast(threadId))}); + tsfn.BlockingCall([=](Napi::Env env, Function callback) { + callback.Call({Number::New(env, static_cast(threadId))}); }); tsfn.Release(); } @@ -54,15 +53,20 @@ static Value TestWithTSFN(const CallbackInfo& info) { // We pass the test data to the Finalizer for cleanup. The finalizer is // responsible for deleting this data as well. - TestData *testData = new TestData(Promise::Deferred::New(info.Env())); + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); ThreadSafeFunction tsfn = ThreadSafeFunction::New( - info.Env(), cb, "Test", 0, threadCount, - std::function(FinalizerCallback), testData); + info.Env(), + cb, + "Test", + 0, + threadCount, + std::function(FinalizerCallback), + testData); for (int i = 0; i < threadCount; ++i) { // A copy of the ThreadSafeFunction will go to the thread entry point - testData->threads.push_back( std::thread(entryWithTSFN, tsfn, i) ); + testData->threads.push_back(std::thread(entryWithTSFN, tsfn, i)); } return testData->deferred.Promise(); @@ -70,7 +74,7 @@ static Value TestWithTSFN(const CallbackInfo& info) { // Task instance created for each new std::thread class DelayedTSFNTask { -public: + public: // Each instance has its own tsfn ThreadSafeFunction tsfn; @@ -90,8 +94,7 @@ class DelayedTSFNTask { }; struct TestDataDelayed { - - TestDataDelayed(Promise::Deferred &&deferred) + TestDataDelayed(Promise::Deferred&& deferred) : deferred(std::move(deferred)){}; ~TestDataDelayed() { taskInsts.clear(); }; // Native Promise returned to JavaScript @@ -107,7 +110,7 @@ struct TestDataDelayed { ThreadSafeFunction tsfn = ThreadSafeFunction(); }; -void FinalizerCallbackDelayed(Napi::Env env, TestDataDelayed *finalizeData) { +void FinalizerCallbackDelayed(Napi::Env env, TestDataDelayed* finalizeData) { for (size_t i = 0; i < finalizeData->threads.size(); ++i) { finalizeData->threads[i].join(); } @@ -115,15 +118,19 @@ void FinalizerCallbackDelayed(Napi::Env env, TestDataDelayed *finalizeData) { delete finalizeData; } -static Value TestDelayedTSFN(const CallbackInfo &info) { +static Value TestDelayedTSFN(const CallbackInfo& info) { int threadCount = info[0].As().Int32Value(); Function cb = info[1].As(); - TestDataDelayed *testData = + TestDataDelayed* testData = new TestDataDelayed(Promise::Deferred::New(info.Env())); testData->tsfn = - ThreadSafeFunction::New(info.Env(), cb, "Test", 0, threadCount, + ThreadSafeFunction::New(info.Env(), + cb, + "Test", + 0, + threadCount, std::function( FinalizerCallbackDelayed), testData); @@ -137,7 +144,7 @@ static Value TestDelayedTSFN(const CallbackInfo &info) { } std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); - for (auto &task : testData->taskInsts) { + for (auto& task : testData->taskInsts) { std::lock_guard lk(task->mtx); task->tsfn = testData->tsfn; task->cv.notify_all(); @@ -149,7 +156,7 @@ static Value TestDelayedTSFN(const CallbackInfo &info) { void AcquireFinalizerCallback(Napi::Env env, TestData* finalizeData, TestData* context) { - (void) context; + (void)context; for (size_t i = 0; i < finalizeData->threads.size(); ++i) { finalizeData->threads[i].join(); } @@ -161,13 +168,13 @@ void entryAcquire(ThreadSafeFunction tsfn, int threadId) { tsfn.Acquire(); TestData* testData = tsfn.GetContext(); std::this_thread::sleep_for(std::chrono::milliseconds(std::rand() % 100 + 1)); - tsfn.BlockingCall( [=](Napi::Env env, Function callback) { + tsfn.BlockingCall([=](Napi::Env env, Function callback) { // This lambda runs on the main thread so it's OK to access the variables // `expected_calls` and `mainWantsRelease`. testData->expected_calls--; if (testData->expected_calls == 0 && testData->mainWantsRelease) testData->tsfn.Release(); - callback.Call( { Number::New(env, static_cast(threadId))}); + callback.Call({Number::New(env, static_cast(threadId))}); }); tsfn.Release(); } @@ -182,7 +189,7 @@ static Value CreateThread(const CallbackInfo& info) { ThreadSafeFunction tsfn = testData->tsfn; int threadId = testData->threads.size(); // A copy of the ThreadSafeFunction will go to the thread entry point - testData->threads.push_back( std::thread(entryAcquire, tsfn, threadId) ); + testData->threads.push_back(std::thread(entryAcquire, tsfn, threadId)); return Number::New(info.Env(), threadId); } @@ -198,21 +205,29 @@ static Value TestAcquire(const CallbackInfo& info) { // We pass the test data to the Finalizer for cleanup. The finalizer is // responsible for deleting this data as well. - TestData *testData = new TestData(Promise::Deferred::New(info.Env())); + TestData* testData = new TestData(Promise::Deferred::New(info.Env())); - testData->tsfn = ThreadSafeFunction::New( - env, cb, "Test", 0, 1, testData, - std::function(AcquireFinalizerCallback), - testData); + testData->tsfn = + ThreadSafeFunction::New(env, + cb, + "Test", + 0, + 1, + testData, + std::function( + AcquireFinalizerCallback), + testData); Object result = Object::New(env); - result["createThread"] = Function::New( env, CreateThread, "createThread", testData); - result["stopThreads"] = Function::New( env, StopThreads, "stopThreads", testData); + result["createThread"] = + Function::New(env, CreateThread, "createThread", testData); + result["stopThreads"] = + Function::New(env, StopThreads, "stopThreads", testData); result["promise"] = testData->deferred.Promise(); return result; } -} +} // namespace Object InitThreadSafeFunctionSum(Env env) { Object exports = Object::New(env); diff --git a/test/threadsafe_function/threadsafe_function_unref.cc b/test/threadsafe_function/threadsafe_function_unref.cc index a54620c48..6c278e7ad 100644 --- a/test/threadsafe_function/threadsafe_function_unref.cc +++ b/test/threadsafe_function/threadsafe_function_unref.cc @@ -15,23 +15,23 @@ static Value TestUnref(const CallbackInfo& info) { Function setTimeout = MaybeUnwrap(global.Get("setTimeout")).As(); ThreadSafeFunction* tsfn = new ThreadSafeFunction; - *tsfn = ThreadSafeFunction::New(info.Env(), cb, resource, "Test", 1, 1, [tsfn](Napi::Env /* env */) { - delete tsfn; - }); + *tsfn = ThreadSafeFunction::New( + info.Env(), cb, resource, "Test", 1, 1, [tsfn](Napi::Env /* env */) { + delete tsfn; + }); tsfn->BlockingCall(); - setTimeout.Call( global, { - Function::New(env, [tsfn](const CallbackInfo& info) { - tsfn->Unref(info.Env()); - }), - Number::New(env, 100) - }); + setTimeout.Call( + global, + {Function::New( + env, [tsfn](const CallbackInfo& info) { tsfn->Unref(info.Env()); }), + Number::New(env, 100)}); return info.Env().Undefined(); } -} +} // namespace Object InitThreadSafeFunctionUnref(Env env) { Object exports = Object::New(env); diff --git a/test/thunking_manual.cc b/test/thunking_manual.cc index d52302ea3..a9a0adf37 100644 --- a/test/thunking_manual.cc +++ b/test/thunking_manual.cc @@ -22,64 +22,59 @@ static Napi::Value TestGetter(const Napi::CallbackInfo& /*info*/) { return Napi::Value(); } -static void TestSetter(const Napi::CallbackInfo& /*info*/) { -} +static void TestSetter(const Napi::CallbackInfo& /*info*/) {} class TestClass : public Napi::ObjectWrap { public: - TestClass(const Napi::CallbackInfo& info): - ObjectWrap(info) { - } + TestClass(const Napi::CallbackInfo& info) : ObjectWrap(info) {} static Napi::Value TestClassStaticMethod(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), 42); } - static void TestClassStaticVoidMethod(const Napi::CallbackInfo& /*info*/) { - } + static void TestClassStaticVoidMethod(const Napi::CallbackInfo& /*info*/) {} Napi::Value TestClassInstanceMethod(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), 42); } - void TestClassInstanceVoidMethod(const Napi::CallbackInfo& /*info*/) { - } + void TestClassInstanceVoidMethod(const Napi::CallbackInfo& /*info*/) {} Napi::Value TestClassInstanceGetter(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), 42); } void TestClassInstanceSetter(const Napi::CallbackInfo& /*info*/, - const Napi::Value& /*new_value*/) { - } + const Napi::Value& /*new_value*/) {} static Napi::Function NewClass(Napi::Env env) { - return DefineClass(env, "TestClass", { - // Make sure to check that the deleter gets called. - StaticMethod("staticMethod", TestClassStaticMethod), - // Make sure to check that the deleter gets called. - StaticMethod("staticVoidMethod", TestClassStaticVoidMethod), - // Make sure to check that the deleter gets called. - StaticMethod(Napi::Symbol::New(env, "staticMethod"), - TestClassStaticMethod), - // Make sure to check that the deleter gets called. - StaticMethod(Napi::Symbol::New(env, "staticVoidMethod"), - TestClassStaticVoidMethod), - // Make sure to check that the deleter gets called. - InstanceMethod("instanceMethod", &TestClass::TestClassInstanceMethod), - // Make sure to check that the deleter gets called. - InstanceMethod("instanceVoidMethod", - &TestClass::TestClassInstanceVoidMethod), - // Make sure to check that the deleter gets called. - InstanceMethod(Napi::Symbol::New(env, "instanceMethod"), - &TestClass::TestClassInstanceMethod), - // Make sure to check that the deleter gets called. - InstanceMethod(Napi::Symbol::New(env, "instanceVoidMethod"), - &TestClass::TestClassInstanceVoidMethod), - // Make sure to check that the deleter gets called. - InstanceAccessor("instanceAccessor", - &TestClass::TestClassInstanceGetter, - &TestClass::TestClassInstanceSetter) - }); + return DefineClass( + env, + "TestClass", + {// Make sure to check that the deleter gets called. + StaticMethod("staticMethod", TestClassStaticMethod), + // Make sure to check that the deleter gets called. + StaticMethod("staticVoidMethod", TestClassStaticVoidMethod), + // Make sure to check that the deleter gets called. + StaticMethod(Napi::Symbol::New(env, "staticMethod"), + TestClassStaticMethod), + // Make sure to check that the deleter gets called. + StaticMethod(Napi::Symbol::New(env, "staticVoidMethod"), + TestClassStaticVoidMethod), + // Make sure to check that the deleter gets called. + InstanceMethod("instanceMethod", &TestClass::TestClassInstanceMethod), + // Make sure to check that the deleter gets called. + InstanceMethod("instanceVoidMethod", + &TestClass::TestClassInstanceVoidMethod), + // Make sure to check that the deleter gets called. + InstanceMethod(Napi::Symbol::New(env, "instanceMethod"), + &TestClass::TestClassInstanceMethod), + // Make sure to check that the deleter gets called. + InstanceMethod(Napi::Symbol::New(env, "instanceVoidMethod"), + &TestClass::TestClassInstanceVoidMethod), + // Make sure to check that the deleter gets called. + InstanceAccessor("instanceAccessor", + &TestClass::TestClassInstanceGetter, + &TestClass::TestClassInstanceSetter)}); } }; @@ -91,42 +86,34 @@ static Napi::Value CreateTestObject(const Napi::CallbackInfo& info) { item["testMethod"] = Napi::Function::New(env, TestMethod, "testMethod"); item.DefineProperties({ - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - "accessor_1", - TestGetter), - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - std::string("accessor_1_std_string"), - TestGetter), - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - Napi::String::New(info.Env(), - "accessor_1_js_string"), - TestGetter), - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - "accessor_2", - TestGetter, - TestSetter), - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - std::string("accessor_2_std_string"), - TestGetter, - TestSetter), - // Make sure to check that the deleter gets called. - Napi::PropertyDescriptor::Accessor(env, - item, - Napi::String::New(env, - "accessor_2_js_string"), - TestGetter, - TestSetter), - Napi::PropertyDescriptor::Value("TestClass", TestClass::NewClass(env)), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor(env, item, "accessor_1", TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, item, std::string("accessor_1_std_string"), TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, + item, + Napi::String::New(info.Env(), "accessor_1_js_string"), + TestGetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, item, "accessor_2", TestGetter, TestSetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor(env, + item, + std::string("accessor_2_std_string"), + TestGetter, + TestSetter), + // Make sure to check that the deleter gets called. + Napi::PropertyDescriptor::Accessor( + env, + item, + Napi::String::New(env, "accessor_2_js_string"), + TestGetter, + TestSetter), + Napi::PropertyDescriptor::Value("TestClass", TestClass::NewClass(env)), }); return item; diff --git a/test/typedarray.cc b/test/typedarray.cc index 08c667699..3ff169781 100644 --- a/test/typedarray.cc +++ b/test/typedarray.cc @@ -3,12 +3,16 @@ using namespace Napi; #if defined(NAPI_HAS_CONSTEXPR) -#define NAPI_TYPEDARRAY_NEW(className, env, length, type) className::New(env, length) -#define NAPI_TYPEDARRAY_NEW_BUFFER(className, env, length, buffer, bufferOffset, type) \ +#define NAPI_TYPEDARRAY_NEW(className, env, length, type) \ + className::New(env, length) +#define NAPI_TYPEDARRAY_NEW_BUFFER( \ + className, env, length, buffer, bufferOffset, type) \ className::New(env, length, buffer, bufferOffset) #else -#define NAPI_TYPEDARRAY_NEW(className, env, length, type) className::New(env, length, type) -#define NAPI_TYPEDARRAY_NEW_BUFFER(className, env, length, buffer, bufferOffset, type) \ +#define NAPI_TYPEDARRAY_NEW(className, env, length, type) \ + className::New(env, length, type) +#define NAPI_TYPEDARRAY_NEW_BUFFER( \ + className, env, length, buffer, bufferOffset, type) \ className::New(env, length, buffer, bufferOffset, type) #endif @@ -18,91 +22,160 @@ Value CreateTypedArray(const CallbackInfo& info) { std::string arrayType = info[0].As(); size_t length = info[1].As().Uint32Value(); ArrayBuffer buffer = info[2].As(); - size_t bufferOffset = info[3].IsUndefined() ? 0 : info[3].As().Uint32Value(); + size_t bufferOffset = + info[3].IsUndefined() ? 0 : info[3].As().Uint32Value(); if (arrayType == "int8") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Int8Array, info.Env(), length, napi_int8_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, info.Env(), length, buffer, bufferOffset, - napi_int8_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int8Array, info.Env(), length, napi_int8_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_int8_array); } else if (arrayType == "uint8") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Uint8Array, info.Env(), length, napi_uint8_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Uint8Array, info.Env(), length, buffer, bufferOffset, - napi_uint8_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint8Array, info.Env(), length, napi_uint8_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint8Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_uint8_array); } else if (arrayType == "uint8_clamped") { - return buffer.IsUndefined() ? - Uint8Array::New(info.Env(), length, napi_uint8_clamped_array) : - Uint8Array::New(info.Env(), length, buffer, bufferOffset, napi_uint8_clamped_array); + return buffer.IsUndefined() + ? Uint8Array::New(info.Env(), length, napi_uint8_clamped_array) + : Uint8Array::New(info.Env(), + length, + buffer, + bufferOffset, + napi_uint8_clamped_array); } else if (arrayType == "int16") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Int16Array, info.Env(), length, napi_int16_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Int16Array, info.Env(), length, buffer, bufferOffset, - napi_int16_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int16Array, info.Env(), length, napi_int16_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int16Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_int16_array); } else if (arrayType == "uint16") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Uint16Array, info.Env(), length, napi_uint16_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Uint16Array, info.Env(), length, buffer, bufferOffset, - napi_uint16_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint16Array, info.Env(), length, napi_uint16_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint16Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_uint16_array); } else if (arrayType == "int32") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Int32Array, info.Env(), length, napi_int32_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Int32Array, info.Env(), length, buffer, bufferOffset, - napi_int32_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Int32Array, info.Env(), length, napi_int32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Int32Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_int32_array); } else if (arrayType == "uint32") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Uint32Array, info.Env(), length, napi_uint32_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Uint32Array, info.Env(), length, buffer, bufferOffset, - napi_uint32_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Uint32Array, info.Env(), length, napi_uint32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Uint32Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_uint32_array); } else if (arrayType == "float32") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Float32Array, info.Env(), length, napi_float32_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Float32Array, info.Env(), length, buffer, bufferOffset, - napi_float32_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Float32Array, info.Env(), length, napi_float32_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Float32Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_float32_array); } else if (arrayType == "float64") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(Float64Array, info.Env(), length, napi_float64_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(Float64Array, info.Env(), length, buffer, bufferOffset, - napi_float64_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + Float64Array, info.Env(), length, napi_float64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(Float64Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_float64_array); #if (NAPI_VERSION > 5) } else if (arrayType == "bigint64") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(BigInt64Array, info.Env(), length, napi_bigint64_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(BigInt64Array, info.Env(), length, buffer, bufferOffset, - napi_bigint64_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + BigInt64Array, info.Env(), length, napi_bigint64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(BigInt64Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_bigint64_array); } else if (arrayType == "biguint64") { - return buffer.IsUndefined() ? - NAPI_TYPEDARRAY_NEW(BigUint64Array, info.Env(), length, napi_biguint64_array) : - NAPI_TYPEDARRAY_NEW_BUFFER(BigUint64Array, info.Env(), length, buffer, bufferOffset, - napi_biguint64_array); + return buffer.IsUndefined() + ? NAPI_TYPEDARRAY_NEW( + BigUint64Array, info.Env(), length, napi_biguint64_array) + : NAPI_TYPEDARRAY_NEW_BUFFER(BigUint64Array, + info.Env(), + length, + buffer, + bufferOffset, + napi_biguint64_array); #endif } else { - Error::New(info.Env(), "Invalid typed-array type.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); return Value(); } } Value CreateInvalidTypedArray(const CallbackInfo& info) { - return NAPI_TYPEDARRAY_NEW_BUFFER(Int8Array, info.Env(), 1, ArrayBuffer(), 0, napi_int8_array); + return NAPI_TYPEDARRAY_NEW_BUFFER( + Int8Array, info.Env(), 1, ArrayBuffer(), 0, napi_int8_array); } Value GetTypedArrayType(const CallbackInfo& info) { TypedArray array = info[0].As(); switch (array.TypedArrayType()) { - case napi_int8_array: return String::New(info.Env(), "int8"); - case napi_uint8_array: return String::New(info.Env(), "uint8"); - case napi_uint8_clamped_array: return String::New(info.Env(), "uint8_clamped"); - case napi_int16_array: return String::New(info.Env(), "int16"); - case napi_uint16_array: return String::New(info.Env(), "uint16"); - case napi_int32_array: return String::New(info.Env(), "int32"); - case napi_uint32_array: return String::New(info.Env(), "uint32"); - case napi_float32_array: return String::New(info.Env(), "float32"); - case napi_float64_array: return String::New(info.Env(), "float64"); + case napi_int8_array: + return String::New(info.Env(), "int8"); + case napi_uint8_array: + return String::New(info.Env(), "uint8"); + case napi_uint8_clamped_array: + return String::New(info.Env(), "uint8_clamped"); + case napi_int16_array: + return String::New(info.Env(), "int16"); + case napi_uint16_array: + return String::New(info.Env(), "uint16"); + case napi_int32_array: + return String::New(info.Env(), "int32"); + case napi_uint32_array: + return String::New(info.Env(), "uint32"); + case napi_float32_array: + return String::New(info.Env(), "float32"); + case napi_float64_array: + return String::New(info.Env(), "float64"); #if (NAPI_VERSION > 5) - case napi_bigint64_array: return String::New(info.Env(), "bigint64"); - case napi_biguint64_array: return String::New(info.Env(), "biguint64"); + case napi_bigint64_array: + return String::New(info.Env(), "bigint64"); + case napi_biguint64_array: + return String::New(info.Env(), "biguint64"); #endif - default: return String::New(info.Env(), "invalid"); + default: + return String::New(info.Env(), "invalid"); } } @@ -145,7 +218,8 @@ Value GetTypedArrayElement(const CallbackInfo& info) { return BigInt::New(info.Env(), array.As()[index]); #endif default: - Error::New(info.Env(), "Invalid typed-array type.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); return Value(); } } @@ -168,7 +242,8 @@ void SetTypedArrayElement(const CallbackInfo& info) { array.As()[index] = static_cast(value.Int32Value()); break; case napi_uint16_array: - array.As()[index] = static_cast(value.Uint32Value()); + array.As()[index] = + static_cast(value.Uint32Value()); break; case napi_int32_array: array.As()[index] = value.Int32Value(); @@ -185,27 +260,31 @@ void SetTypedArrayElement(const CallbackInfo& info) { #if (NAPI_VERSION > 5) case napi_bigint64_array: { bool lossless; - array.As()[index] = value.As().Int64Value(&lossless); + array.As()[index] = + value.As().Int64Value(&lossless); break; } case napi_biguint64_array: { bool lossless; - array.As()[index] = value.As().Uint64Value(&lossless); + array.As()[index] = + value.As().Uint64Value(&lossless); break; } #endif default: - Error::New(info.Env(), "Invalid typed-array type.").ThrowAsJavaScriptException(); + Error::New(info.Env(), "Invalid typed-array type.") + .ThrowAsJavaScriptException(); } } -} // end anonymous namespace +} // end anonymous namespace Object InitTypedArray(Env env) { Object exports = Object::New(env); exports["createTypedArray"] = Function::New(env, CreateTypedArray); - exports["createInvalidTypedArray"] = Function::New(env, CreateInvalidTypedArray); + exports["createInvalidTypedArray"] = + Function::New(env, CreateInvalidTypedArray); exports["getTypedArrayType"] = Function::New(env, GetTypedArrayType); exports["getTypedArrayLength"] = Function::New(env, GetTypedArrayLength); exports["getTypedArrayBuffer"] = Function::New(env, GetTypedArrayBuffer); diff --git a/test/version_management.cc b/test/version_management.cc index 39dfeecf4..6496f5700 100644 --- a/test/version_management.cc +++ b/test/version_management.cc @@ -3,25 +3,26 @@ using namespace Napi; Value getNapiVersion(const CallbackInfo& info) { - Napi::Env env = info.Env(); - uint32_t napi_version = VersionManagement::GetNapiVersion(env); - return Number::New(env, napi_version); + Napi::Env env = info.Env(); + uint32_t napi_version = VersionManagement::GetNapiVersion(env); + return Number::New(env, napi_version); } Value getNodeVersion(const CallbackInfo& info) { - Napi::Env env = info.Env(); - const napi_node_version* node_version = VersionManagement::GetNodeVersion(env); - Object version = Object::New(env); - version.Set("major", Number::New(env, node_version->major)); - version.Set("minor", Number::New(env, node_version->minor)); - version.Set("patch", Number::New(env, node_version->patch)); - version.Set("release", String::New(env, node_version->release)); - return version; + Napi::Env env = info.Env(); + const napi_node_version* node_version = + VersionManagement::GetNodeVersion(env); + Object version = Object::New(env); + version.Set("major", Number::New(env, node_version->major)); + version.Set("minor", Number::New(env, node_version->minor)); + version.Set("patch", Number::New(env, node_version->patch)); + version.Set("release", String::New(env, node_version->release)); + return version; } Object InitVersionManagement(Env env) { - Object exports = Object::New(env); - exports["getNapiVersion"] = Function::New(env, getNapiVersion); - exports["getNodeVersion"] = Function::New(env, getNodeVersion); - return exports; + Object exports = Object::New(env); + exports["getNapiVersion"] = Function::New(env, getNapiVersion); + exports["getNodeVersion"] = Function::New(env, getNodeVersion); + return exports; }