From 04f5146aa4a87f0eafc9b0059102e218757a511e Mon Sep 17 00:00:00 2001 From: homura Date: Wed, 13 Dec 2023 20:44:57 +0800 Subject: [PATCH] feat(codec): throw when duplicated ids are found --- packages/codec/src/molecule/layout.ts | 8 ++++++++ packages/codec/tests/molecule.test.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/packages/codec/src/molecule/layout.ts b/packages/codec/src/molecule/layout.ts index 1d987ed79..b0490db56 100644 --- a/packages/codec/src/molecule/layout.ts +++ b/packages/codec/src/molecule/layout.ts @@ -338,6 +338,14 @@ export function union>( ): UnionCodec { checkShape(itemCodec, Array.isArray(fields) ? fields : Object.keys(fields)); + // check duplicated id + if (!Array.isArray(fields)) { + const ids = Object.values(fields); + if (ids.length !== new Set(ids).size) { + throw new Error(`Duplicated id in union: ${ids.join(", ")}`); + } + } + return createBytesCodec({ pack(obj) { const availableFields: (keyof T)[] = Object.keys(itemCodec); diff --git a/packages/codec/tests/molecule.test.ts b/packages/codec/tests/molecule.test.ts index f5fae16e9..aa9a0538f 100644 --- a/packages/codec/tests/molecule.test.ts +++ b/packages/codec/tests/molecule.test.ts @@ -229,6 +229,10 @@ test("test union with custom id", (t) => { ])); }); +test("test union with duplicated custom id", (t) => { + t.throws(() => union({ key1: Uint8, key2: Uint32LE }, { key1: 0, key2: 0 })); +}); + test("test byteOf", (t) => { t.deepEqual(byteOf(Uint8).pack(1), bytify([1])); t.throws(() => byteOf(Uint16).pack(1));