@ende/encoding/varint

ende add jsr:@ende/encoding

Version 2026.10.15 on JSR.

Utilities for Varint encoding of typed integers. Varint encoding represents integers using a variable number of bytes, with smaller values requiring fewer bytes.

import { encodeVarint, decodeVarint } from "@ende/encoding/varint";
import { assertEquals } from "@ende/assert";

const buf = new Uint8Array(10);
assertEquals(
  encodeVarint(42n, buf),
  [new Uint8Array([42]), 1]
);

assertEquals(
  decodeVarint(new Uint8Array([42])),
  [ 42n, 1 ]
);

Exports

  • decodeVarint — Given a non empty `buf`, starting at `offset` (default: 0), begin decoding bytes as Varint encoded bytes, for a maximum of 10 bytes (offset + 10). The returned tuple is of the decoded varint 32-bit number, and the new offset with which to continue decoding other data.
  • decodeVarint32 — Given a `buf`, starting at `offset` (default: 0), begin decoding bytes as Varint encoded bytes, for a maximum of 5 bytes (offset + 5). The returned tuple is of the decoded varint 32-bit number, and the new offset with which to continue decoding other data.
  • encodeVarint — Takes unsigned number `num` and converts it into a Varint encoded `Uint8Array`, returning a tuple consisting of a `Uint8Array` slice of the encoded Varint, and an offset where the Varint encoded bytes end within the `Uint8Array`.
  • MaxUint64 — The maximum value of an unsigned 64-bit integer. Equivalent to `2n**64n - 1n`
  • MaxVarintLen32 — The maximum length, in bytes, of a Varint encoded 32-bit integer.
  • MaxVarintLen64 — The maximum length, in bytes, of a Varint encoded 64-bit integer.
  • Uint8Array_ — Proxy type of {@code Uint8Array<ArrayBuffer>} or {@code Uint8Array} in TypeScript 5.7 or below respectively.