import type { Endian } from '@/types.js' const _0n = BigInt(0) const _255n = BigInt(255) const _256n = BigInt(256) /** * Calculates the minimum byte size needed to represent a bigint. * @param big - BigInt value to measure * @returns Byte size (1, 2, 4, 8, 16, or 32) * @throws {TypeError} If bigint is larger than 32 bytes */ export function get_big_size ( big : bigint) : number { // 1 byte. if (big <= 0xFFn) return 1 // 2 bytes. if (big <= 0xFFFFn) return 2 // 4 bytes. if (big <= 0xFFFFFFFFn) return 4 // 8 bytes. if (big <= 0xFFFFFFFFFFFFFFFFn) return 8 // 16 bytes. if (big <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFn) return 16 // 32 bytes. if (big <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFn) { return 32 } throw new TypeError('Must specify a fixed buffer size for bigints greater than 32 bytes.') } /** * Converts a bigint to bytes with specified endianness. * @param big - BigInt value to convert * @param size - Optional byte size (auto-calculated if not provided) * @param endian - Byte order: 'be' (big-endian, default) or 'le' (little-endian) * @returns Uint8Array containing the bigint as bytes */ export function big_to_bytes ( big : bigint, size ?: number, endian : Endian = 'be' ) : Uint8Array { if (size === undefined) size = get_big_size(big) const use_le = (endian === 'le') const buffer = new ArrayBuffer(size) const dataView = new DataView(buffer) let offset = (use_le) ? 0 : size - 1 while (big > _0n) { const byte = big & _255n const num = Number(byte) if (use_le) { dataView.setUint8(offset++, num) } else { dataView.setUint8(offset--, num) } big = (big - byte) / _256n } return new Uint8Array(buffer) } /** * Converts bytes to a bigint (little-endian byte order). * @param bytes - Uint8Array to convert * @returns BigInt representation of the bytes */ export function bytes_to_big ( bytes : Uint8Array ) : bigint { let num = BigInt(0) for (let i = bytes.length - 1; i >= 0; i--) { num = (num * _256n) + BigInt(bytes[i]) } return BigInt(num) } /** * JSON replacer function that converts bigints to string format (e.g., "123n"). * Use with JSON.stringify to handle bigint values. * @param _ - Key (unused) * @param v - Value to process * @returns Original value or string representation if bigint */ export function bigint_replacer (_ : unknown, v : unknown) : unknown { return typeof v === 'bigint' ? `${v}n` : v } /** * JSON reviver function that converts string format (e.g., "123n") back to bigints. * Use with JSON.parse to restore bigint values. * @param _ - Key (unused) * @param v - Value to process * @returns Original value or bigint if string matches pattern */ export function bigint_reviver (_ : unknown, v : unknown) : unknown { return typeof v === 'string' && /^[0-9]+n$/.test(v) ? BigInt(v.slice(0, -1)) : v }