Skip to content

Commit a18bce9

Browse files
committed
feat: add method to convert codec names to numbers and back
Since ipld/js-ipld@108aef0 codec names have started being passed around by `js-ipld` as numbers instead of strings. From a DX perspective it's still quite nice to use human-readable strings instead of numbers but at some point you have to convert between them so this PR adds methods to get a codec name based on a number and a number based on a name.
1 parent 879b0f9 commit a18bce9

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Diff for: 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

Diff for: 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)