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
26 changes: 7 additions & 19 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1264,27 +1264,15 @@ export class Parser {
}

private nextNotBit() {
// Used to test if next type is a bitN or not
if (this.next) {
if (this.next.type === "nest") {
// For now consider a nest as a bit
if (this.next.options.type instanceof Parser) {
// Something in the nest
if (this.next.options.type.next) {
return this.next.options.type.next.type !== "bit";
}
return false;
} else {
// Nest is empty. For now assume this means bit is not next. However what if something comes after the nest?
return true;
}
} else {
return this.next.type !== "bit";
let next = this.next;
while (next?.type === "nest" && next.options.type instanceof Parser) {
if (next.options.type.next) {
return next.options.type.next.type !== "bit";
}
} else {
// Nothing else so next can't be bits
return true;
// Empty nests consume no bits; inspect the field after them.
next = next.next;
}
return next?.type !== "bit";
}

private generateBit(ctx: Context) {
Expand Down
41 changes: 41 additions & 0 deletions test/composite_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,47 @@ function compositeParserTests(
expect(result.nested.three).toStrictEqual(0x45);
});

it("should flush bits before an empty nest at the end", () => {
const parser = new Parser()
.bit4("value")
.nest("empty", { type: new Parser() });

expect(parser.parse(factory([0xf0]))).toStrictEqual({
value: 15,
empty: {},
});
});

it("should flush bits before empty nests followed by a byte", () => {
const parser = new Parser()
.bit4("value")
.nest("first", { type: new Parser() })
.nest("second", { type: new Parser() })
.uint8("tail");

expect(parser.parse(factory([0xf0, 42]))).toStrictEqual({
value: 15,
first: {},
second: {},
tail: 42,
});
});

it("should keep bits packed across an empty nest", () => {
const parser = new Parser()
.bit4("high")
.nest("empty", { type: new Parser() })
.bit4("low")
.uint8("tail");

expect(parser.parse(factory([0xf5, 42]))).toStrictEqual({
high: 15,
empty: {},
low: 5,
tail: 42,
});
});

it("bit before nest should work", () => {
const parser = Parser.start()
.useContextVars()
Expand Down