Skip to content

Commit bf4af0d

Browse files
authored
feat: improve v4 performance by reusing random number array (#435)
* add test for return value of v4 in case of passing a buffer
1 parent e156415 commit bf4af0d

File tree

4 files changed

+15
-11
lines changed

4 files changed

+15
-11
lines changed

README_js.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ runmd.onRequire = (path) => {
88
runmd.Date.now = () => 1551914748172;
99

1010
let seed = 0xdefaced;
11-
require('crypto').randomBytes = function () {
12-
const a = [];
13-
for (let i = 0; i < 16; i++) a.push((seed = (seed * 0x41a7) & 0x7fffffff) & 0xff);
11+
require('crypto').randomFillSync = function (a) {
12+
for (let i = 0; i < 16; i++) a[i] = (seed = (seed * 0x41a7) & 0x7fffffff) & 0xff;
1413
return a;
1514
};
1615
```

src/rng.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import crypto from 'crypto';
22

3+
const rnds8 = new Uint8Array(16);
4+
35
export default function rng() {
4-
return crypto.randomBytes(16);
6+
return crypto.randomFillSync(rnds8);
57
}

src/v4.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@ import rng from './rng.js';
22
import bytesToUuid from './bytesToUuid.js';
33

44
function v4(options, buf, offset) {
5-
const i = (buf && offset) || 0;
6-
75
if (typeof options === 'string') {
8-
buf = options === 'binary' ? new Uint32Array(16) : null;
6+
buf = options === 'binary' ? new Uint8Array(16) : null;
97
options = null;
108
}
119

@@ -19,12 +17,16 @@ function v4(options, buf, offset) {
1917

2018
// Copy bytes to buffer, if provided
2119
if (buf) {
22-
for (let ii = 0; ii < 16; ++ii) {
23-
buf[i + ii] = rnds[ii];
20+
const start = offset || 0;
21+
22+
for (let i = 0; i < 16; ++i) {
23+
buf[start + i] = rnds[i];
2424
}
25+
26+
return buf;
2527
}
2628

27-
return buf || bytesToUuid(rnds);
29+
return bytesToUuid(rnds);
2830
}
2931

3032
export default v4;

test/unit/v4.test.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,14 @@ describe('v4', () => {
4545

4646
test('fills one UUID into a buffer as expected', () => {
4747
const buffer = [];
48-
v4(
48+
const result = v4(
4949
{
5050
random: randomBytesFixture,
5151
},
5252
buffer,
5353
);
5454
assert.deepEqual(buffer, expectedBytes);
55+
assert.strictEqual(buffer, result);
5556
});
5657

5758
test('fills two UUIDs into a buffer as expected', () => {

0 commit comments

Comments
 (0)