Skip to content

Commit

Permalink
feat: add convenience function for getting the codec code
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
vmx committed Jan 18, 2019
1 parent 1c43120 commit ab110e3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ exports.getCodec = (prefixedData) => {
return codecName
}

/**
* Get the code of the prefixed data.
* @param {Buffer} prefixedData
* @returns {number}
*/
exports.getCode = (prefixedData) => {
return varint.decode(prefixedData)
}

/**
* Get the code as varint of a codec name.
* @param {string} codecName
Expand All @@ -78,6 +87,15 @@ exports.getCodeVarint = (codecName) => {
return code
}

/**
* Get the varint of a code.
* @param {Number} code
* @returns {Array.<number>}
*/
exports.getVarint = (code) => {
return varint.encode(code)
}

// Make the constants top-level constants
const constants = require('./constants')
Object.assign(exports, constants)
Expand Down
12 changes: 12 additions & 0 deletions test/multicodec.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ describe('multicodec', () => {
expect(code).to.eql(Buffer.from('1b', 'hex'))
})

it('returns code from prefixed data', () => {
const buf = Buffer.from('hey')
const prefixedBuf = multicodec.addPrefix('dag-cbor', buf)
const code = multicodec.getCode(prefixedBuf)
expect(code).to.eql(multicodec.DAG_CBOR)
})

it('returns varint from code', () => {
const code = multicodec.getVarint(multicodec.KECCAK_256)
expect(code).to.eql([0x1b])
})

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

0 comments on commit ab110e3

Please sign in to comment.