Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++;
}
Expand Down Expand Up @@ -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})`)};`,
);
Expand Down Expand Up @@ -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};`);
Expand All @@ -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
Expand Down Expand Up @@ -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};`);
}
Expand Down
53 changes: 53 additions & 0 deletions test/length_once.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});