Skip to content

Commit 1c1b8ae

Browse files
committed
lib: support ranges in validateInt32()
This commit adds minimum and maximum value checks to the validateInt32() validator. PR-URL: #20588 Fixes: #20498 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: Weijia Wang <starkwang@126.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent a7fa0db commit 1c1b8ae

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

lib/internal/validators.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,23 @@ function validateAndMaskMode(value, name, def) {
4848
throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
4949
}
5050

51-
function validateInt32(value, name) {
51+
function validateInt32(value, name, min = -2147483648, max = 2147483647) {
52+
// The defaults for min and max correspond to the limits of 32-bit integers.
5253
if (!isInt32(value)) {
5354
let err;
5455
if (typeof value !== 'number') {
5556
err = new ERR_INVALID_ARG_TYPE(name, 'number', value);
5657
} else if (!Number.isInteger(value)) {
5758
err = new ERR_OUT_OF_RANGE(name, 'an integer', value);
5859
} else {
59-
// 2 ** 31 === 2147483648
60-
err = new ERR_OUT_OF_RANGE(name, '> -2147483649 && < 2147483648', value);
60+
err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
6161
}
6262
Error.captureStackTrace(err, validateInt32);
6363
throw err;
64+
} else if (value < min || value > max) {
65+
const err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
66+
Error.captureStackTrace(err, validateInt32);
67+
throw err;
6468
}
6569
}
6670

test/parallel/test-fs-truncate.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ function testFtruncate(cb) {
210210
code: 'ERR_OUT_OF_RANGE',
211211
name: 'RangeError [ERR_OUT_OF_RANGE]',
212212
message: 'The value of "len" is out of range. It must be ' +
213-
`> -2147483649 && < 2147483648. Received ${input}`
213+
`>= -2147483648 && <= 2147483647. Received ${input}`
214214
}
215215
);
216216
});

0 commit comments

Comments
 (0)