-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-initial.js
48 lines (39 loc) · 1.12 KB
/
1-initial.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
// Initial code (before optimizations)
const crypto = require('crypto');
class CryptoRandomPrefetcher {
constructor(bufSize, valueSize) {
if (bufSize % valueSize !== 0) {
throw new RangeError('buffer size must be a multiple of value size');
}
this.buf = crypto.randomBytes(bufSize);
this.pos = 0;
this.vsz = valueSize;
}
// Return Buffer with next `valueSize` random bytes.
next() {
if (this.pos === this.buf.length) {
this.pos = 0;
crypto.randomFillSync(this.buf);
}
const end = this.pos + this.vsz;
const buf = this.buf.slice(this.pos, end);
this.pos = end;
return buf;
}
[Symbol.iterator]() {
return {
[Symbol.iterator]() {
return this;
},
next: () => ({ value: this.next(), done: false }),
};
}
}
const cryptoPrefetcher = (bufSize, valueSize) =>
new CryptoRandomPrefetcher(bufSize, valueSize);
const randPrefetcher = cryptoPrefetcher(4096, 4);
const UINT32_MAX = 0xffffffff;
const cryptoRandom = () =>
randPrefetcher.next().readUInt32LE(0, true) / (UINT32_MAX + 1);
module.exports = { cryptoRandom };