From 8e2398111bc2e55c242502b95ac3bfd9fd4685f2 Mon Sep 17 00:00:00 2001 From: Thanh-Phuong Date: Sat, 24 Jun 2017 00:11:52 -0500 Subject: [PATCH] Fix buffer not being modified (uuid v5) (#201) * Fix buffer not being modified * Add unit tests for v5 buffer * Handle old node versions for test --- .gitignore | 1 + test/test.js | 14 ++++++++++++++ v5.js | 8 ++++++++ 3 files changed, 23 insertions(+) diff --git a/.gitignore b/.gitignore index 9a1ad138c..faf9dfb61 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.sw* +.idea/** .DS_Store node_modules package-lock.json diff --git a/test/test.js b/test/test.js index 35387414d..56b13e3be 100644 --- a/test/test.js +++ b/test/test.js @@ -70,6 +70,20 @@ test('v5', function() { assert.equal(v5('hello.example.com', v5.DNS), 'fdda765f-fc57-5604-a269-52a7df8164ec'); assert.equal(v5('http://example.com/hello', v5.URL), '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'); assert.equal(v5('hello', '0f5abcd1-c194-47f3-905b-2df7263a084b'), '90123e1c-7512-523e-bb28-76fab9f2f73d'); + + // test the buffer functionality + var buf = new Array(16); + var testBuf = [0xfd, 0xda, 0x76, 0x5f, 0xfc, 0x57, 0x56, 0x04, 0xa2, 0x69, 0x52, 0xa7, 0xdf, 0x81, 0x64, 0xec]; + v5('hello.example.com', v5.DNS, buf); + assert.ok(buf.length === testBuf.length && buf.every(function (elem, idx) { return elem === testBuf[idx]; })); + + // test offsets as well + buf = new Array(19); + for (var i=0; i<3; ++i) buf[i] = 'landmaster'; + v5('hello.example.com', v5.DNS, buf, 3); + assert.ok(buf.length === testBuf.length+3 && buf.every(function (elem, idx) { + return (idx >= 3) ? (elem === testBuf[idx-3]) : (elem === 'landmaster'); + })); }); diff --git a/v5.js b/v5.js index 39cc35e7c..07eaf7477 100644 --- a/v5.js +++ b/v5.js @@ -21,6 +21,8 @@ function stringToBytes(str) { } function v5(name, namespace, buf, offset) { + var off = buf && offset || 0; + if (typeof(name) == 'string') name = stringToBytes(name); if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace); @@ -31,6 +33,12 @@ function v5(name, namespace, buf, offset) { var bytes = sha1(namespace.concat(name)); bytes[6] = (bytes[6] & 0x0f) | 0x50; bytes[8] = (bytes[8] & 0x3f) | 0x80; + + if (buf) { + for (var idx = 0; idx < 16; ++idx) { + buf[off+idx] = bytes[idx]; + } + } return buf || bytesToUuid(bytes); }