Skip to content

Commit

Permalink
Merge pull request #44 from multiformats/add-method-to-return-codec-n…
Browse files Browse the repository at this point in the history
…ames

feat: add method to convert codec names to numbers and back
  • Loading branch information
hacdias authored May 11, 2019
2 parents 879b0f9 + a18bce9 commit 82eff23
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,28 @@ exports.getCodec = (prefixedData) => {
return codecName
}

/**
* Get the name of the codec.
* @param {number} codec
* @returns {string}
*/
exports.getName = (codec) => {
return codeToCodecName[codec.toString(16)]
}

/**
* Get the code of the codec
* @param {string} name
* @returns {number}
*/
exports.getNumber = (name) => {
const code = codecNameToCodeVarint[name]
if (code === undefined) {
throw new Error('Codec `' + name + '` not found')
}
return util.varintBufferDecode(code)[0]
}

/**
* Get the code of the prefixed data.
* @param {Buffer} prefixedData
Expand Down
10 changes: 10 additions & 0 deletions test/multicodec.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ describe('multicodec', () => {
expect(code).to.eql([0x1b])
})

it('returns the codec name from code', () => {
expect(multicodec.getName(144)).to.eql('eth-block')
expect(multicodec.getName(112)).to.eql('dag-pb')
})

it('returns the codec number from name', () => {
expect(multicodec.getNumber('eth-block')).to.eql(144)
expect(multicodec.getNumber('dag-pb')).to.eql(112)
})

it('throws error on unknown codec name when getting the code', () => {
expect(() => {
multicodec.getCodeVarint('this-codec-doesnt-exist')
Expand Down

0 comments on commit 82eff23

Please sign in to comment.