Skip to content

Commit

Permalink
feat: improve v4 performance by reusing random number array (#435)
Browse files Browse the repository at this point in the history
* add test for return value of v4 in case of passing a buffer
  • Loading branch information
awwit authored May 6, 2020
1 parent e156415 commit bf4af0d
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 11 deletions.
5 changes: 2 additions & 3 deletions README_js.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ runmd.onRequire = (path) => {
runmd.Date.now = () => 1551914748172;

let seed = 0xdefaced;
require('crypto').randomBytes = function () {
const a = [];
for (let i = 0; i < 16; i++) a.push((seed = (seed * 0x41a7) & 0x7fffffff) & 0xff);
require('crypto').randomFillSync = function (a) {
for (let i = 0; i < 16; i++) a[i] = (seed = (seed * 0x41a7) & 0x7fffffff) & 0xff;
return a;
};
```
Expand Down
4 changes: 3 additions & 1 deletion src/rng.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import crypto from 'crypto';

const rnds8 = new Uint8Array(16);

export default function rng() {
return crypto.randomBytes(16);
return crypto.randomFillSync(rnds8);
}
14 changes: 8 additions & 6 deletions src/v4.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import rng from './rng.js';
import bytesToUuid from './bytesToUuid.js';

function v4(options, buf, offset) {
const i = (buf && offset) || 0;

if (typeof options === 'string') {
buf = options === 'binary' ? new Uint32Array(16) : null;
buf = options === 'binary' ? new Uint8Array(16) : null;
options = null;
}

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

// Copy bytes to buffer, if provided
if (buf) {
for (let ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
const start = offset || 0;

for (let i = 0; i < 16; ++i) {
buf[start + i] = rnds[i];
}

return buf;
}

return buf || bytesToUuid(rnds);
return bytesToUuid(rnds);
}

export default v4;
3 changes: 2 additions & 1 deletion test/unit/v4.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ describe('v4', () => {

test('fills one UUID into a buffer as expected', () => {
const buffer = [];
v4(
const result = v4(
{
random: randomBytesFixture,
},
buffer,
);
assert.deepEqual(buffer, expectedBytes);
assert.strictEqual(buffer, result);
});

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

0 comments on commit bf4af0d

Please sign in to comment.