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
5 changes: 5 additions & 0 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1591,6 +1591,11 @@ export class Parser {
`if (offset <= ${start}) throw new Error("Array element did not consume any bytes");`,
);
}
if (lengthInBytes !== undefined && this.options.readUntil == null) {
ctx.pushCode(
`if (offset > ${counter}) throw new RangeError("Array element exceeds lengthInBytes");`,
);
}

ctx.pushCode("}");

Expand Down
61 changes: 61 additions & 0 deletions test/composite_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,67 @@ function compositeParserTests(

describe(`Composite parser (${name})`, () => {
describe("Array parser", () => {
it("should reject a primitive that crosses lengthInBytes", () => {
const parser = new Parser()
.array("items", {
type: "uint16be",
lengthInBytes: 3,
})
.uint8("tail");
expect(() => parser.parse(factory([0, 1, 0, 2, 42]))).toThrow(
"Array element exceeds lengthInBytes",
);
});

for (const aliased of [false, true]) {
it(`should reject a variable element crossing lengthInBytes (alias ${aliased})`, () => {
const element = new Parser()
.uint8("size")
.buffer("data", { length: "size" });
const type = aliased
? element.namely("byteBoundaryElement").alias!
: element;
const parser = new Parser()
.uint8("size")
.array("items", {
type,
lengthInBytes: "size",
})
.uint8("tail");
expect(() => parser.parse(factory([2, 2, 10, 20, 42]))).toThrow(
"Array element exceeds lengthInBytes",
);
});
}

it("should finish lengthInBytes exactly before the trailing field", () => {
const parser = new Parser()
.uint8("size")
.array("items", {
type: "uint16be",
lengthInBytes: function (this: any) {
return this.size;
},
})
.uint8("tail");
expect(parser.parse(factory([4, 0, 1, 0, 2, 42]))).toStrictEqual({
size: 4,
items: [1, 2],
tail: 42,
});
});

it("should retain readUntil precedence over lengthInBytes", () => {
const parser = new Parser().array("items", {
type: "uint8",
readUntil: "eof",
lengthInBytes: 1,
});
expect(parser.parse(factory([1, 2, 3]))).toStrictEqual({
items: [1, 2, 3],
});
});

it("should resolve element type without endian suffix by endianness()", () => {
const buffer = factory([0x01, 0x00, 0x00, 0x02]);
expect(
Expand Down