From 88bf2739ae5bbec26107ecf4f6d26585eedb36b6 Mon Sep 17 00:00:00 2001 From: Mikeal Rogers Date: Fri, 20 Dec 2019 23:07:58 +0000 Subject: [PATCH] fix: name table not hex encoded --- src/index.js | 10 +++++----- src/int-table.js | 12 ++++++++++++ test/multicodec.spec.js | 2 +- 3 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 src/int-table.js diff --git a/src/index.js b/src/index.js index 0be8211..5486fa2 100644 --- a/src/index.js +++ b/src/index.js @@ -12,8 +12,8 @@ 'use strict' const varint = require('varint') +const intTable = require('./int-table') const codecNameToCodeVarint = require('./varint-table') -const codeToCodecName = require('./name-table') const util = require('./util') exports = module.exports @@ -57,10 +57,10 @@ exports.rmPrefix = (data) => { * @returns {string} */ exports.getCodec = (prefixedData) => { - const code = util.varintBufferDecode(prefixedData) - const codecName = codeToCodecName[code.toString('hex')] + const code = varint.decode(prefixedData) + const codecName = intTable.get(code) if (codecName === undefined) { - throw new Error('Code `0x' + code.toString('hex') + '` not found') + throw new Error(`Code ${code} not found`) } return codecName } @@ -71,7 +71,7 @@ exports.getCodec = (prefixedData) => { * @returns {string} */ exports.getName = (codec) => { - return codeToCodecName[codec.toString(16)] + return intTable.get(codec) } /** diff --git a/src/int-table.js b/src/int-table.js new file mode 100644 index 0000000..98b168a --- /dev/null +++ b/src/int-table.js @@ -0,0 +1,12 @@ +'use strict' +const baseTable = require('./base-table.json') + +// map for hexString -> codecName +const nameTable = new Map() + +for (const encodingName in baseTable) { + const code = baseTable[encodingName] + nameTable.set(code, encodingName) +} + +module.exports = Object.freeze(nameTable) diff --git a/test/multicodec.spec.js b/test/multicodec.spec.js index 6b846e2..439794e 100644 --- a/test/multicodec.spec.js +++ b/test/multicodec.spec.js @@ -99,7 +99,7 @@ describe('multicodec', () => { expect(() => { multicodec.getCodec(prefixedBuf) }).to.throw( - 'Code `0xffee` not found' + 'Code 65518 not found' ) }) })