import { StrutBase } from './base.js'; import type { StrutParserContext, StrutParserInput, StrutType } from './type.js'; export class StrutTypeArray extends StrutBase { count: number; type: StrutType; constructor(name: string, type: StrutType, count: number) { super(`Array:${name}:${type.name}x${count}`); this.count = count; this.type = type; } get size(): number { return this.count * this.type.size; } parse(bytes: StrutParserInput, ctx: StrutParserContext): T[] { const value: T[] = []; for (let i = 0; i < this.count; i++) value.push(this.type.parse(bytes, ctx)); return value; } } export class StrutTypeArrayOffset extends StrutBase { type: StrutType; isMaxLength: boolean; /** Name of the variable to use as the length */ lengthName: string; /** Since we reference the current object we need to make sure currentObject is passed through */ isLookupRequired = true; constructor(name: string, type: StrutType, lengthVar: string, isMaxLength: boolean) { super('Array:Offset:' + name); this.isMaxLength = isMaxLength; this.lengthName = lengthVar; this.type = type; } /** Size cannot be calculated as it is variable */ get size(): number { throw new Error('Unable to calculate size of dynamic object: ' + this.name); } parse(bytes: StrutParserInput, ctx: StrutParserContext, currentObject: Record): T[] { const value: T[] = []; let packetLength = currentObject?.[this.lengthName]; if (packetLength == null || typeof packetLength !== 'number') { throw new Error(`${this.name}: Missing variable a "${this.lengthName}"`); } if (this.isMaxLength) packetLength -= ctx.offset - ctx.startOffset; for (let i = 0; i < packetLength; i++) value.push(this.type.parse(bytes, ctx)); return value; } }