Skip to content

Commit c6ee55b

Browse files
vmxhacdias
authored andcommitted
feat: make adding a custom codec possible
With this change it is possible to add a custom codec via `addCodec()`. Example: const name = 'my-custom-codec' const code = Buffer.from('ffff', 'hex') multicodec.addCodec(name, code)
1 parent 9859a71 commit c6ee55b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/index.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,14 @@ exports.getCodeVarint = (codecName) => {
7777
}
7878
return code
7979
}
80+
81+
/**
82+
* Add a new codec
83+
* @param {string} name Name of the codec
84+
* @param {Buffer} code The code of the codec
85+
* @returns {void}
86+
*/
87+
exports.addCodec = (name, code) => {
88+
codecNameToCodeVarint[name] = util.varintBufferEncode(code)
89+
codeToCodecName[code.toString('hex')] = name
90+
}

test/multicodec.spec.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const dirtyChai = require('dirty-chai')
66
const expect = chai.expect
77
chai.use(dirtyChai)
88
const multicodec = require('../src')
9+
const util = require('../src/util')
910

1011
describe('multicodec', () => {
1112
it('add prefix through multicodec (string)', () => {
@@ -34,6 +35,15 @@ describe('multicodec', () => {
3435
expect(code).to.eql(Buffer.from('1b', 'hex'))
3536
})
3637

38+
it('works with custom codec when getting the code', () => {
39+
const name = 'my-custom-codec1'
40+
const code = Buffer.from('ffff', 'hex')
41+
multicodec.addCodec(name, code)
42+
43+
const codeVarint = multicodec.getCodeVarint(name)
44+
expect(util.varintBufferDecode(codeVarint)).to.deep.eql(code)
45+
})
46+
3747
it('throws error on unknown codec name when getting the code', () => {
3848
expect(() => {
3949
multicodec.getCodeVarint('this-codec-doesnt-exist')
@@ -42,6 +52,27 @@ describe('multicodec', () => {
4252
)
4353
})
4454

55+
it('works with custom codec when getting the codec', () => {
56+
const name = 'my-custom-codec2'
57+
const code = Buffer.from('ffff', 'hex')
58+
multicodec.addCodec(name, code)
59+
60+
const buf = Buffer.from('hey')
61+
const prefixedBuf = multicodec.addPrefix(name, buf)
62+
expect(multicodec.getCodec(prefixedBuf)).to.eql(name)
63+
})
64+
65+
it('throws error on unknown codec when adding as prefix', () => {
66+
const name = 'this-codec-doesnt-exist'
67+
68+
const buf = Buffer.from('hey')
69+
expect(() => {
70+
multicodec.addPrefix(name, buf)
71+
}).to.throw(
72+
'multicodec not recognized'
73+
)
74+
})
75+
4576
it('throws error on unknown codec name when getting the codec', () => {
4677
const code = Buffer.from('ffee', 'hex')
4778

0 commit comments

Comments
 (0)