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
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
7 changes: 5 additions & 2 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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":
Expand Down
25 changes: 25 additions & 0 deletions test/composite_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
27 changes: 27 additions & 0 deletions test/primitive_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down