@vekexasia/bigint-constrained
v1.0.0
Published
A library to convert bigint to and from buffers with Buffer polyfills and support for uint/int
Downloads
3
Readme
@vekexasia/bigint-constrained: BigInt wrapper for boundaries checking
This project is part of the bigint-swissknife project. It aims to monkeypatch the Buffer native class adding support for BigInts. This is useful when working with Node.js.
Why?
Sometimes you need to work with a bounded BigInt. This library provides a simple wrapper around BigInt that allows you to specify a minimum and maximum value for the BigInt.
For example, if you need to make sure the bigint you work with is at max 255 (aka uint8), you can use the following:
import { u8 } from '@vekexasia/bigint-constrained';
const a = u8(255n);
const b = u8(256n); // throws an error
const c = u8(-1n); // throws an error
a.add(1n); // throws an error
Please notice:
- Every operation performs boundaries checking and throws an error if the operation would result in a value outside the boundaries.
- Every operation is idempotent on the calling instance and returns a new instance of the bounded BigInt with the same boundaries.
Documentation
You can find typedoc documentation here.
Installation
Add the library to your project:
npm install @vekexasia/bigint-constrained
or
yarn add @vekexasia/bigint-constrained
Usage
Simply import the library like shown above and then you can start using the methods to work with bounded BigInts.
Right now the library exposes the following bounded BigInts:
u8
(uint8)u16
(uint16)u32
(uint32)u64
(uint64)u128
(uint64)u256
(uint64)i8
(int8)- ...
i256
(int256)
If these are not sufficient you can always create your own like so:
import {CheckedBigInt} from '@vekexasia/bigint-constrained';
const u1024 = new CheckedBigInt(0n /*value*/, 1024 /*bits*/, false /*unsigned*/);
or custom bounds:
import {CheckedBigInt} from '@vekexasia/bigint-constrained';
const between10And20 = new CheckedBigInt(10n, {min: 10n, max: 20n});
TypeScript
The library is entirely written in TypeScript and comes with its own type definitions.
License
This project is licensed under the MIT License - see the LICENSE file for details.