Skip to content

Commit

Permalink
Merge pull request #1065 from strager/move-only-functor
Browse files Browse the repository at this point in the history
src,test: allow creating Function with move-only functor
  • Loading branch information
NickNaso authored Sep 17, 2021
2 parents 2b57a4a + 3e5897a commit 2dc1f5b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
3 changes: 2 additions & 1 deletion napi-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <cstring>
#include <mutex>
#include <type_traits>
#include <utility>

namespace Napi {

Expand Down Expand Up @@ -2156,7 +2157,7 @@ inline Function Function::New(napi_env env,
void* data) {
using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr)));
using CbData = details::CallbackData<Callable, ReturnType>;
auto callbackData = new CbData({ cb, data });
auto callbackData = new CbData{std::move(cb), data};

napi_value value;
napi_status status = CreateFunction(env,
Expand Down
20 changes: 20 additions & 0 deletions test/function.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <memory>
#include "napi.h"
#include "test_helper.h"

Expand Down Expand Up @@ -271,5 +272,24 @@ Object InitFunction(Env env) {
exports["callWithFunctionOperator"] =
Function::New<CallWithFunctionOperator>(env);
result["templated"] = exports;

exports = Object::New(env);
exports["lambdaWithNoCapture"] =
Function::New(env, [](const CallbackInfo& info) {
auto env = info.Env();
return Boolean::New(env, true);
});
exports["lambdaWithCapture"] =
Function::New(env, [data = 42](const CallbackInfo& info) {
auto env = info.Env();
return Boolean::New(env, data == 42);
});
exports["lambdaWithMoveOnlyCapture"] = Function::New(
env, [data = std::make_unique<int>(42)](const CallbackInfo& info) {
auto env = info.Env();
return Boolean::New(env, *data == 42);
});
result["lambda"] = exports;

return result;
}
7 changes: 7 additions & 0 deletions test/function.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const assert = require('assert');
module.exports = require('./common').runTest(binding => {
test(binding.function.plain);
test(binding.function.templated);
testLambda(binding.function.lambda);
});

function test(binding) {
Expand Down Expand Up @@ -112,3 +113,9 @@ function test(binding) {
binding.makeCallbackWithInvalidReceiver(() => {});
});
}

function testLambda(binding) {
assert.ok(binding.lambdaWithNoCapture());
assert.ok(binding.lambdaWithCapture());
assert.ok(binding.lambdaWithMoveOnlyCapture());
}

0 comments on commit 2dc1f5b

Please sign in to comment.