From fdff6ffb03f49bd99c5dc6aea62a874591d12e30 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Tue, 24 Nov 2026 16:34:43 +0800 Subject: [PATCH] Invalidate compiled parsers after builder mutations --- lib/binary_parser.ts | 4 ++++ test/compiled_mutation.ts | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 test/compiled_mutation.ts diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..9780ef7 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -705,6 +705,7 @@ export class Parser { this.sanitizeFieldName(alias); aliasRegistry.set(alias, this); this.alias = alias; + this.compiled = undefined; return this; } @@ -963,6 +964,7 @@ export class Parser { useContextVars(useContextVariables = true): this { this.useContextVariables = useContextVariables; + this.compiled = undefined; return this; } @@ -973,6 +975,7 @@ export class Parser { } this.constructorFn = constructorFn; + this.compiled = undefined; return this; } @@ -1143,6 +1146,7 @@ export class Parser { this.next = parser; } this.head = parser; + this.compiled = undefined; return this; } diff --git a/test/compiled_mutation.ts b/test/compiled_mutation.ts new file mode 100644 index 0000000..040d61c --- /dev/null +++ b/test/compiled_mutation.ts @@ -0,0 +1,42 @@ +import { Parser } from "../lib/binary_parser"; + +describe("changes after compilation", () => { + for (const explicit of [false, true]) { + it(`includes fields appended after ${explicit ? "compile" : "parse"}`, () => { + const parser = new Parser().uint8("first"); + const input = new Uint8Array([1, 2]); + if (explicit) parser.compile(); + else expect(parser.parse(input)).toStrictEqual({ first: 1 }); + parser.uint8("second"); + expect(parser.parse(input)).toStrictEqual({ first: 1, second: 2 }); + }); + } + + it("uses a constructor selected after the first parse", () => { + class Result { + kind = "custom"; + } + const parser = new Parser().uint8("value"); + parser.parse(new Uint8Array([1])); + parser.create(Result); + const result = parser.parse(new Uint8Array([2])); + expect(result).toBeInstanceOf(Result); + expect(result.kind).toBe("custom"); + expect(result.value).toBe(2); + }); + + it("honors context toggles after earlier parses", () => { + const child = new Parser().uint8("value", { + formatter(this: any) { + return this.$parent !== undefined; + }, + }); + const parser = new Parser().nest("child", { type: child }); + const input = new Uint8Array([1]); + expect(parser.parse(input).child.value).toBe(false); + parser.useContextVars(); + expect(parser.parse(input).child.value).toBe(true); + parser.useContextVars(false); + expect(parser.parse(input).child.value).toBe(false); + }); +});