Skip to content

Commit

Permalink
src,test: allow creating Function with move-only functor
Browse files Browse the repository at this point in the history
Function::New fails to compile when given a move-only functor. For
example, when constructing a callback function for Promise#then, a
lambda might capture an ObjectReference. Creating a Function for such a
lambda results in a compilation error.

Tweak Function::New to work with move-only functors.

For existing users of Function::New, this commit should not change
behavior.
  • Loading branch information
strager committed Sep 7, 2021
1 parent da2e754 commit 3e5897a
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
Expand Up @@ -14,6 +14,7 @@
#include <cstring>
#include <mutex>
#include <type_traits>
#include <utility>

namespace Napi {

Expand Down Expand Up @@ -2154,7 +2155,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
@@ -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
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 3e5897a

Please sign in to comment.