diff --git a/src/index.js b/src/index.js index fc51399..11160f3 100644 --- a/src/index.js +++ b/src/index.js @@ -61,3 +61,16 @@ exports.getCodec = (prefixedData) => { const codecName = codeToCodecName[code.toString('hex')] return codecName } + +/** + * Get the code as varint of a codec name. + * @param {string} codecName + * @returns {Buffer} + */ +exports.getCodeVarint = (codecName) => { + const code = codecNameToCodeVarint[codecName] + if (code === undefined) { + throw new Error('Codec `' + codecName + '` not found') + } + return code +} diff --git a/test/multicodec.spec.js b/test/multicodec.spec.js index fb340a7..d34567b 100644 --- a/test/multicodec.spec.js +++ b/test/multicodec.spec.js @@ -28,4 +28,17 @@ describe('multicodec', () => { expect(multicodec.getCodec(prefixedBuf)).to.equal('eth-block') expect(buf).to.eql(multicodec.rmPrefix(prefixedBuf)) }) + + it('returns code via codec name', () => { + const code = multicodec.getCodeVarint('keccak-256') + expect(code).to.eql(Buffer.from('1b', 'hex')) + }) + + it('throws error on unknown codec name when getting the code', () => { + expect(() => { + multicodec.getCodeVarint('this-codec-doesnt-exist') + }).to.throw( + 'Codec `this-codec-doesnt-exist` not found' + ) + }) })