Skip to content

Commit

Permalink
Fix buffer not being modified (uuid v5) (#201)
Browse files Browse the repository at this point in the history
* Fix buffer not being modified

* Add unit tests for v5 buffer

* Handle old node versions for test
  • Loading branch information
Landmaster authored and broofa committed Jun 24, 2017
1 parent c50ac88 commit 8e23981
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1,4 +1,5 @@
*.sw*
.idea/**
.DS_Store
node_modules
package-lock.json
14 changes: 14 additions & 0 deletions test/test.js
Expand Up @@ -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');
}));
});


Expand Down
8 changes: 8 additions & 0 deletions v5.js
Expand Up @@ -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);

Expand All @@ -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);
}
Expand Down

0 comments on commit 8e23981

Please sign in to comment.