Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/bright-chefs-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@ckb-ccc/core": major
---

feat(core)!: Codec.from

105 changes: 65 additions & 40 deletions packages/core/src/codec/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import { Bytes, bytesFrom, BytesLike } from "../bytes/index.js";

export type CodecLike<Encodable, Decoded = Encodable> = {
readonly encode: (encodable: Encodable) => Bytes;
readonly decode: (
decodable: BytesLike,
encode: (encodable: Encodable) => BytesLike;
decode: (
decodable: Bytes,
config?: { isExtraFieldIgnored?: boolean },
Comment thread
Hanssen0 marked this conversation as resolved.
) => Decoded;
readonly byteLength?: number;
from?: ((encoded: Encodable) => Decoded) | null;
byteLength?: number;
};
export class Codec<Encodable, Decoded = Encodable> {
constructor(
Expand All @@ -17,6 +18,7 @@ export class Codec<Encodable, Decoded = Encodable> {
decodable: BytesLike,
config?: { isExtraFieldIgnored?: boolean }, // This is equivalent to "compatible" in the Rust implementation of Molecule.
) => Decoded,
public readonly from: (encodable: Encodable) => Decoded,
public readonly byteLength?: number, // if provided, treat codec as fixed length
) {}

Expand All @@ -40,53 +42,76 @@ export class Codec<Encodable, Decoded = Encodable> {
}
}

static from<Encodable, Decoded = Encodable>({
encode,
decode,
byteLength,
}: CodecLike<Encodable, Decoded>): Codec<Encodable, Decoded> {
static from<Encodable, Decoded = Encodable>(
codecLike: CodecLike<Encodable, Decoded>,
): Codec<Encodable, Decoded> {
const newEncode = function (encodable: Encodable) {
const encoded = bytesFrom(codecLike.encode(encodable));
if (
codecLike.byteLength !== undefined &&
encoded.byteLength !== codecLike.byteLength
) {
throw new Error(
`Codec.encode: expected byte length ${codecLike.byteLength}, got ${encoded.byteLength}`,
);
}
return encoded;
};
const newDecode = function (
decodable: BytesLike,
config?: { isExtraFieldIgnored?: boolean },
) {
const decodableBytes = bytesFrom(decodable);
if (
codecLike.byteLength !== undefined &&
decodableBytes.byteLength !== codecLike.byteLength
) {
throw new Error(
`Codec.decode: expected byte length ${codecLike.byteLength}, got ${decodableBytes.byteLength}`,
);
}
return codecLike.decode(decodableBytes, config);
};
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, config) => {
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, config);
},
byteLength,
newEncode,
newDecode,
codecLike.from?.bind(codecLike) ??
function (encodable: Encodable) {
Comment thread
Hanssen0 marked this conversation as resolved.
return newDecode(newEncode(encodable));
},
codecLike.byteLength,
);
}

map<NewEncodable = Encodable, NewDecoded = Decoded>({
inMap,
outMap,
from,
}: {
inMap?: (encodable: NewEncodable) => Encodable;
outMap?: (decoded: Decoded) => NewDecoded;
from?: (encodable: NewEncodable) => NewDecoded;
}): Codec<NewEncodable, NewDecoded> {
return new Codec(
(encodable) =>
this.encode((inMap ? inMap(encodable) : encodable) as Encodable),
(buffer, config) =>
(outMap
? outMap(this.decode(buffer, config))
: this.decode(buffer, config)) as NewDecoded,
this.byteLength,
);
const encode = inMap
? (encodable: NewEncodable) => this.encode(inMap(encodable))
: (this.encode as unknown as (encodable: NewEncodable) => Bytes);
const decode = outMap
? (buffer: BytesLike, config?: { isExtraFieldIgnored?: boolean }) =>
outMap(this.decode(buffer, config))
: (this.decode as unknown as (
buffer: BytesLike,
config?: { isExtraFieldIgnored?: boolean },
) => NewDecoded);
const newFrom =
from ??
((encodable: NewEncodable): NewDecoded => {
const toEncode = (inMap ? inMap(encodable) : encodable) as Encodable;
return (
outMap ? outMap(this.from(toEncode)) : this.from(toEncode)
) as NewDecoded;
});

return new Codec(encode, decode, newFrom, this.byteLength);
}

