Skip to content

Commit

Permalink
feat: add optional offset param to varint.decode (#201)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gozala authored Sep 20, 2022
1 parent f2664fb commit 1e1b583
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/varint.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import varint from '../vendor/varint.js'

/**
* @param {Uint8Array} data
* @param {number} [offset=0]
* @returns {[number, number]}
*/
export const decode = (data) => {
const code = varint.decode(data)
export const decode = (data, offset = 0) => {
const code = varint.decode(data, offset)
return [code, varint.decode.bytes]
}

Expand Down
28 changes: 28 additions & 0 deletions test/test-varint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/* globals describe, it */

import { varint } from 'multiformats'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'

chai.use(chaiAsPromised)
const { assert } = chai

const UTF8 = new TextEncoder()

describe('varint', () => {
it('can decode with offset', () => {
const message = UTF8.encode('hello-world')
const outerTag = 0x55
const innerTag = 0xe3
const outerTagSize = varint.encodingLength(outerTag)
const innerTagSize = varint.encodingLength(innerTag)

const bytes = new Uint8Array(message.byteLength + outerTagSize + innerTagSize)
varint.encodeTo(outerTag, bytes)
varint.encodeTo(innerTag, bytes, outerTagSize)
bytes.set(message, outerTagSize + innerTagSize)

assert.deepStrictEqual(varint.decode(bytes), [outerTag, outerTagSize])
assert.deepStrictEqual(varint.decode(bytes, outerTagSize), [innerTag, innerTagSize])
})
})

0 comments on commit 1e1b583

Please # to comment.