Skip to content

Commit

Permalink
feat(codec): throw when duplicated ids are found
Browse files Browse the repository at this point in the history
  • Loading branch information
homura committed Dec 13, 2023
1 parent c677c67 commit 04f5146
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
8 changes: 8 additions & 0 deletions packages/codec/src/molecule/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,14 @@ export function union<T extends Record<string, BytesCodec>>(
): UnionCodec<T> {
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);
Expand Down
4 changes: 4 additions & 0 deletions packages/codec/tests/molecule.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 04f5146

Please sign in to comment.