diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..967d69e 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -47,6 +47,14 @@ class Context { this.pushCode(`throw new Error(${err});`); } + generateOptionOnce(val: number | string | Function): string { + const expression = this.generateOption(val); + if (typeof val === "number") return expression; + const variable = this.generateTmpVariable(); + this.pushCode(`var ${variable} = ${expression};`); + return variable; + } + generateTmpVariable(): string { return "$tmp" + this.tmpVariableCount++; } @@ -1435,7 +1443,7 @@ export class Parser { ctx.pushCode(`${name} = ${decode(`buffer.subarray(${start}, offset)`)};`); ctx.pushCode(`if (offset - ${start} < ${len}) offset++;`); } else if (this.options.length != null) { - const len = ctx.generateOption(this.options.length); + const len = ctx.generateOptionOnce(this.options.length); ctx.pushCode( `${name} = ${decode(`buffer.subarray(offset, offset + ${len})`)};`, ); @@ -1478,7 +1486,7 @@ export class Parser { } else if (this.options.readUntil === "eof") { ctx.pushCode(`${varName} = buffer.subarray(offset);`); } else { - const len = ctx.generateOption(this.options.length!); + const len = ctx.generateOptionOnce(this.options.length!); ctx.pushCode(`${varName} = buffer.subarray(offset, offset + ${len});`); ctx.pushCode(`offset += ${len};`); @@ -1490,7 +1498,10 @@ export class Parser { } private generateArray(ctx: Context) { - const length = ctx.generateOption(this.options.length!); + const length = + this.options.readUntil == null && this.options.lengthInBytes == null + ? ctx.generateOptionOnce(this.options.length!) + : ""; const lengthInBytes = this.options.lengthInBytes == null ? undefined @@ -1739,7 +1750,7 @@ export class Parser { } else if (this.options.readUntil === "eof") { ctx.pushCode(`${wrappedBuf} = buffer.subarray(offset);`); } else { - const len = ctx.generateOption(this.options.length!); + const len = ctx.generateOptionOnce(this.options.length!); ctx.pushCode(`${wrappedBuf} = buffer.subarray(offset, offset + ${len});`); ctx.pushCode(`offset += ${len};`); } diff --git a/test/length_once.ts b/test/length_once.ts new file mode 100644 index 0000000..8b6cdeb --- /dev/null +++ b/test/length_once.ts @@ -0,0 +1,53 @@ +import { Parser } from "../lib/binary_parser"; + +describe("dynamic field lengths", () => { + for (const kind of ["string", "buffer", "wrapped"] as const) { + it(`evaluates a ${kind} length once before advancing the cursor`, () => { + let calls = 0; + const length = () => (++calls === 1 ? 2 : 3); + const parser = new Parser().uint8("prefix"); + if (kind === "wrapped") { + parser.wrapped("field", { + length, + wrapper: (bytes) => bytes, + type: new Parser().array("bytes", { + type: "uint8", + readUntil: "eof", + }), + }); + } else { + parser[kind]("field", { length }); + } + parser.saveOffset("offset").uint8("next"); + const result = parser.parse(new Uint8Array([9, 65, 66, 99, 100, 101])); + expect(result.field).toStrictEqual( + kind === "string" + ? "AB" + : kind === "buffer" + ? new Uint8Array([65, 66]) + : { bytes: [65, 66] }, + ); + expect([result.offset, result.next, calls]).toStrictEqual([3, 99, 1]); + }); + } + + it("uses the captured array length when assigning context indexes", () => { + let calls = 0; + const element = new Parser().uint8("value", { + formatter(this: any, value) { + return { value, index: this.$index }; + }, + }); + const parser = new Parser().useContextVars().array("items", { + type: element, + length: () => (++calls === 1 ? 2 : 5), + }); + expect(parser.parse(new Uint8Array([8, 9]))).toStrictEqual({ + items: [ + { value: { value: 8, index: 0 } }, + { value: { value: 9, index: 1 } }, + ], + }); + expect(calls).toBe(1); + }); +});