diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..7a3bce1 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -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) { diff --git a/test/composite_parser.ts b/test/composite_parser.ts index 08d4738..631ec07 100644 --- a/test/composite_parser.ts +++ b/test/composite_parser.ts @@ -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()