lib: support min/max values in validateInteger()

This commit updates validateInteger() in two ways:

- Number.isInteger() is used instead of Number.isSafeInteger().
  This ensures that all integer values are supported.
- Minimum and maximum values are supported. They default to
  the min and max safe integer values, but can be customized.

PR-URL: https://github.com/nodejs/node/pull/28810
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Richard Lau <riclau@uk.ibm.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
cjihrig 2019-07-22 17:44:49 -04:00 committed by Rich Trott
parent 52c5287aca
commit 4fc7cd9bc1

View File

@ -13,6 +13,7 @@ const {
isArrayBufferView
} = require('internal/util/types');
const { signals } = internalBinding('constants').os;
const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;
function isInt32(value) {
return value === (value | 0);
@ -60,12 +61,16 @@ function parseMode(value, name, def) {
throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
}
const validateInteger = hideStackFrames((value, name) => {
if (typeof value !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
if (!Number.isSafeInteger(value))
throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
});
const validateInteger = hideStackFrames(
(value, name, min = MIN_SAFE_INTEGER, max = MAX_SAFE_INTEGER) => {
if (typeof value !== 'number')
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
if (!Number.isInteger(value))
throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
if (value < min || value > max)
throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
}
);
const validateInt32 = hideStackFrames(
(value, name, min = -2147483648, max = 2147483647) => {