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
17 changes: 16 additions & 1 deletion lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1766,15 +1766,30 @@ export class Parser {
if (this.options.type instanceof Parser) {
if (this.varName) {
ctx.pushCode(`${wrapperVar} = ${this.options.type.newObject(ctx)};`);
if (ctx.useContextVariables) {
const parentVar = ctx.generateVariable();
ctx.pushCode(`${wrapperVar}.$parent = ${parentVar};`);
ctx.pushCode(`${wrapperVar}.$root = ${parentVar}.$root;`);
}
}
ctx.pushPath(this.varName);
this.options.type.generate(ctx);
ctx.popPath(this.varName);
if (this.varName && ctx.useContextVariables) {
ctx.pushCode(`delete ${wrapperVar}.$parent;`);
ctx.pushCode(`delete ${wrapperVar}.$root;`);
}
} else if (aliasRegistry.has(this.options.type!)) {
const tempVar = ctx.generateTmpVariable();
ctx.pushCode(
`var ${tempVar} = ${FUNCTION_PREFIX + this.options.type}(0);`,
`var ${tempVar} = ${FUNCTION_PREFIX + this.options.type}(0, {`,
);
if (ctx.useContextVariables) {
const parentVar = ctx.generateVariable();
ctx.pushCode(`$parent: ${parentVar},`);
ctx.pushCode(`$root: ${parentVar}.$root,`);
}
ctx.pushCode("});");
ctx.pushCode(`${wrapperVar} = ${tempVar}.result;`);
if (this.options.type !== this.alias) {
ctx.addReference(this.options.type!);
Expand Down
47 changes: 47 additions & 0 deletions test/wrapper_context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Parser } from "../lib/binary_parser";

describe("wrapped parser context", () => {
for (const aliased of [false, true]) {
it(`preserves parent and root for ${aliased ? "named" : "inline"} types`, () => {
const child = new Parser().uint8("value", {
formatter(this: any, value) {
return { value, parent: this.$parent.tag, root: this.$root.rootTag };
},
});
const type = aliased
? child.namely("wrapper_context_child").alias!
: child;
const parent = new Parser().uint8("tag").wrapped("child", {
length: 1,
wrapper: (bytes) => bytes,
type,
});
const parser = new Parser()
.useContextVars()
.uint8("rootTag")
.nest("parent", { type: parent });
expect(parser.parse(new Uint8Array([3, 4, 5]))).toStrictEqual({
rootTag: 3,
parent: { tag: 4, child: { value: { value: 5, parent: 4, root: 3 } } },
});
});
}

it("leaves context disabled for inline wrapped types by default", () => {
const child = new Parser().uint8("value", {
formatter(this: any, value) {
expect(Object.hasOwn(this, "$parent")).toBe(false);
expect(Object.hasOwn(this, "$root")).toBe(false);
return value;
},
});
const parser = new Parser().wrapped("child", {
type: child,
length: 1,
wrapper: (bytes) => bytes,
});
expect(parser.parse(new Uint8Array([5]))).toStrictEqual({
child: { value: 5 },
});
});
});