Skip to content

Commit

Permalink
fix(core): codec should throw if byteLength mismatch
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanssen0 committed Jan 12, 2025
1 parent a1d5626 commit 3fdb2c4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-ghosts-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ckb-ccc/core": patch
---

fix(core): codec should throw if byteLength mismatch
35 changes: 29 additions & 6 deletions packages/core/src/molecule/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,30 @@ export class Codec<Encodable, Decoded = Encodable> {
decode,
byteLength,
}: CodecLike<Encodable, Decoded>): Codec<Encodable, Decoded> {
return new Codec(encode, decode, byteLength);
return new Codec(
(encodable: Encodable) => {
const encoded = encode(encodable);
if (byteLength !== undefined && encoded.byteLength !== byteLength) {
throw new Error(
`Codec.encode: expected byte length ${byteLength}, got ${encoded.byteLength}`,
);
}
return encoded;
},
(decodable) => {
const decodableBytes = bytesFrom(decodable);
if (
byteLength !== undefined &&
decodableBytes.byteLength !== byteLength
) {
throw new Error(
`Codec.decode: expected byte length ${byteLength}, got ${decodableBytes.byteLength}`,
);
}
return decode(decodable);
},
byteLength,
);
}

map<NewEncodable = Encodable, NewDecoded = Decoded>({
Expand All @@ -43,15 +66,15 @@ export class Codec<Encodable, Decoded = Encodable> {
inMap?: (encodable: NewEncodable) => Encodable;
outMap?: (decoded: Decoded) => NewDecoded;
}): Codec<NewEncodable, NewDecoded> {
return Codec.from({
byteLength: this.byteLength,
encode: (encodable) =>
return new Codec(
(encodable) =>
this.encode((inMap ? inMap(encodable) : encodable) as Encodable),
decode: (buffer) =>
(buffer) =>
(outMap
? outMap(this.decode(buffer))
: this.decode(buffer)) as NewDecoded,
});
this.byteLength,
);
}

mapIn<NewEncodable>(
Expand Down

0 comments on commit 3fdb2c4

Please sign in to comment.