diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..541b64b 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -137,7 +137,7 @@ interface ParserOptions { key?: string; tag?: string | ((item: any) => number); offset?: number | string | ((item: any) => number); - wrapper?: (buffer: Buffer) => Buffer; + wrapper?: (buffer: Buffer) => Buffer | Uint8Array; skip?: boolean; } diff --git a/package.json b/package.json index 8a46529..aa42b44 100644 --- a/package.json +++ b/package.json @@ -23,8 +23,9 @@ "build": "tsc", "format": "oxfmt --list-different \"{lib,example,test,benchmark}/**/*.{ts,js}\"", "format:fix": "oxfmt \"{lib,example,test,benchmark}/**/*.{ts,js}\"", - "test": "vitest run --project node", + "test": "vitest run --project node && npm run test:types", "test:browser": "vitest run --project browser", + "test:types": "tsc --project test/types/tsconfig.json", "prepare": "npm run build", "lint": "oxlint --type-aware lib test" }, diff --git a/test/types/tsconfig.json b/test/types/tsconfig.json new file mode 100644 index 0000000..de308c9 --- /dev/null +++ b/test/types/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "strict": true, + "noEmit": true, + "types": ["node"] + }, + "files": ["wrapped.ts"] +} diff --git a/test/types/wrapped.ts b/test/types/wrapped.ts new file mode 100644 index 0000000..f69d4c3 --- /dev/null +++ b/test/types/wrapped.ts @@ -0,0 +1,31 @@ +import { Parser } from "../../lib/binary_parser.js"; + +const type = new Parser().uint8("value"); + +const copiedBytes = new Parser().wrapped("data", { + length: 1, + type, + wrapper: (input) => Uint8Array.from(input), +}); +copiedBytes.parse(Uint8Array.of(42)); + +const slicedBytes = new Parser().wrapped("data", { + length: 1, + type, + wrapper: (input: Uint8Array): Uint8Array => input.subarray(0), +}); +slicedBytes.parse(Buffer.from([42])); + +const copiedBuffer = new Parser().wrapped("data", { + length: 1, + type, + wrapper: (input: Buffer): Buffer => Buffer.from(input), +}); +copiedBuffer.parse(Buffer.from([42])); + +new Parser().wrapped("data", { + length: 1, + type, + // @ts-expect-error Wrapper output must provide Uint8Array's byte-view methods. + wrapper: () => new ArrayBuffer(1), +});