big-varint
TypeScript icon, indicating that this package has built-in type declarations

0.1.3 • Public • Published

big-varint

standard-readme compliant license NPM version TypeScript types lines of code

Encode and decode arbitrarily large signed and unsigned BigInts.

This library is TypeScript-native, ESM-only, and has zero dependencies. It uses Uint8Arrays and works in the browser, Node, and Deno. It uses the same binary encoding as Go's encoding/binary module, the Protobuf spec, and the varint / signed-varint NPM packages.

Table of Contents

Install

npm i big-varint

Or in Deno:

import { signed, unsigned } from "https://cdn.skypack.dev/big-varint"

signed.encode(-2138912031n)

Usage

Encode a Signed Varint

import { signed } from "big-varint"

const i = -300n

signed.encode(i) // Uint8Array(2) [ 215, 4 ]

Decode a Signed Varint

import { signed } from "big-varint"

const data = new Uint8Array([215, 4])

signed.decode(data) // -300n

decode can also be passed an optional offset parameter:

import { signed } from "big-varint"

const data = new Uint8Array([0, 0, 215, 4, 37, 37, 37])

signed.decode(data, 2) // -300n

Get the Encoding Length of a Signed Varint

import { signed } from "big-varint"

const i = -300n

signed.encodingLength(i) // 2

Encode an Unsigned Varint

import { unsigned } from "big-varint"

const i = 123456789012345678901234567890n

unsigned.encode(i)

/*
Uint8Array(14) [
  210, 149, 252, 241,
  228, 157, 248, 185,
  195, 237, 191, 200,
  238,  49
]
*/

Decode an Unsigned Varint

import { unsigned } from "big-varint"

const data = new Uint8Array([
	210, 149, 252, 241, 228, 157, 248, 185, 195, 237, 191, 200, 238, 49,
])

unsigned.decode(data) // 123456789012345678901234567890n

decode can also be passed an optional offset parameter:

import { unsigned } from "big-varint"

const data = new Uint8Array([
	0, 0, 0, 0, 210, 149, 252, 241, 228, 157, 248, 185, 195, 237, 191, 200, 238,
	49, 37, 37,
])

unsigned.decode(data, 4) // 123456789012345678901234567890n

Get the Encoding Length of an Unsigned Varint

import { unsigned } from "big-varint"

const i = 123456789012345678901234567890n

unsigned.encodingLength(i) // 14

Testing

Tests use AVA 4 (currently in alpha) and live in the test directory.

npm run test

Credits

A previous version of this library was adapted from chrisdickinson/varint, but has since been rewritten from scratch.

Contributing

I don't expect to add any additional functionality to this library, but am potentially open to proposals for better interfaces. Open issues to discuss any questions before making an PRs.

License

MIT © 2021 Joel Gustafson

Package Sidebar

Install

npm i big-varint

Weekly Downloads

12

Version

0.1.3

License

MIT

Unpacked Size

7.54 kB

Total Files

9

Last publish

Collaborators

  • joelg