slightly improves performance in randBits()
- only calculates (bitLength % 8) once - uses const where possible
This commit is contained in:
parent
36d9786b3d
commit
155dd49434
|
@ -400,13 +400,14 @@ export function randBits(bitLength, forceLength = false) {
|
||||||
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
|
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
|
||||||
|
|
||||||
const byteLength = Math.ceil(bitLength / 8);
|
const byteLength = Math.ceil(bitLength / 8);
|
||||||
let rndBytes = randBytesSync(byteLength, false);
|
const rndBytes = randBytesSync(byteLength, false);
|
||||||
if (bitLength % 8) {
|
const bitLengthMod8 = bitLength % 8;
|
||||||
|
if (bitLengthMod8) {
|
||||||
// Fill with 0's the extra bits
|
// Fill with 0's the extra bits
|
||||||
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1);
|
rndBytes[0] = rndBytes[0] & (2 ** bitLengthMod8 - 1);
|
||||||
}
|
}
|
||||||
if (forceLength) {
|
if (forceLength) {
|
||||||
let mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128;
|
const mask = bitLengthMod8 ? 2 ** (bitLengthMod8 - 1) : 128;
|
||||||
rndBytes[0] = rndBytes[0] | mask;
|
rndBytes[0] = rndBytes[0] | mask;
|
||||||
}
|
}
|
||||||
return rndBytes;
|
return rndBytes;
|
||||||
|
|
Loading…
Reference in New Issue