diff --git a/README.md b/README.md index 1179fb49..6ddeaa83 100644 --- a/README.md +++ b/README.md @@ -298,13 +298,26 @@ That function will have state while `stream = true` is used. ### `@exodus/bytes/bigint.js` +Convert between BigInt and Uint8Array + ```js import { fromBigInt, toBigInt } from '@exodus/bytes/bigint.js' ``` #### `fromBigInt(bigint, { length, format = 'uint8' })` + +Convert a BigInt to a Uint8Array or Buffer + +The output bytes are in big-endian format. + +Throws if the BigInt is negative or cannot fit into the specified length. + #### `toBigInt(arr)` +Convert a Uint8Array or Buffer to a BigInt + +The bytes are interpreted as a big-endian unsigned integer. + ### `@exodus/bytes/hex.js` Implements Base16 from [RFC4648](https://datatracker.ietf.org/doc/html/rfc4648) diff --git a/bigint.d.ts b/bigint.d.ts new file mode 100644 index 00000000..a0758f99 --- /dev/null +++ b/bigint.d.ts @@ -0,0 +1,48 @@ +/** + * Convert between BigInt and Uint8Array + * + * ```js + * import { fromBigInt, toBigInt } from '@exodus/bytes/bigint.js' + * ``` + * + * @module @exodus/bytes/bigint.js + */ + +/// + +import type { OutputFormat, Uint8ArrayBuffer } from './array.js'; + +/** + * Options for converting BigInt to bytes + */ +export interface FromBigIntOptions { + /** The length in bytes of the output array */ + length: number; + /** Output format (default: 'uint8') */ + format?: OutputFormat; +} + +/** + * Convert a BigInt to a Uint8Array or Buffer + * + * The output bytes are in big-endian format. + * + * Throws if the BigInt is negative or cannot fit into the specified length. + * + * @param x - The BigInt to convert (must be non-negative) + * @param options - Conversion options + * @returns The converted bytes in big-endian format + */ +export function fromBigInt(x: bigint, options: { length: number; format?: 'uint8' }): Uint8ArrayBuffer; +export function fromBigInt(x: bigint, options: { length: number; format: 'buffer' }): Buffer; +export function fromBigInt(x: bigint, options: FromBigIntOptions): Uint8ArrayBuffer | Buffer; + +/** + * Convert a Uint8Array or Buffer to a BigInt + * + * The bytes are interpreted as a big-endian unsigned integer. + * + * @param arr - The bytes to convert + * @returns The BigInt representation + */ +export function toBigInt(arr: ArrayBufferView): bigint; diff --git a/package.json b/package.json index 3fa2d797..17e3bdd9 100644 --- a/package.json +++ b/package.json @@ -90,6 +90,7 @@ "/base64.d.ts", "/bech32.js", "/bigint.js", + "/bigint.d.ts", "/encoding-browser.js", "/encoding-browser.browser.js", "/encoding-browser.native.js", @@ -140,7 +141,10 @@ "default": "./base64.js" }, "./bech32.js": "./bech32.js", - "./bigint.js": "./bigint.js", + "./bigint.js": { + "types": "./bigint.d.ts", + "default": "./bigint.js" + }, "./hex.js": { "types": "./hex.d.ts", "node": "./hex.node.js",