Skip to content

Commit

Permalink
feat: add codec name to codec code helper
Browse files Browse the repository at this point in the history
Introduce the function `getCodeVarint()` to return a Buffer containing
the Varint encoded codec code of a given codec name. It throws an
error if the codec isn't found.

Reason for this change was the js-cid module that is using the
conversion table directly. If the codec doesn't exist it would throw
error messages that didn't make much sense.
  • Loading branch information
vmx authored and hacdias committed May 30, 2018
1 parent 4ec6375 commit 46e0e02
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
13 changes: 13 additions & 0 deletions test/multicodec.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
)
})
})

0 comments on commit 46e0e02

Please sign in to comment.