Skip to content

Commit cffcc05

Browse files
committed
perf: use a random pool
1 parent c82b087 commit cffcc05

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/random-util.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
3+
const RANDOM_POOL_SIZE = 8192;
4+
const RANDOM_POOL_REFRESH = 1024;
5+
6+
let randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
7+
let randomPoolIdx = RANDOM_POOL_SIZE;
8+
let randomPending = true;
9+
10+
function onRandomBytes (err, buf) {
11+
randomPending = false;
12+
if (!err) {
13+
randomPool = buf;
14+
randomPoolIdx = 0;
15+
}
16+
}
17+
18+
crypto.randomBytes(RANDOM_POOL_SIZE, onRandomBytes);
19+
20+
function randomFillSync (buffer, offset, size) {
21+
if (RANDOM_POOL_SIZE - randomPoolIdx < size) {
22+
return crypto.randomFillSync(buffer, offset, size);
23+
}
24+
25+
randomPool.copy(buffer, offset, randomPoolIdx, randomPoolIdx + size);
26+
randomPoolIdx += size;
27+
28+
if (!randomPending && RANDOM_POOL_SIZE - randomPoolIdx < RANDOM_POOL_REFRESH) {
29+
randomPending = true;
30+
crypto.randomBytes(RANDOM_POOL_SIZE, onRandomBytes);
31+
}
32+
33+
return buffer;
34+
}
35+
36+
module.exports = { randomFillSync };

lib/sender.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
const net = require('net');
66
const tls = require('tls');
7-
const { randomFillSync } = require('crypto');
7+
const { randomFillSync } = require('./random-util');
88

99
const PerMessageDeflate = require('./permessage-deflate');
1010
const { EMPTY_BUFFER } = require('./constants');

0 commit comments

Comments
 (0)