日本語のREADMEはこちらです: README.ja.md
Varuint is an implementation of Unsigned Varint (LEB128-like, 7-bit + continuation bit) encoding and decoding. It can be used directly via URL import in Deno and the browser.
Varuint.encode(n)→Uint8ArrayVaruint.decode(bin, offset=0, wantBigInt=false)→numberorBigInt(whenwantBigInt=true)Varuint.length(n)→ required byte length (number)
import { Varuint } from "https://code4fukui.github.io/Varuint/Varuint.js";
const bin = Varuint.encode(300);
console.log(bin); // Uint8Array(2) [172, 2]
const n = Varuint.decode(bin);
console.log(n); // 300
const len = Varuint.length(n);
console.log(len); // 2Returns the number of bytes required to represent n as a varuint.
console.log(Varuint.length(0)); // 1
console.log(Varuint.length(127)); // 1
console.log(Varuint.length(128)); // 2
console.log(Varuint.length(16384)); // 3Encodes n (a number or BigInt) into a Uint8Array.
- Supports
numberonly for safe integers - Use
BigIntfor larger values
console.log(Varuint.encode(300)); // Uint8Array [172, 2]
console.log(Varuint.encode(0)); // Uint8Array [0]Decodes a varuint from bin.
- Returns number by default
- Returns BigInt when
wantBigInt=true - Starts decoding from the given
offset(useful for concatenated values)
const buf = new Uint8Array([9, 9, 172, 2, 9]);
console.log(Varuint.decode(buf, 2)); // 300
console.log(Varuint.decode(buf, 2, true)); // 300nNote: If the decoded value exceeds
Number.MAX_SAFE_INTEGERwhenwantBigInt=false, aRangeErrorwill be thrown.
- Stores 7 bits at a time from the least significant bit
- Sets the most significant bit (0x80) of each byte to 1 if the value continues
- The last byte has the MSB set to 0
Example:
300→0xAC 0x02([172, 2])
deno testMIT License — see LICENSE.