import { Decoder } from "../decoder/Decoder.js"; import { decode, type Iterator } from "../encoding/decode.js"; import type { Schema } from "../Schema.js"; import { $refTypeFieldIndexes } from "../types/symbols.js"; /** * Bound single-struct decoder for input packets. Wraps the standard * `Decoder` so bytes emitted by `InputEncoder` land on the bound instance. * * - `decode(bytes)`: single-input packet (reliable mode). * - `decodeAll(bytes, cb)`: multi-input length-framed packet (unreliable * mode). Invokes `cb` with the mutated instance once per framed input, * oldest → newest. The instance is re-used across callbacks — consume * synchronously (apply to game state) rather than holding the reference. * * Flat primitive fields only, like {@link InputEncoder}: ref/collection * fields throw at construction. */ export class InputDecoder { readonly instance: T; private readonly _decoder: Decoder; private readonly _it: Iterator = { offset: 0 }; constructor(instance: T) { // untrusted input: keep the decoder off its ref/collection paths if ((instance.constructor as typeof Schema)[Symbol.metadata]?.[$refTypeFieldIndexes]) { throw new Error(`InputDecoder: '${instance.constructor.name}' must have primitive fields only.`); } this.instance = instance; this._decoder = new Decoder(instance); this._decoder.strict = true; } /** * Decode a single-input (reliable) packet into the bound instance. * Returns the instance for chaining. */ decode(bytes: Uint8Array): T { this._decoder.decode(bytes); return this.instance; } /** * Walk a multi-input (unreliable) packet, decoding each length-framed * input into the bound instance in order and invoking `onInput` after * each decode. `onInput` receives the bound instance and the framework * **seq** of that input (decoded from the packet's base seq + position) — * the receiver dedupes the redundancy ring on it (monotonic: drop seq ≤ * last seen). Reads of the instance must be synchronous; downstream code * should apply the input to game state, not retain the reference. * * Packet layout: `[baseSeq][len][body]…[len][body]` (oldest→newest); * slot *i* has `seq = baseSeq + i`. * * Returns the number of inputs decoded. */ decodeAll(bytes: Uint8Array, onInput: (instance: T, seq: number) => void): number { const it = this._it; it.offset = 0; const baseSeq = decode.number(bytes, it); // packet-level base seq (oldest slot) let count = 0; while (it.offset < bytes.length) { const len = decode.number(bytes, it); const end = it.offset + len; // NaN-safe; a negative len would rewind the cursor forever if (!(len >= 0 && end <= bytes.length)) { break; } this._decoder.decode(bytes.subarray(it.offset, end)); onInput(this.instance, baseSeq + count); // slot seq by position it.offset = end; count++; } return count; } }