Skip to content

Commit

Permalink
chore: improve varint leb128 docs and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hugomrdias committed Jan 8, 2025
1 parent 4ed0ee9 commit 4986f0e
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 4 deletions.
10 changes: 10 additions & 0 deletions packages/iso-base/src/leb128.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/**
* Unsigned LEB128 encoding and decoding.
*
* Supports bigints and numbers.
*
* @see https://en.wikipedia.org/wiki/LEB128
*
* @module
*/

export const unsigned = {
/**
* Decode a Uint8Array into a number.
Expand Down
9 changes: 6 additions & 3 deletions packages/iso-base/src/varint.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/* eslint-disable no-fallthrough */
/**
* Variable length integer encoding with helpers for tagging Uint8Arrays with multicodec prefixes.
* Unsigned variable length integer encoding with helpers for tagging Uint8Arrays with multicodec prefixes.
* Same as unsigned leb128 encoding but with js safe integers limitations and multiformats rules.
*
*
* @see https://github.com/multiformats/unsigned-varint
*
* @module
*/
Expand Down Expand Up @@ -135,7 +138,7 @@ export function encode(value, buf, offset = 0) {
}

/**
* Decodes buf from position offset or default 0 and returns the decoded original integer.
* Decodes buffer from position offset or default 0 and returns the decoded original integer.
*
* @param {Uint8Array} buf
* @param {number} [offset]
Expand Down
29 changes: 29 additions & 0 deletions packages/iso-base/test/varint.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import assert from 'assert'
import { hex } from '../src/rfc4648.js'
import { decode, encode, encodingLength } from '../src/varint.js'

/**
Expand Down Expand Up @@ -135,4 +136,32 @@ describe('varint', () => {
}
)
})

/** @type {Array<[string, number , number]>} */
const VECTORS = [
['01', 1, 1],
['7f', 127, 1],
['8001', 128, 2],
['ff01', 255, 2],
['ac02', 300, 2],
['808001', 16384, 3],
['d901', 217, 2],
['e29a01', 19_810, 3],
['e086bd2b', 91_177_824, 4],
['e599c7ed09', 2_645_675_237, 5],
]
for (const [b, num, size] of VECTORS) {
const bytes = hex.decode(b)
it(`${b} decode`, () => {
assert.deepStrictEqual(decode(bytes)[0], num)
})

it(`${b} size`, () => {
assert.deepStrictEqual(encodingLength(num), size)
})

it(`${b} encode`, () => {
assert.deepStrictEqual(encode(num)[0], bytes)
})
}
})
3 changes: 2 additions & 1 deletion packages/iso-base/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"src/utils.js",
"src/base-x.js",
"src/varint.js",
"src/ec-compression.js"
"src/ec-compression.js",
"src/leb128.js"
],
"includeVersion": true,
"excludeExternals": true,
Expand Down

0 comments on commit 4986f0e

Please sign in to comment.