encodeVarint

import { encodeVarint } from "jsr:@ende/encoding";

function

function encodeVarint(num: bigint | number, buf: Uint8Array = [UNSUPPORTED], offset: number = 0): [Uint8Array_, number]

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.

If buf is not given then a Uint8Array will be created. offset defaults to 0.

If passed buf then that will be written into, starting at offset. The resulting returned Uint8Array will be a slice of buf. The resulting returned number is effectively offset + bytesWritten.

num: bigint | number

The number to encode.

buf: Uint8Array = [UNSUPPORTED]

The buffer to write into.

offset: number = 0

The offset to start writing at.

Returns

A tuple of the encoded Varint Uint8Array and the new offset.

Example: Usage

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

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

Source