Skip to content

src,test: allow creating Function with move-only functor #1065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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
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());
}