From f30b4a763dee06239fe8c0b6fab47e8a240e087a Mon Sep 17 00:00:00 2001 From: Christoph Tavan Date: Fri, 29 May 2020 21:05:51 +0200 Subject: [PATCH] Revert "feat: short version of parsing UUID" This reverts commit d096cc21b14e84f86e2fd7d6bf5068cb1124b157. --- src/uuid-bin.js | 18 ++++++++++++++---- src/v35.js | 22 ++++++++++++++++++---- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/uuid-bin.js b/src/uuid-bin.js index 0a82fd27..f7305adc 100644 --- a/src/uuid-bin.js +++ b/src/uuid-bin.js @@ -39,8 +39,13 @@ switch (version) { assert(name != null, 'v3 name not specified'); assert(namespace != null, 'v3 namespace not specified'); - if (namespace === 'URL') namespace = v3.URL; - if (namespace === 'DNS') namespace = v3.DNS; + if (namespace === 'URL') { + namespace = v3.URL; + } + + if (namespace === 'DNS') { + namespace = v3.DNS; + } console.log(v3(name, namespace)); break; @@ -57,8 +62,13 @@ switch (version) { assert(name != null, 'v5 name not specified'); assert(namespace != null, 'v5 namespace not specified'); - if (namespace === 'URL') namespace = v5.URL; - if (namespace === 'DNS') namespace = v5.DNS; + if (namespace === 'URL') { + namespace = v5.URL; + } + + if (namespace === 'DNS') { + namespace = v5.DNS; + } console.log(v5(name, namespace)); break; diff --git a/src/v35.js b/src/v35.js index a0f68ab6..dc7775fe 100644 --- a/src/v35.js +++ b/src/v35.js @@ -1,15 +1,29 @@ import bytesToUuid from './bytesToUuid.js'; import validate from './validate.js'; -// Char offset to hex pairs in uuid strings -const HEX_PAIRS = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34]; +// Int32 to 4 bytes https://stackoverflow.com/a/12965194/3684944 +function numberToBytes(num, bytes, offset) { + for (let i = 0; i < 4; ++i) { + const byte = num & 0xff; + // Fill the 4 bytes right-to-left. + bytes[offset + 3 - i] = byte; + num = (num - byte) / 256; + } +} function uuidToBytes(uuid) { if (!validate(uuid)) { - throw TypeError('Invalid UUID'); + return []; } - return HEX_PAIRS.map((i) => parseInt(uuid.substr(i, 2), 16)); + const bytes = new Array(16); + + numberToBytes(parseInt(uuid.slice(0, 8), 16), bytes, 0); + numberToBytes(parseInt(uuid.slice(9, 13) + uuid.slice(14, 18), 16), bytes, 4); + numberToBytes(parseInt(uuid.slice(19, 23) + uuid.slice(24, 28), 16), bytes, 8); + numberToBytes(parseInt(uuid.slice(28), 16), bytes, 12); + + return bytes; } function stringToBytes(str) {