diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..f272e2b 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -409,8 +409,8 @@ export class Parser { if ( typeof type === "string" && !aliasRegistry.has(type) && - !(type in PRIMITIVE_SIZES) && - type + this.endian in PRIMITIVE_SIZES + !Object.hasOwn(PRIMITIVE_SIZES, type) && + Object.hasOwn(PRIMITIVE_SIZES, type + this.endian) ) { return (type + this.endian) as T; } @@ -824,7 +824,7 @@ export class Parser { if ( typeof options.type === "string" && !aliasRegistry.has(options.type) && - !(options.type in PRIMITIVE_SIZES) + !Object.hasOwn(PRIMITIVE_SIZES, options.type) ) { throw new Error(`Array element type "${options.type}" is unknown.`); } @@ -872,7 +872,7 @@ export class Parser { if ( typeof value === "string" && !aliasRegistry.has(value) && - !(value in PRIMITIVE_SIZES) + !Object.hasOwn(PRIMITIVE_SIZES, value) ) { throw new Error(`Choice type "${value}" is unknown.`); } @@ -929,7 +929,7 @@ export class Parser { if ( typeof options.type === "string" && - !(options.type in PRIMITIVE_SIZES) && + !Object.hasOwn(PRIMITIVE_SIZES, options.type) && !aliasRegistry.has(options.type) ) { throw new Error(`Pointer type "${options.type}" is unknown.`); diff --git a/test/primitive_names.ts b/test/primitive_names.ts new file mode 100644 index 0000000..9d71c3a --- /dev/null +++ b/test/primitive_names.ts @@ -0,0 +1,29 @@ +import { Parser } from "../lib/binary_parser"; + +describe("primitive type lookup", () => { + for (const type of ["toString", "constructor", "valueOf"]) { + it(`rejects inherited Object member ${type} as an array type`, () => { + expect(() => new Parser().array("items", { type, length: 1 })).toThrow( + "unknown", + ); + }); + it(`rejects inherited Object member ${type} as a pointer type`, () => { + expect(() => new Parser().pointer("item", { type, offset: 0 })).toThrow( + "unknown", + ); + }); + it(`rejects inherited Object member ${type} as a choice type`, () => { + expect(() => + new Parser().choice("item", { tag: 1, choices: { 1: type } }), + ).toThrow("unknown"); + }); + } + + it("still permits an explicitly registered alias with an Object member name", () => { + new Parser().uint8("value").namely("toString"); + const parser = new Parser().array("items", { type: "toString", length: 1 }); + expect(parser.parse(new Uint8Array([7]))).toStrictEqual({ + items: [{ value: 7 }], + }); + }); +});