-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (43 loc) · 1.12 KB
/
index.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
49
50
51
52
53
54
'use strict'
const XorShift = require('xorshift').constructor
const crypto = require('crypto')
module.exports = function prb (seed) {
const xorshift = new XorShift(from(seed))
return function randomBytes (n) {
const buf = Buffer.allocUnsafe(n)
let offset = 0
while (offset < n) {
let [a, b] = xorshift.randomint()
let used = 0
while (used < 4 && offset < n) {
buf[offset++] = a // ECMAScript engines do `a % Math.pow(2, 8)` for us
a = a >>> 8
used++
}
while (used < 8 && offset < n) {
buf[offset++] = b
b = b >>> 8
used++
}
}
return buf
}
}
// Make a seed for xorshift from a (short) string or buffer.
// TODO: move to a package, shared with pseudo-math-random
function from (seed) {
let buf
if (seed == null) {
buf = crypto.randomBytes(16)
} else if (!seed.length) {
throw new RangeError('Seed length must be > 0')
} else {
buf = crypto.createHash('sha256').update(seed).digest()
}
return [
buf.readUInt32BE(0),
buf.readUInt32BE(4),
buf.readUInt32BE(8),
buf.readUInt32BE(12)
]
}