Equality and hashing
Pinna compares a value written over the one held. When the two are equal, the held value stays, and nothing that read it reruns. What counts as equal depends on what holds the value. The Effect pages are for applications that already use Effect: see Schema-checked boxes.
Example
A schemaBox compares as Schema.toEquivalence of its schema does. An
equal write keeps the object the box holds.
import { createRealm, schemaBox, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const realm = createRealm();
const Reading = Schema.Struct({ at: Schema.Date, value: Schema.Number });
type Reading = typeof Reading.Type;
const $reading = schemaBox(realm, Reading, { at: new Date(0), value: 1 });
const record = (reading: Reading) => {
update(realm, (_read, write) => {
// A Date compares by its time: an equal reading keeps the object
// the box holds, and nobody reruns.
write($reading, reading);
});
};A SchemaModel without its own Equal compares its boxes and its realm by
identity, so two decodes of the same JSON are not equal when the class has a
$ field.
import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
class Position extends SchemaModel<Position>("Position")({
id: Schema.String,
$size: BoxField(Schema.Number),
}) {}
const samePosition = Schema.toEquivalence(Position);
const first = decode(realm, Position)({ id: "a", size: 1 });
const again = decode(realm, Position)({ id: "a", size: 1 });
// false: each decode makes its own $size box, and boxes compare by identity.
const positionsEqual = samePosition(first, again);A refetch through write.replaceAll keeps each plain row that did not
change.
import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
// No `$` field, so a plain Schema.Class.
class Quote extends Schema.Class<Quote>("Quote")({
symbol: Schema.String,
price: Schema.Number,
}) {}
class Market extends SchemaModel<Market>("Market")({
$quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }),
}) {}
const market = decode(realm, Market)({ quotes: [] });
const receiveQuotes = (json: unknown) => {
const quotes = decode(realm, Schema.Array(Quote))(json);
update(realm, (_read, write) => {
// A quote equal under Quote's schema is kept, and what read its row does not rerun.
write.replaceAll(market.$quotes, quotes);
});
};A refetched SchemaModel row is merged into the held one, so a component
that reads the row reruns only when a plain field changes, and one that
reads $size reruns when the size does.
import { decode, reconcileSchema, schemaBox, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const $positions = schemaBox(realm, Schema.Array(Position), []);
const receivePositions = (json: unknown) => {
const fresh = decode(realm, Schema.Array(Position))(json);
update(realm, (read, write) => {
// A held id keeps its Position, and the new size goes into its $size box.
write(
$positions,
reconcileSchema(read($positions), fresh, { keyOf: (position) => position.id }),
);
});
};A SchemaModel that defines [Equal.symbol] decides its own equality. A
refetched rate under a held pair is merged, and its box takes the new bid.
import {
BoxField,
decode,
reconcileSchema,
SchemaModel,
schemaBox,
update,
} from "@frondruntime/pinna-effect";
import { Equal, Hash, Schema } from "effect";
class Rate extends SchemaModel<Rate>("Rate")({
pair: Schema.String,
$bid: BoxField(Schema.Number),
}) {
// One rate per pair. Plain fields only: Effect caches what Equal.equals answers.
[Equal.symbol](that: unknown): boolean {
return that instanceof Rate && that.realm === this.realm && this.pair === that.pair;
}
[Hash.symbol](): number {
return Hash.string(this.pair);
}
}
const $rates = schemaBox(realm, Schema.Array(Rate), []);
const receiveRates = (json: unknown) => {
const fresh = decode(realm, Schema.Array(Rate))(json);
update(realm, (read, write) => {
// A pair already held keeps its rate, and the new bid goes into that rate's box.
write($rates, reconcileSchema(read($rates), fresh, { keyOf: (rate) => rate.pair }));
});
};{ equals } replaces the default of any box.
import { schemaBox } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const Row = Schema.Struct({ id: Schema.String, price: Schema.Number });
// Every new array is a change, even one equal part by part.
const $log = schemaBox(realm, Schema.Array(Schema.String), [], { equals: Object.is });
// The same row while the id is the same, whatever the price.
const $selected = schemaBox(
realm,
Row,
{ id: "a", price: 1 },
{ equals: (held, next) => held.id === next.id },
);Rules
- The core’s
box,collection, andcomputedcompare withObject.isunless{ equals }says otherwise, so a new array or object is a change. A computed value compares withObject.isinpinna-effecttoo, even when what it reads is aschemaBox. - A
schemaBoxand aBoxFieldcompare with the schema’s equivalence, with the answers ofSchema.toEquivalence. An equal write keeps the value held and notifies nobody, so a refetch of the same data reruns nothing. - Under a schema’s equivalence a primitive equals the same value,
NaNequalsNaN, and0equals-0. ADateequals one with the same time, and two invalid Dates are equal. An array or a struct compares part by part. A schema with an equivalence annotation, such asSchema.overrideToEquivalence, compares with it. - A box of
Schema.Unknown,Schema.Any, orSchema.ObjectKeywordcompares withObject.is: such a schema says nothing of the value’s shape, and a structural compare would hash the whole value on every write. AnUnknownfield inside a struct compares structurally. { equals }replaces the schema’s equivalence:Object.iscounts every new array or object as a change, even one equal part by part, and a function by id counts a row with a new price as unchanged.- A
SchemaModelinstance without its ownEqualcompares its plain fields by value and its boxes and its realm by identity. Everydecodemakes new boxes, so a refetched instance with a$field is not equal to the one held, and neither is an instance from another realm. - A
SchemaModelwith its own[Equal.symbol]is compared by that method wherever Pinna compares with the class’s schema, as in aschemaBoxand inreconcileSchema, on every comparison, with no answer cached. A plainSchema.Classignores its own[Equal.symbol]there, as Effect’s schema does, and compares field by field. - A refetched
SchemaModelinstance under a held key is merged into the held one when both are of the same class and realm and their plain fields are equal, or the class’s own[Equal.symbol]finds them equal, even when a plain field differs. The held instance stays; eachBoxFieldtakes the refetched value, compared with its schema, and eachCollectionFieldmerges its rows the same way, so a refetch reruns only the readers of a box that changed. A plain field that holds a model is compared, not merged. Any other difference replaces the instance. reconcileSchema,write.replaceAll, andwrite.upsertmerge. AschemaBoxof an array compares by index and does not.- A
CollectionFieldmerges aSchemaModelrow written under a held key and compares any other row with the row schema’s equivalence:replaceAllandupsertkeep every equal or merged row, and notify nobody when nothing changed. reconciletakesequalsand has no default: a refetch builds new objects, and the comparison is the caller’s choice.reconcileSchemakeeps a row that is the same instance, merges aSchemaModelrow, compares any other instance of aSchema.Classwith its class’s equivalence, and anything else with Effect’sEqual.equals. A key repeated in the new array throws before any box is written. The merge writes in the open update, or in one of its own; a refetch that changes no box opens none, so it runs inside a computed value too.equalsreplaces all of it.- Effect’s
Equal.equals, whichHashSetandHashMaplook values up with, is not the schema’s equivalence. It comparesHash.hashfirst, caches each object’s hash, caches its answer for a pair of objects, and compares an instance by every own property. The two agree on a plainSchema.Classand on aSchemaModelwhose fields are all plain: two decodes of the same JSON into one realm are equal, andHashSet.hasfinds either. They part on two cases:- A
$property of the class body, such as a computed value, is no schema field. The schema’s equivalence ignores it;Equal.equalscompares it by identity, so two instances are not equal under Effect. - A
SchemaModelwith[Equal.symbol]and no[Hash.symbol]is equal under the schema’s equivalence and not underEqual.equals, which compares hashes first. Define both, on plain fields only, such as the key, since Effect caches the hash.
- A
- Under Effect’s
Equal.equals, a box, a computed value, an atom, and a realm equal only themselves. A plain object holding them compares them by identity, never by their contents.
Answers
| Call | Compares a new value with the held one by default with |
|---|---|
box(realm, initial, { equals? }) |
Object.is. |
collection(realm, { keyOf, equals? }) |
Object.is, row by row. |
computed(realm, compute, { equals? }) |
Object.is. |
schemaBox(realm, schema, initial, { equals? }) |
The schema’s equivalence. |
BoxField(schema) |
The schema’s equivalence. |
CollectionField(schema, { keyOf }) |
A merge for a SchemaModel row, the row schema’s equivalence otherwise, row by row. |
reconcile(previous, next, { keyOf, equals }) |
equals, required. |
reconcileSchema(previous, next, { keyOf, equals? }) |
A merge for a SchemaModel row, the class’s equivalence for another schema class instance, Equal.equals otherwise. |
See also
- Schema-checked boxes: the box that checks a schema on every write.
- Classes: the model whose fields these rules compare.
- Collection fields:
replaceAllandreconcileon a refetch. - Boxes and computed: the core’s box and its
equals. - Collections: the core’s collection and its
equals.