Function 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.

    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.

    Parameters

    • num: number | bigint

      The number to encode.

    • buf: Uint8Array = ...

      The buffer to write into.

    • offset: number = 0

      The offset to start writing at.

    Returns [Uint8Array_, number]

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

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

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