Skip to content

Commit

Permalink
src: add support for addon instance data
Browse files Browse the repository at this point in the history
Support `napi_get_instance_data()` and `napi_set_instance_data()`.

Fixes: nodejs#654
  • Loading branch information
Gabriel Schulhof committed Feb 4, 2020
1 parent a71082f commit d0024e2
Show file tree
Hide file tree
Showing 7 changed files with 150 additions and 0 deletions.
25 changes: 25 additions & 0 deletions napi-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,31 @@ inline Value Env::RunScript(String script) {
return Value(_env, result);
}

#ifdef NAPI_EXPERIMENTAL
template <typename T, Env::Finalizer<T> fini = Env::DefaultFini<T>>
inline void Env::SetInstanceData(T* data) {
napi_status status =
napi_set_instance_data(_env, data, [](napi_env, void* data, void*) {
fini(static_cast<T*>(data));
}, nullptr);
NAPI_THROW_IF_FAILED_VOID(_env, status);
}

template <typename T>
inline T* Env::GetInstanceData() {
void* data = nullptr;

napi_status status = napi_get_instance_data(_env, &data);
NAPI_THROW_IF_FAILED(_env, status, nullptr);

return static_cast<T*>(data);
}

template <typename T> void Env::DefaultFini(T* data) {
delete data;
}
#endif // NAPI_EXPERIMENTAL

////////////////////////////////////////////////////////////////////////////////
// Value class
////////////////////////////////////////////////////////////////////////////////
Expand Down
11 changes: 11 additions & 0 deletions napi.h
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ namespace Napi {
///
/// In the V8 JavaScript engine, a N-API environment approximately corresponds to an Isolate.
class Env {
#ifdef NAPI_EXPERIMENTAL
private:
template <typename T> static void DefaultFini(T* data);
#endif
public:
Env(napi_env env);

Expand All @@ -188,6 +192,13 @@ namespace Napi {
Value RunScript(const std::string& utf8script);
Value RunScript(String script);

#ifdef NAPI_EXPERIMENTAL
template <typename T> using Finalizer = void (*)(T*);
template <typename T, Finalizer<T> fini = Env::DefaultFini<T>>
void SetInstanceData(T* data);
template <typename T> T* GetInstanceData();
#endif

private:
napi_env _env;
};
Expand Down
75 changes: 75 additions & 0 deletions test/addon_data.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include <stdio.h>
#define NAPI_EXPERIMENTAL
#include "napi.h"

// An overly elaborate way of exposing a boolean value to JS:
// 0. The native boolean is stored in an instance of the `Addon` class, which is
// itself stored on the heap on the `napi_env` using the APIs under test.
// 1. A property descriptor is provided on the `exports` object, for which
// * The get accessor returns an instance of the `VerboseIndicator` class.
// * The set accessor accepts a boolean and stores it on the `napi_env`.
// 2. A persistent reference to the `VerboseIndicator` class is stored on the
// `napi_env` along with the boolean. Each instance of the class has a
// property served by two property descriptors:
// * The get accessor returns the boolean stored on the `napi_env`.
// * The set accessor accepts a boolean and stores it on the `napi_env`.

class Addon {
public:
class VerboseIndicator : public Napi::ObjectWrap<VerboseIndicator> {
public:
VerboseIndicator(const Napi::CallbackInfo& info):
Napi::ObjectWrap<VerboseIndicator>(info) {
info.This().As<Napi::Object>()["verbose"] =
Napi::Boolean::New(info.Env(),
info.Env().GetInstanceData<Addon>()->verbose);
}

Napi::Value Getter(const Napi::CallbackInfo& info) {
return Napi::Boolean::New(info.Env(),
info.Env().GetInstanceData<Addon>()->verbose);
}

void Setter(const Napi::CallbackInfo& info, const Napi::Value& val) {
info.Env().GetInstanceData<Addon>()->verbose = val.As<Napi::Boolean>();
}

static Napi::FunctionReference Init(Napi::Env env) {
return Napi::Persistent(DefineClass(env, "VerboseIndicator", {
InstanceAccessor<
&VerboseIndicator::Getter,
&VerboseIndicator::Setter>("verbose")
}));
}
};

Addon(Napi::Env env): VerboseIndicator(VerboseIndicator::Init(env)) {}

~Addon() {
if (verbose) {
fprintf(stderr, "addon_data: Addon::~Addon\n");
}
}

bool verbose = false;
Napi::FunctionReference VerboseIndicator;
};

static Napi::Value Getter(const Napi::CallbackInfo& info) {
return info.Env().GetInstanceData<Addon>()->VerboseIndicator.New({});
}

static void Setter(const Napi::CallbackInfo& info) {
info.Env().GetInstanceData<Addon>()->verbose = info[0].As<Napi::Boolean>();
}

Napi::Object InitAddonData(Napi::Env env) {
env.SetInstanceData(new Addon(env));
Napi::Object result = Napi::Object::New(env);

result.DefineProperties({
Napi::PropertyDescriptor::Accessor<Getter, Setter>("verbose"),
});

return result;
}
35 changes: 35 additions & 0 deletions test/addon_data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';
const buildType = process.config.target_defaults.default_configuration;
const assert = require('assert');
const { spawn } = require('child_process');
const readline = require('readline');
const path = require('path');

test(path.resolve(__dirname, `./build/${buildType}/binding.node`));
test(path.resolve(__dirname, `./build/${buildType}/binding_noexcept.node`));

function test(bindingName) {
const binding = require(bindingName);

// Make sure it is possible to get/set instance data.
assert.strictEqual(binding.addon_data.verbose.verbose, false);
binding.addon_data.verbose = true;
assert.strictEqual(binding.addon_data.verbose.verbose, true);
binding.addon_data.verbose = false;
assert.strictEqual(binding.addon_data.verbose.verbose, false);

// Make sure the instance data finalizer is called at process exit.
const child = spawn(process.execPath, [
'-e',
`require('${bindingName}').addon_data.verbose = true;`
]);
let foundMessage = false;
readline
.createInterface({ input: child.stderr })
.on('line', (line) => {
if (line.match('addon_data: Addon::~Addon')) {
foundMessage = true;
}
})
.on('close', () => assert.strictEqual(foundMessage, true));
}
2 changes: 2 additions & 0 deletions test/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using namespace Napi;

Object InitAddonData(Env env);
Object InitArrayBuffer(Env env);
Object InitAsyncContext(Env env);
#if (NAPI_VERSION > 3)
Expand Down Expand Up @@ -57,6 +58,7 @@ Object InitVersionManagement(Env env);
Object InitThunkingManual(Env env);

Object Init(Env env, Object exports) {
exports.Set("addon_data", InitAddonData(env));
exports.Set("arraybuffer", InitArrayBuffer(env));
exports.Set("asynccontext", InitAsyncContext(env));
#if (NAPI_VERSION > 3)
Expand Down
1 change: 1 addition & 0 deletions test/binding.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
'target_defaults': {
'includes': ['../common.gypi'],
'sources': [
'addon_data.cc',
'arraybuffer.cc',
'asynccontext.cc',
'asyncprogressworker.cc',
Expand Down
1 change: 1 addition & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ process.config.target_defaults.default_configuration =
// FIXME: We might need a way to load test modules automatically without
// explicit declaration as follows.
let testModules = [
'addon_data',
'arraybuffer',
'asynccontext',
'asyncprogressworker',
Expand Down

0 comments on commit d0024e2

Please sign in to comment.