Skip to content
Merged
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
18 changes: 18 additions & 0 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,12 @@ export class Parser {
throw new Error("length or readUntil must be defined for wrapped.");
}

if (!(options.type instanceof Parser) && !varName) {
throw new Error(
"type must be a Parser object if the variable name is omitted.",
);
}

return this.setNextParser("wrapper", varName as string, options);
}

Expand Down Expand Up @@ -702,6 +708,18 @@ export class Parser {
) {
throw new Error(`Choice type "${value}" is unknown.`);
}

if (typeof value === "string" && !varName) {
throw new Error(
"Choice type must be a Parser object if the variable name is omitted.",
);
}
}

if (typeof options.defaultChoice === "string" && !varName) {
throw new Error(
"defaultChoice must be a Parser object if the variable name is omitted.",
);
}

return this.setNextParser("choice", varName as string, options);
Expand Down
31 changes: 31 additions & 0 deletions test/composite_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,27 @@ function compositeParserTests(
},
});
});
it("should throw if varName is omitted and a choice is a string", () => {
Parser.start().uint8("v").namely("choiceNoVarNameAlias");
expect(() =>
new Parser().uint8("tag").choice({
tag: "tag",
choices: { 1: "choiceNoVarNameAlias" },
}),
).toThrow();
expect(() =>
new Parser()
.uint8("tag")
.choice({ tag: "tag", choices: { 1: "uint8" } }),
).toThrow();
expect(() =>
new Parser().uint8("tag").choice({
tag: "tag",
choices: { 1: Parser.start().uint8("v") },
defaultChoice: "uint8",
}),
).toThrow();
});
});

describe("Nest parser", () => {
Expand Down Expand Up @@ -1452,6 +1473,16 @@ function compositeParserTests(
parserWithoutName.parse(buffer),
);
});
it("should throw if varName is omitted and type is a string", () => {
Parser.start().uint8("v").namely("wrappedNoVarNameAlias");
expect(() =>
new Parser().uint8("x").wrapped({
length: 1,
wrapper: (b: Uint8Array) => b,
type: "wrappedNoVarNameAlias",
}),
).toThrow();
});
});
});
}
Expand Down
Loading