Skip to content

Commit 047252b

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

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

lib/random-util.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
9+
function onRandomBytes (err, buf) {
10+
randomPending = false;
11+
if (!err) {
12+
randomPool = buf;
13+
randomPoolIdx = 0;
14+
}
15+
}
16+
17+
let randomPending = true;
18+
crypto.randomBytes(RANDOM_POOL_SIZE, onRandomBytes);
19+
20+
function randomFillMask (buffer) {
21+
if (RANDOM_POOL_SIZE - randomPoolIdx < 4) {
22+
return crypto.randomFillSync(buffer, offset, size);
23+
}
24+
25+
buffer[0] = randomPool[randomPoolIdx++];
26+
buffer[1] = randomPool[randomPoolIdx++];
27+
buffer[2] = randomPool[randomPoolIdx++];
28+
buffer[3] = randomPool[randomPoolIdx++];
29+
30+
if (!randomPending && RANDOM_POOL_SIZE - randomPoolIdx < RANDOM_POOL_REFRESH) {
31+
randomPending = true;
32+
crypto.randomBytes(RANDOM_POOL_SIZE, onRandomBytes);
33+
}
34+
35+
return buffer;
36+
}
37+
38+
module.exports = { randomFillMask };

lib/sender.js

Lines changed: 2 additions & 2 deletions
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 { randomFillMask } = require('./random-util');
88

99
const PerMessageDeflate = require('./permessage-deflate');
1010
const { EMPTY_BUFFER } = require('./constants');
@@ -81,7 +81,7 @@ class Sender {
8181

8282
if (!options.mask) return [target, data];
8383

84-
randomFillSync(mask, 0, 4);
84+
randomFillMask(mask);
8585

8686
target[1] |= 0x80;
8787
target[offset - 4] = mask[0];

0 commit comments

Comments
 (0)