Skip to content

Commit 82eff23

Browse files
authored
Merge pull request #44 from multiformats/add-method-to-return-codec-names
feat: add method to convert codec names to numbers and back
2 parents 879b0f9 + a18bce9 commit 82eff23

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/index.js

+22
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,28 @@ exports.getCodec = (prefixedData) => {
6565
return codecName
6666
}
6767

68+
/**
69+
* Get the name of the codec.
70+
* @param {number} codec
71+
* @returns {string}
72+
*/
73+
exports.getName = (codec) => {
74+
return codeToCodecName[codec.toString(16)]
75+
}
76+
77+
/**
78+
* Get the code of the codec
79+
* @param {string} name
80+
* @returns {number}
81+
*/
82+
exports.getNumber = (name) => {
83+
const code = codecNameToCodeVarint[name]
84+
if (code === undefined) {
85+
throw new Error('Codec `' + name + '` not found')
86+
}
87+
return util.varintBufferDecode(code)[0]
88+
}
89+
6890
/**
6991
* Get the code of the prefixed data.
7092
* @param {Buffer} prefixedData

test/multicodec.spec.js

+10
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ describe('multicodec', () => {
4646
expect(code).to.eql([0x1b])
4747
})
4848

49+
it('returns the codec name from code', () => {
50+
expect(multicodec.getName(144)).to.eql('eth-block')
51+
expect(multicodec.getName(112)).to.eql('dag-pb')
52+
})
53+
54+
it('returns the codec number from name', () => {
55+
expect(multicodec.getNumber('eth-block')).to.eql(144)
56+
expect(multicodec.getNumber('dag-pb')).to.eql(112)
57+
})
58+
4959
it('throws error on unknown codec name when getting the code', () => {
5060
expect(() => {
5161
multicodec.getCodeVarint('this-codec-doesnt-exist')

0 commit comments

Comments
 (0)