Skip to content

Commit ab110e3

Browse files
committed
feat: add convenience function for getting the codec code
It's not possible to get the varint encoding from a code as well es getting the code from a varint encoded array-like structure.
1 parent 1c43120 commit ab110e3

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/index.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ exports.getCodec = (prefixedData) => {
6565
return codecName
6666
}
6767

68+
/**
69+
* Get the code of the prefixed data.
70+
* @param {Buffer} prefixedData
71+
* @returns {number}
72+
*/
73+
exports.getCode = (prefixedData) => {
74+
return varint.decode(prefixedData)
75+
}
76+
6877
/**
6978
* Get the code as varint of a codec name.
7079
* @param {string} codecName
@@ -78,6 +87,15 @@ exports.getCodeVarint = (codecName) => {
7887
return code
7988
}
8089

90+
/**
91+
* Get the varint of a code.
92+
* @param {Number} code
93+
* @returns {Array.<number>}
94+
*/
95+
exports.getVarint = (code) => {
96+
return varint.encode(code)
97+
}
98+
8199
// Make the constants top-level constants
82100
const constants = require('./constants')
83101
Object.assign(exports, constants)

test/multicodec.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ describe('multicodec', () => {
3434
expect(code).to.eql(Buffer.from('1b', 'hex'))
3535
})
3636

37+
it('returns code from prefixed data', () => {
38+
const buf = Buffer.from('hey')
39+
const prefixedBuf = multicodec.addPrefix('dag-cbor', buf)
40+
const code = multicodec.getCode(prefixedBuf)
41+
expect(code).to.eql(multicodec.DAG_CBOR)
42+
})
43+
44+
it('returns varint from code', () => {
45+
const code = multicodec.getVarint(multicodec.KECCAK_256)
46+
expect(code).to.eql([0x1b])
47+
})
48+
3749
it('throws error on unknown codec name when getting the code', () => {
3850
expect(() => {
3951
multicodec.getCodeVarint('this-codec-doesnt-exist')

0 commit comments

Comments
 (0)