import { Buff } from '@/class/buff.js' import type { Buffable, Endian } from '@/types.js' /** * Stream processor for consuming byte data sequentially. * Useful for parsing binary protocols where data is read in order. */ export class Stream { /** Current number of bytes remaining in the stream */ public size : number /** Current stream data */ public data : Uint8Array /** * Creates a new Stream from buffable data. * @param data - Data to create stream from (hex string, number, Uint8Array, etc.) */ constructor (data : Buffable) { this.data = new Buff(data) this.size = this.data.length } /** * Reads bytes from the stream without consuming them. * @param size - Number of bytes to peek * @returns Buff containing the peeked bytes * @throws {Error} If size exceeds remaining stream size */ peek (size : number) : Buff { if (size > this.size) { throw new Error(`Size greater than stream: ${size} > ${this.size}`) } return new Buff(this.data.slice(0, size)) } /** * Reads and consumes bytes from the stream. * @param size - Number of bytes to read * @returns Buff containing the read bytes * @throws {Error} If size exceeds remaining stream size */ read (size : number) : Buff { const chunk = this.peek(size) this.data = this.data.slice(size) this.size = this.data.length return chunk } /** * Reads a variable-length integer from the stream. * Follows Bitcoin's CompactSize varint encoding format. * @see https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer * @param endian - Byte order for multi-byte values * @returns Decoded integer value * @throws {Error} If stream is too short for the varint payload */ read_varint (endian ?: Endian) : number { const num = this.read(1).num switch (true) { case (num >= 0 && num < 0xFD): return num case (num === 0xFD): return this.read(2).to_num(endian) case (num === 0xFE): return this.read(4).to_num(endian) case (num === 0xFF): return this.read(8).to_num(endian) default: throw new Error(`Varint is out of range: ${num}`) } } }