-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
crypto: add randomInt function #34600
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
Changes from all commits
c7e3d0b
c068dc4
c83e6a9
e746f6c
f8e9397
d6df4b9
2cb022f
ca5d07b
b7a1838
b220b3c
e62fe80
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ | |
const { | ||
MathMin, | ||
NumberIsNaN, | ||
NumberIsSafeInteger | ||
} = primordials; | ||
|
||
const { AsyncWrap, Providers } = internalBinding('async_wrap'); | ||
|
@@ -119,6 +120,82 @@ function randomFill(buf, offset, size, cb) { | |
_randomBytes(buf, offset, size, wrap); | ||
} | ||
|
||
// Largest integer we can read from a buffer. | ||
// e.g.: Buffer.from("ff".repeat(6), "hex").readUIntBE(0, 6); | ||
const RAND_MAX = 0xFFFF_FFFF_FFFF; | ||
|
||
// Generates an integer in [min, max) range where min is inclusive and max is | ||
// exclusive. | ||
function randomInt(min, max, cb) { | ||
jasnell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Detect optional min syntax | ||
// randomInt(max) | ||
// randomInt(max, cb) | ||
const minNotSpecified = typeof max === 'undefined' || | ||
typeof max === 'function'; | ||
|
||
if (minNotSpecified) { | ||
cb = max; | ||
max = min; | ||
min = 0; | ||
} | ||
|
||
const isSync = typeof cb === 'undefined'; | ||
if (!isSync && typeof cb !== 'function') { | ||
throw new ERR_INVALID_CALLBACK(cb); | ||
} | ||
if (!NumberIsSafeInteger(min)) { | ||
throw new ERR_INVALID_ARG_TYPE('min', 'safe integer', min); | ||
} | ||
if (!NumberIsSafeInteger(max)) { | ||
throw new ERR_INVALID_ARG_TYPE('max', 'safe integer', max); | ||
} | ||
addaleax marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!(max >= min)) { | ||
throw new ERR_OUT_OF_RANGE('max', `>= ${min}`, max); | ||
} | ||
|
||
// First we generate a random int between [0..range) | ||
const range = max - min; | ||
|
||
if (!(range <= RAND_MAX)) { | ||
addaleax marked this conversation as resolved.
Show resolved
Hide resolved
|
||
throw new ERR_OUT_OF_RANGE(`max${minNotSpecified ? '' : ' - min'}`, | ||
`<= ${RAND_MAX}`, range); | ||
} | ||
jasnell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const excess = RAND_MAX % range; | ||
const randLimit = RAND_MAX - excess; | ||
|
||
if (isSync) { | ||
// Sync API | ||
while (true) { | ||
jasnell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const x = randomBytes(6).readUIntBE(0, 6); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Performance suggestion: allocate a buffer once with (I recognize that on average we'll get lucky 50% or more on the first try so consider this a take-it-or-leave-it suggestion, not a must.) |
||
// If x > (maxVal - (maxVal % range)), we will get "modulo bias" | ||
if (x > randLimit) { | ||
// Try again | ||
continue; | ||
} | ||
tniessen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const n = (x % range) + min; | ||
return n; | ||
} | ||
} else { | ||
// Async API | ||
const pickAttempt = () => { | ||
randomBytes(6, (err, bytes) => { | ||
if (err) return cb(err); | ||
const x = bytes.readUIntBE(0, 6); | ||
// If x > (maxVal - (maxVal % range)), we will get "modulo bias" | ||
if (x > randLimit) { | ||
// Try again | ||
return pickAttempt(); | ||
} | ||
const n = (x % range) + min; | ||
cb(null, n); | ||
}); | ||
}; | ||
|
||
pickAttempt(); | ||
} | ||
} | ||
|
||
function handleError(ex, buf) { | ||
if (ex) throw ex; | ||
return buf; | ||
|
@@ -127,5 +204,6 @@ function handleError(ex, buf) { | |
module.exports = { | ||
randomBytes, | ||
randomFill, | ||
randomFillSync | ||
randomFillSync, | ||
randomInt | ||
}; |
Uh oh!
There was an error while loading. Please reload this page.