Skip to content

Commit 4f3bbfa

Browse files
Gabriel Schulhoftargos
Gabriel Schulhof
authored andcommitted
n-api: test uint32 truncation
Re: nodejs/abi-stable-node#55 (comment) PR-URL: #21722 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent 2770778 commit 4f3bbfa

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

test/addons-napi/test_number/test.js

+14
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,20 @@ testNumber(Number.POSITIVE_INFINITY);
3535
testNumber(Number.NEGATIVE_INFINITY);
3636
testNumber(Number.NaN);
3737

38+
function testUint32(input, expected = input) {
39+
assert.strictEqual(expected, test_number.TestUint32Truncation(input));
40+
}
41+
42+
// Test zero
43+
testUint32(0.0, 0);
44+
testUint32(-0.0, 0);
45+
46+
// Test overflow scenarios
47+
testUint32(4294967295);
48+
testUint32(4294967296, 0);
49+
testUint32(4294967297, 1);
50+
testUint32(17 * 4294967296 + 1, 1);
51+
3852
// validate documented behavior when value is retrieved as 32-bit integer with
3953
// `napi_get_value_int32`
4054
function testInt32(input, expected = input) {

test/addons-napi/test_number/test_number.c

+23
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,28 @@ static napi_value Test(napi_env env, napi_callback_info info) {
2323
return output;
2424
}
2525

26+
static napi_value TestUint32Truncation(napi_env env, napi_callback_info info) {
27+
size_t argc = 1;
28+
napi_value args[1];
29+
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
30+
31+
NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments");
32+
33+
napi_valuetype valuetype0;
34+
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
35+
36+
NAPI_ASSERT(env, valuetype0 == napi_number,
37+
"Wrong type of arguments. Expects a number as first argument.");
38+
39+
uint32_t input;
40+
NAPI_CALL(env, napi_get_value_uint32(env, args[0], &input));
41+
42+
napi_value output;
43+
NAPI_CALL(env, napi_create_uint32(env, input, &output));
44+
45+
return output;
46+
}
47+
2648
static napi_value TestInt32Truncation(napi_env env, napi_callback_info info) {
2749
size_t argc = 1;
2850
napi_value args[1];
@@ -71,6 +93,7 @@ static napi_value Init(napi_env env, napi_value exports) {
7193
napi_property_descriptor descriptors[] = {
7294
DECLARE_NAPI_PROPERTY("Test", Test),
7395
DECLARE_NAPI_PROPERTY("TestInt32Truncation", TestInt32Truncation),
96+
DECLARE_NAPI_PROPERTY("TestUint32Truncation", TestUint32Truncation),
7497
DECLARE_NAPI_PROPERTY("TestInt64Truncation", TestInt64Truncation),
7598
};
7699

0 commit comments

Comments
 (0)