mapIn<NewEncodable>(
Expand Down
105 changes: 105 additions & 0 deletions packages/core/src/codec/entity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { describe, expect, test } from "vitest";
import { bytesFrom } from "../bytes/index.js";
import { mol } from "../molecule/index.js";
import { Codec } from "./codec.js";
import { codec, Entity } from "./entity.js";

interface FooLike {
v: number;
}

/**
* A minimal entity decorated with `@codec`, used as the base class for the
* dispatch tests below. `Foo.from` marks values it produces with `via: "Foo"`
* so tests can assert which class' `from` actually ran.
*/
@codec(mol.table({ v: mol.Uint8 }))
class Foo extends Entity.Base<FooLike, Foo>() {
public readonly v: number;
public readonly via: string;

constructor(v: number, via: string) {
super();
this.v = v;
this.via = via;
}

static override from(fooLike: FooLike | Foo): Foo {
if (fooLike instanceof Foo) {
return fooLike;
}
return new Foo(fooLike.v, "Foo");
}

override clone(): Foo {
return new Foo(this.v, this.via);
}
}

/** A subclass of `Foo` that overrides `from` with distinguishable behavior. */
class Bar extends Foo {
static override from(fooLike: FooLike | Foo): Foo {
if (fooLike instanceof Foo) {
return fooLike;
}
return new Foo(fooLike.v, "Bar");
}
}

describe("codec decorator static method dispatch", () => {
test("Foo.encode/decode/fromBytes dispatch to Foo.from", () => {
const bytes = Foo.encode({ v: 1 });
expect(Foo.decode(bytes).via).toBe("Foo");
expect(Foo.fromBytes(bytes).via).toBe("Foo");
});

test("Bar.encode/decode/fromBytes dispatch to Bar.from, not the inherited Foo.from", () => {
// Bar does not redefine encode/decode/fromBytes; it inherits them from the
// shared Base installed by the `@codec` decorator on `Foo`. Calling them
// through `Bar` must still resolve `from` against `Bar`, since `this` is
// bound to the receiver of the call (`Bar`), not the class that was
// originally decorated (`Foo`).
const bytes = Bar.encode({ v: 1 });
expect(Bar.decode(bytes).via).toBe("Bar");
expect(Bar.fromBytes(bytes).via).toBe("Bar");
});

test("Bar used as a nested field codec dispatches to Bar.from, not Foo.from", () => {
// `mol.table` builds its field codec via `Codec.from(Bar)`, which reads
// `Bar.encode`/`Bar.decode`/`Bar.from` off `Bar` without ever detaching
// them from their receiver (no destructuring). This must preserve the
// correct `this` binding so nested encode/decode still dispatch to
// `Bar.from` and not to `Foo.from`.
const outer = mol.table({ inner: Bar });

const encoded = outer.encode({ inner: { v: 1 } });
const decoded = outer.decode(encoded);
expect(decoded.inner.via).toBe("Bar");

const fromed = outer.from({ inner: { v: 1 } });
expect(fromed.inner.via).toBe("Bar");
});

test("tearing encode off a class and calling it without a receiver throws", () => {
// This is expected, ordinary JavaScript behavior for static methods that
// rely on `this`: once detached from their receiver, they can no longer
// resolve `this.from`. The `@codec` decorator and `Codec.from` must not
// paper over this by rebinding `this` at property-read time; only the
// framework's own internal call sites (e.g. `Codec.from`) are responsible
// for calling these methods without tearing them off their class.
const { encode } = Bar;
expect(() => encode({ v: 1 })).toThrow(TypeError);
});

test("Codec.from does not tear encode/decode/from off the source object", () => {
// Regression guard for `Codec.from`: it must keep a reference to the
// passed-in `codecLike` and call `codecLike.encode(...)` etc. as member
// calls (preserving `this`), rather than destructuring
// `{ encode, decode, from }` into standalone functions, which would lose
// the receiver and break subclass dispatch through nested codecs.
const rebound = Codec.from(Bar);
const encoded = rebound.encode({ v: 1 });
expect(rebound.decode(bytesFrom(encoded)).via).toBe("Bar");
expect(rebound.from({ v: 1 }).via).toBe("Bar");
});
});
Loading