diff --git a/README.md b/README.md index dc8e9ad..5a515e1 100644 --- a/README.md +++ b/README.md @@ -563,8 +563,10 @@ These options can be used in all parsers. numbers and so on). If `assert` is a `string` or `number`, the actual parsed result will be compared with it with `===` (strict equality check), and an exception is thrown if they mismatch. On the other hand, if `assert` is a - function, that function is executed with one argument (the parsed result) - and if it returns false, an exception is thrown. + function, that function receives the parsed result and the buffer currently + being parsed (`Buffer` or `Uint8Array`). If it returns false, an exception is + thrown. The second argument allows checksums to inspect the encoded bytes; + existing predicates that only use the first argument continue to work. ```javascript // simple magic number validation @@ -583,6 +585,20 @@ These options can be used in all parsers. }); ``` + For example, validate a byte checksum over two preceding bytes: + + ```javascript + const packet = new Parser() + .uint8("a") + .uint8("b") + .uint8("checksum", { + assert: (checksum, buffer) => checksum === ((buffer[0] + buffer[1]) & 0xff) + }); + ``` + + The buffer is the supplied view, not its underlying `ArrayBuffer`. In a + wrapped parser it is the buffer returned by the wrapper. + ### Context variables You can use some special fields while parsing to traverse your structure. These context variables will be removed after the parsing process. diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..dbb9c6d 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -121,7 +121,10 @@ const FUNCTION_PREFIX = "___parser_"; interface ParserOptions { length?: number | string | ((item: any) => number); - assert?: number | string | ((item: number | string) => boolean); + assert?: + | number + | string + | ((item: number | string, buffer: Uint8Array) => boolean); lengthInBytes?: number | string | ((item: any) => number); type?: string | Parser; formatter?: (item: any) => any; @@ -1239,7 +1242,7 @@ export class Parser { case "function": { const func = ctx.addImport(this.options.assert); - ctx.pushCode(`if (!${func}.call(vars, ${varName})) {`); + ctx.pushCode(`if (!${func}.call(vars, ${varName}, buffer)) {`); } break; case "number": diff --git a/test/composite_parser.ts b/test/composite_parser.ts index 08d4738..164123a 100644 --- a/test/composite_parser.ts +++ b/test/composite_parser.ts @@ -14,6 +14,31 @@ function compositeParserTests( describe(`Composite parser (${name})`, () => { describe("Array parser", () => { + it("should pass the input buffer to assertions in array elements", () => { + const input = factory([3, 4, 7, 5, 6, 11]); + let index = 0; + const element = new Parser() + .uint8("a") + .uint8("b") + .uint8("checksum", { + assert: (value, buffer) => { + expect(buffer).toBe(input); + const offset = index++ * 3; + return value === buffer[offset] + buffer[offset + 1]; + }, + }); + const parser = new Parser().array("items", { + type: element, + length: 2, + }); + expect(parser.parse(input)).toStrictEqual({ + items: [ + { a: 3, b: 4, checksum: 7 }, + { a: 5, b: 6, checksum: 11 }, + ], + }); + expect(index).toBe(2); + }); it("should resolve element type without endian suffix by endianness()", () => { const buffer = factory([0x01, 0x00, 0x00, 0x02]); expect( diff --git a/test/primitive_parser.ts b/test/primitive_parser.ts index 0d67482..f5bece2 100644 --- a/test/primitive_parser.ts +++ b/test/primitive_parser.ts @@ -28,6 +28,33 @@ function primitiveParserTests( expect(parser.parse(buffer)).toStrictEqual({}); }); + + it("should pass the original input view to checksum assertions", () => { + const input = factory([255, 3, 4, 7, 255]).subarray(1, 4); + const parser = new Parser() + .uint8("a") + .uint8("b") + .uint8("checksum", { + assert: function (this: { a: number }, value, buffer) { + expect(buffer).toBe(input); + expect(this.a).toBe(3); + return value === buffer[0] + buffer[1]; + }, + }); + expect(parser.parse(input)).toStrictEqual({ a: 3, b: 4, checksum: 7 }); + input[2] = 8; + expect(() => parser.parse(input)).toThrow("Assertion error"); + }); + + it("should pass the input buffer to bit field assertions", () => { + const input = factory([0x12]); + const parser = new Parser() + .bit4("high", { + assert: (value, buffer) => value === buffer[0] >> 4, + }) + .bit4("low"); + expect(parser.parse(input)).toStrictEqual({ high: 1, low: 2 }); + }); it("should parse integer types", () => { const parser = Parser.start().uint8("a").int16le("b").uint32be("c");