import * as Lib from '@/lib/index.js' import { Assert, Check } from '@/util/index.js' import type { Buffable, Bytes, Endian, Replacer, Reviver } from '@/types.js' /** * Buff - A compact byte manipulation class that extends Uint8Array. * Provides conversion methods between different data formats (hex, binary, numbers, strings) * and byte operations with support for endianness. */ export class Buff extends Uint8Array { /** * Creates a Buff from a number. * @param number - The number to convert (must be non-negative) * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance */ static num = ( number : number, size ?: number, endian ?: Endian ) : Buff => { return new Buff(number, size, endian) } /** * Creates a Buff from a bigint. * @param bigint - The bigint to convert * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance */ static big = ( bigint : bigint, size ?: number, endian ?: Endian ) : Buff => { return new Buff(bigint, size, endian) } /** * Creates a Buff from a binary string (containing only '0' and '1'). * @param data - Binary string to convert * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance */ static bin = ( data : string, size ?: number, endian ?: Endian ) : Buff => { const uint = Lib.bin_to_bytes(data) return new Buff(uint, size, endian) } /** * Creates a Buff from a Uint8Array. * @param data - Uint8Array to convert * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance */ static u8a = ( data : Uint8Array, size ?: number, endian ?: Endian ) : Buff => { return new Buff(data, size, endian) } /** * Creates a Buff from a UTF-8 string. * @param data - String to encode * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance */ static str = ( data : string, size ?: number, endian ?: Endian ) : Buff => { const uint = Lib.str_to_bytes(data) return new Buff(uint, size, endian) } /** * Creates a Buff from a hexadecimal string. * @param data - Hex string to convert (e.g., 'ff00') * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance * @throws {TypeError} If hex string contains invalid characters */ static hex = ( data : string, size ?: number, endian ?: Endian ) : Buff => { Assert.is_hex(data) return new Buff(data, size, endian) } /** * Creates a Buff from validated bytes (hex string or Uint8Array). * @param bytes - Bytes to convert * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) * @returns A new Buff instance * @throws {Error} If bytes contains invalid elements */ static bytes = ( bytes : Bytes, size? : number, endian? : Endian ) : Buff => { Assert.is_bytes(bytes) return new Buff(bytes, size, endian) } /** * Creates a Buff from JSON data. * @param data - Data to serialize as JSON * @param replacer - Optional JSON replacer function (defaults to bigint_replacer) * @returns A new Buff instance containing the JSON bytes */ static json = ( data : T, replacer ?: Replacer ) : Buff => { replacer = replacer ?? Lib.bigint_replacer const str = JSON.stringify(data, replacer) const uint = Lib.str_to_bytes(str) return new Buff(uint) } /** * Splits bytes into equal-sized Buff chunks. * @param payload - Data to split * @param chunk_size - Size of each chunk * @param total_size - Expected total size * @returns Array of Buff chunks */ static chunk = ( payload : Bytes, chunk_size : number, total_size : number ) : Buff[] => { const bytes = Lib.buffer(payload) const chunks = Lib.split_bytes(bytes, chunk_size, total_size) return chunks.map(e => new Buff(e)) } /** * Checks if two Buffable values are equal by comparing their bytes. * @param a - First value to compare * @param b - Second value to compare * @returns True if both values represent the same bytes */ static is_equal = ( a : Buffable, b : Buffable ) : boolean => { const buf_a = new Buff(a) const buf_b = new Buff(b) if (buf_a.length !== buf_b.length) return false for (let i = 0; i < buf_a.length; i++) { if (buf_a[i] !== buf_b[i]) return false } return true } /** Checks if a value is valid bytes (hex string or Uint8Array) */ static is_bytes = Check.is_bytes /** Checks if a string is valid hexadecimal */ static is_hex = Check.is_hex /** * Generates a Buff with cryptographically secure random bytes. * @param size - Number of random bytes (default: 32) * @returns A new Buff instance with random data */ static random (size = 32) : Buff { const uint = Lib.get_random_bytes(size) return new Buff(uint, size) } /** * Creates a Buff containing the current Unix timestamp (4 bytes). * @returns A new Buff instance with the timestamp */ static now () : Buff { const stamp = Math.floor(Date.now() / 1000) return new Buff(stamp, 4) } /** * Creates a new Buff instance. * @param data - Data to convert (number, bigint, hex string, Uint8Array, or ArrayBuffer) * @param size - Optional byte size for padding * @param endian - Byte order: 'be' (big-endian) or 'le' (little-endian) */ constructor ( data : Buffable | ArrayBuffer, size ?: number, endian ?: Endian ) { super(Lib.buffer(data, size, endian)) } /** Gets the buffer as a number array */ get arr () : number[] { return this.to_arr() } /** Gets the buffer as a bigint (big-endian) */ get big () : bigint { return this.to_big() } /** Gets the buffer as a binary string */ get bin () : string { return this.to_bin() } /** Gets the buffer as a hexadecimal string (big-endian) */ get hex () : string { return this.to_hex() } /** Gets the buffer as a number (big-endian) */ get num () : number { return this.to_num() } /** Gets the buffer as a UTF-8 string */ get str () : string { return this.to_str() } /** Gets the buffer as a plain Uint8Array */ get u8a () : Uint8Array { return this.to_u8a() } /** * Converts the buffer to a bigint. * @param endian - Byte order: 'be' (big-endian, default) or 'le' (little-endian) * @returns BigInt representation of the buffer */ to_big (endian : Endian = 'be') : bigint { const bytes = (endian === 'be') ? this.u8a.reverse() : this.u8a return Lib.bytes_to_big(bytes) } /** * Converts the buffer to a hexadecimal string. * @param endian - Byte order: 'be' (big-endian, default) or 'le' (little-endian) * @returns Hexadecimal string representation */ to_hex (endian : Endian = 'be') : string { const bytes = (endian === 'be') ? this.u8a : this.u8a.reverse() return Lib.bytes_to_hex(bytes) } /** * Parses the buffer as JSON. * @param reviver - Optional JSON reviver function (defaults to bigint_reviver) * @returns Parsed JSON data */ to_json (reviver ?: Reviver) : T { if (reviver === undefined) { reviver = Lib.bigint_reviver } const str = Lib.bytes_to_str(this) return JSON.parse(str, reviver) } /** * Converts the buffer to a number. * @param endian - Byte order: 'be' (big-endian, default) or 'le' (little-endian) * @returns Number representation of the buffer * @throws {TypeError} If result exceeds Number.MAX_SAFE_INTEGER */ to_num (endian : Endian = 'be') : number { const bytes = (endian === 'be') ? this.u8a.reverse() : this.u8a return Lib.bytes_to_num(bytes) } /** Converts the buffer to a number array */ to_arr () : number[] { return [ ...this ] } /** Converts the buffer to a binary string */ to_bin () : string { return Lib.bytes_to_bin(this) } /** Converts the buffer to a UTF-8 string */ to_str () : string { return Lib.bytes_to_str(this) } /** Converts the buffer to a plain Uint8Array */ to_u8a () : Uint8Array { return new Uint8Array(this) } /** * Appends data to the end of this buffer. * @param data - Data to append * @returns A new Buff with the data appended */ append (data : Buffable) : Buff { return Buff.join([ this, new Buff(data) ]) } /** * Checks if this buffer equals another. * @param data - Data to compare * @returns True if both represent the same bytes */ equals (data : Buffable) : boolean { const other = new Buff(data) if (this.length !== other.length) return false for (let i = 0; i < this.length; i++) { if (this[i] !== other[i]) return false } return true } /** * Prepends data to the beginning of this buffer. * @param data - Data to prepend * @returns A new Buff with the data prepended */ prepend (data : Buffable) : Buff { return Buff.join([ new Buff(data), this ]) } /** * Prepends a varint-encoded length prefix to this buffer. * @param endian - Byte order for multi-byte varints * @returns A new Buff with the length prefix * @throws {Error} If buffer is empty */ prefix_varint (endian ?: Endian) : Buff { if (this.length === 0) throw new Error('buffer is empty') const varint = Buff.create_varint(this.length, endian) return this.prepend(varint) } /** * Reverses the buffer in place. * @returns This Buff instance (for chaining) */ reverse () : this { super.reverse() return this } /** * Sets values in the buffer from an array. * @param array - Source array of numbers * @param offset - Starting position in the buffer (default: 0) */ set (array : ArrayLike, offset ?: number) : void { super.set(array, offset) } /** * Returns a copy of a section of this buffer. * @param start - Start index * @param end - End index (exclusive) * @returns A new Buff containing the sliced data */ slice (start ?: number, end ?: number) : Buff { const arr = new Uint8Array(this).slice(start, end) return new Buff(arr) } /** * Returns a view of a section of this buffer (shares memory). * @param begin - Start index * @param end - End index (exclusive) * @returns A new Buff view of the subarray */ subarray (begin ?: number, end ?: number) : Buff { const arr = new Uint8Array(this).subarray(begin, end) return new Buff(arr) } /** Returns the hex representation for JSON serialization */ toJSON () { return this.hex } /** Returns the hex representation as a string */ toString () { return this.hex } /** * Creates a Buff from an array or Uint8Array. * @param data - Source data * @returns A new Buff instance */ static from (data : Uint8Array | number[]) : Buff { return new Buff(Uint8Array.from(data)) } /** * Creates a Buff from a list of numbers. * @param args - Numbers to include in the buffer * @returns A new Buff instance */ static of (...args : number[]) : Buff { return new Buff(Uint8Array.of(...args)) } /** * Joins multiple Buffable values into a single Buff. * @param arr - Array of values to join * @returns A new Buff containing all data concatenated */ static join (arr : Buffable[]) : Buff { const bytes = arr.map(e => new Buff(e)) const joined = Lib.join_bytes(bytes) return new Buff(joined) } /** * Sorts an array of Buffable values by their hex representation. * @param arr - Array of values to sort * @param size - Optional byte size for padding * @returns Sorted array of Buff instances */ static sort (arr : Buffable[], size ?: number) : Buff[] { const hex = arr.map(e => new Buff(e, size).hex) hex.sort() return hex.map(e => Buff.hex(e, size)) } /** * Creates a varint-encoded Buff from a number. * Uses Bitcoin's CompactSize varint encoding format. * @see https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer * @param num - Number to encode (must be non-negative) * @param endian - Byte order for multi-byte values * @returns A new Buff with the varint encoding * @throws {Error} If number is negative or too large (>= 2^64) */ static create_varint (num : number, endian ?: Endian) : Buff { if (num < 0) { throw new Error(`Varint cannot be negative: ${num}`) } if (num < 0xFD) { return Buff.num(num, 1) } else if (num < 0x10000) { return Buff.of(0xFD, ...Buff.num(num, 2, endian)) } else if (num < 0x100000000) { return Buff.of(0xFE, ...Buff.num(num, 4, endian)) } else if (BigInt(num) < 0x10000000000000000n) { return Buff.of(0xFF, ...Buff.num(num, 8, endian)) } else { throw new Error(`Value is too large: ${num}`) } } }