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' ) }) })