silk.schema.schema.
Read and write your own types in any data format, from the types alone.
When to use#
Write impl Schema for T {} for a struct or a union, and read or write it with a format such
as silk.schema.json.SchemaJson. Declare what the type cannot say, such as a wire name or a
port range, in its Spec. Give a type its own read, write and shape when its wire form
differs from its fields, such as a port written as text, and build them from a codec chain with
Schemas.readVia, Schemas.writeVia and Schemas.shapeVia.
Details#
A type is declared once, and the schema derives what to do from it. The default read and
write walk the type's public fields with silk.core.reflect, so a struct is read from an
object with one member per field, in any order, and written in declaration order. A union whose
variants have no fields is the name of its variant, such as "Admin". A union with a variant
that has fields is an object whose type member names the variant and whose other members are
that variant's fields, such as {"type": "Circle", "radius": 2}; Spec.tag picks another
member name. An Option field may be absent, or null, when it is None, and is left out when
written.
Spec holds what the types cannot say: a field whose name on the wire differs, the rules a
field's value follows (Spec.between, Spec.length, Spec.items, Spec.pattern), a default,
and whether unknown keys are rejected. The rules are data, so the same declaration checks a
read, words its errors, and fills the type's silk.schema.shape.Shapes, which JSON Schema
and command line help are rendered from.
A format implements SchemaReader and SchemaWriter, so the same types read and write
JSON, TOML, YAML and MessagePack without changes. Binary data is a silk.collections.bytes.Bytes
field: a format with a binary type, such as MessagePack, holds the bytes as they are, and a text
format holds them as Base64 text.
Gotchas#
Every field of a derived struct or variant must be public, because reflection sees only public
fields. A variant field cannot be named type, or whatever Spec.tag picks.
Examples#
Read and write a struct as JSON#
import silk.core.effect { Effect }
import silk.core.result { Result }
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.schema.issue { SchemaError }
import silk.schema.json { SchemaJson }
import silk.schema.schema { Schema, Spec }
import silk.text.string { String }
struct User {
pub id: u64,
pub name: String,
pub admin: bool,
}
impl Schema for User {
static fn spec() -> Spec<User> {
return Spec<User>.of() |> Spec<User>.rename("id", "user_id") |> Spec<User>.length("name", 1, 64)
}
}
effect fn load() -> u64 ! SchemaError | OutOfMemoryError ? &mut Allocator {
let user = run SchemaJson.decode<User>(b"{\"name\": \"Ada\", \"user_id\": 7, \"admin\": true}")
if !user.admin { return 0 }
return user.id
}
pub effect fn main() -> i32 ! OutOfMemoryError {
let mut allocator = Allocator.systemAllocatorProvider()
let loaded = run Effect.result(load()) |> Effect.provideMut<Allocator>(&mut allocator)
return match move loaded {
Result<u64, SchemaError | OutOfMemoryError>.Success {value} => if value == 7 { 0 } else { 1 }
Result<u64, SchemaError | OutOfMemoryError>.Failure {..} => 2
}
}Import as Schema with import silk.schema.schema { Schema }.
Public declarations: 11.
SchemaReader#
pub interface SchemaReaderThe reading side of a data format, in terms every format shares: scalars, text, bytes, lists and objects.
When to use#
Implement it to let every Schema type read a new format. Programs call a format's own entry
point, such as silk.schema.json.SchemaJson.decode, rather than these operations.
Details#
The schema reads an object by calling beginObject, then member once for each field it
needs, in its own order, and then endObject. member finds the member wherever it is in the
object and leaves the reader at its value.
A reader that knows where values are in its input reports it through lastSpan and
lastKind, so problems found after a value is read, such as a failed range, point at it. A
reader that collects every problem, as SchemaJson.decodeAll does, returns true from
collecting, records what report gives it, and moves past a failed part with recover.
Operation taggedOptions#
fn taggedOptions(self: &Self) -> boolWhether options use a tagged array ([false] or [true, value]) to preserve nested options.
Operation path#
fn path(self: &mut Self) -> &mut SchemaPathReturns the path of the part being read.
Operation boolean#
effect fn boolean(self: &mut Self) -> bool ! Issue | OutOfMemoryError ? &mut AllocatorReads true or false.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value.
Operation signed#
effect fn signed(self: &mut Self) -> i64 ! Issue | OutOfMemoryError ? &mut AllocatorReads an integer that fits in i64.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value, orInvalidValuefor an integer outsidei64.
Operation unsigned#
effect fn unsigned(self: &mut Self) -> u64 ! Issue | OutOfMemoryError ? &mut AllocatorReads an integer that fits in u64.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value, orInvalidValuefor an integer outsideu64.
Operation float#
effect fn float(self: &mut Self) -> f64 ! Issue | OutOfMemoryError ? &mut AllocatorReads a number as an f64.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value.
Operation text#
effect fn text(self: &mut Self) -> String ! Issue | OutOfMemoryError ? &mut AllocatorReads text.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value.OutOfMemoryErrorif theAllocatorcannot supply the text.
Operation bytes#
effect fn bytes(self: &mut Self) -> Bytes
! Issue | OutOfMemoryError
? &mut AllocatorReads binary data. The default reads text and decodes it as standard Base64 with padding (RFC 4648), which is how a text format holds bytes; a format with a binary type overrides it.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value, orInvalidValuefor text that is not Base64.OutOfMemoryErrorif theAllocatorcannot supply the bytes.
Operation null#
effect fn null(self: &mut Self) -> bool ! Issue | OutOfMemoryError ? &mut AllocatorReads past a null value and returns true, or returns false and leaves another value
unread.
Operation beginList#
effect fn beginList(self: &mut Self) -> () ! Issue | OutOfMemoryError ? &mut AllocatorStarts reading a list.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value.
Operation nextElement#
effect fn nextElement(self: &mut Self) -> bool ! Issue | OutOfMemoryError ? &mut AllocatorReturns true and leaves the reader at the next element, or returns false and reads past
the end of the list.
Operation beginObject#
effect fn beginObject(self: &mut Self) -> () ! Issue | OutOfMemoryError ? &mut AllocatorStarts reading an object.
Errors#
IssuewithIssueReason.InvalidTypefor another kind of value.
Operation member#
effect fn member(self: &mut Self, key: string) -> bool ! Issue | OutOfMemoryError ? &mut AllocatorFinds the member key of the object being read and leaves the reader at its value, or
returns false if the object has no such member.
Operation nextMember#
effect fn nextMember(self: &mut Self) -> Option<String>
! Issue | OutOfMemoryError
? &mut AllocatorReturns the next unread member's owned key and leaves the reader at its value.
Returns None after every member has been visited; endObject still closes the object.
Operation rejectUnread#
effect fn rejectUnread(self: &mut Self, expected: string<'static>) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReports every member of the object being read that no member call found, as
IssueReason.UnexpectedKey with expected naming the keys the type accepts. The default
reports nothing.
Errors#
Issuefor the first unread member, unless the reader collects every problem.
Operation endObject#
effect fn endObject(self: &mut Self) -> () ! Issue | OutOfMemoryError ? &mut AllocatorReads past the end of the object being read, whatever members were read.
Operation lastSpan#
fn lastSpan(self: &Self) -> Option<Span>Returns the input bytes of the last complete value read, or of an object's opening when
member found no such key. The default knows none.
Operation lastKind#
fn lastKind(self: &Self) -> ValueKindReturns the kind of the last complete value read. The default knows none.
Operation report#
effect fn report(self: &mut Self, issue: Issue) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReports a problem with the part at the current path. The default fails with it; a reader that collects every problem records it and returns.
Errors#
Issue, the one reported, unless the reader collects every problem.OutOfMemoryErrorif the reader cannot record it.
Operation collecting#
fn collecting(self: &Self) -> boolReturns whether the reader records every problem and goes on after a part fails. The default
is false.
Operation mark#
effect fn mark(self: &mut Self) -> usize
! OutOfMemoryError
? &mut AllocatorRemembers the reader's position, before a part that may fail, and returns a mark for
recover or release. Only a collecting reader is asked.
Errors#
OutOfMemoryErrorif the reader cannot remember it.
Operation recover#
effect fn recover(self: &mut Self, mark: usize, skip: bool) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReturns to the position mark names after the part read from it failed, and when skip is
true reads past that part, so reading goes on with its next sibling. Forgets mark and
every later one.
Errors#
Issueif the part is not well formed, so reading cannot go on.
Operation release#
fn release(self: &mut Self, mark: usize) -> ()Forgets mark and every later one, after the part read from it succeeded.
SchemaWriter#
pub interface SchemaWriterThe writing side of a data format, in terms every format shares: scalars, text, bytes, lists and objects.
When to use#
Implement it to let every Schema type write a new format. Programs call a format's own entry
point, such as silk.schema.json.SchemaJson.encode.
Details#
The schema writes a list as beginList, then element before each element, then endList. It
writes an object as beginObject, then key before each member's value, then endObject.
beginList and beginObject are told how many elements or members follow, because a format
such as MessagePack writes that count first; a format that does not need it ignores it.
Operation taggedOptions#
fn taggedOptions(self: &Self) -> boolWhether options use a tagged array ([false] or [true, value]) to preserve nested options.
Operation boolean#
effect fn boolean(self: &mut Self, value: bool) -> () ! Issue | WriterError ? &mut WriterWrites true or false.
Operation signed#
effect fn signed(self: &mut Self, value: i64) -> () ! Issue | WriterError ? &mut WriterWrites a signed integer.
Operation unsigned#
effect fn unsigned(self: &mut Self, value: u64) -> () ! Issue | WriterError ? &mut WriterWrites an unsigned integer.
Operation float#
effect fn float(self: &mut Self, value: f64) -> () ! Issue | WriterError ? &mut WriterWrites a number.
Errors#
IssuewithIssueReason.InvalidValueif the format cannot holdvalue, such as a NaN in JSON.
Operation text#
effect fn text(self: &mut Self, value: string) -> () ! Issue | WriterError ? &mut WriterWrites text.
Operation bytes#
effect fn bytes(self: &mut Self, value: &[u8]) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites binary data. The default writes it as text in standard Base64 with padding (RFC 4648), which is how a text format holds bytes; a format with a binary type overrides it.
Errors#
Issueif the format cannot hold the value.WriterErrorif theWriterfails.OutOfMemoryErrorif theAllocatorcannot supply the Base64 text.
Operation null#
effect fn null(self: &mut Self) -> () ! Issue | WriterError ? &mut WriterWrites a null value.
Operation beginList#
effect fn beginList(self: &mut Self, count: usize) -> () ! Issue | WriterError ? &mut WriterStarts a list of count elements. Exactly count calls of element follow, each before
its element, and then endList.
Operation element#
effect fn element(self: &mut Self) -> () ! Issue | WriterError ? &mut WriterStarts the next element of the list being written.
Operation endList#
effect fn endList(self: &mut Self) -> () ! Issue | WriterError ? &mut WriterEnds the list being written.
Operation beginObject#
effect fn beginObject(self: &mut Self, count: usize) -> () ! Issue | WriterError ? &mut WriterStarts an object of count members. Exactly count calls of key follow, each before its
member's value, and then endObject.
Operation key#
effect fn key(self: &mut Self, name: string) -> () ! Issue | WriterError ? &mut WriterWrites the key of the next member of the object being written. Its value comes next.
Operation endObject#
effect fn endObject(self: &mut Self) -> () ! Issue | WriterError ? &mut WriterEnds the object being written.
FieldRule#
pub struct FieldRuleOne rule of a field, as a Spec holds it.
Field field#
pub field: string<'static>The field's name in Silk.
Field constraint#
pub constraint: ConstraintThe rule.
Implementation Copy for FieldRule#
impl Copy for FieldRuleSpec#
pub struct Spec<T>What a type's schema says beyond its declaration: wire names, the rules a field's value follows, defaults, and whether unknown keys are rejected.
When to use#
Return one from Schema.spec and build it with pipes:
Spec<Server>.of()
|> Spec<Server>.rename("idleSeconds", "idle_seconds")
|> Spec<Server>.between("port", 1, 65535)
|> Spec<Server>.between("idleSeconds", 1, 3600)
|> Spec<Server>.expected("idleSeconds", "at most an hour")Details#
A spec exists only during static evaluation. Field names are checked against T where they
are written, and the editor links them to the field. A rule applies to the field's value after
it is read, and a value that breaks it fails with IssueReason.CheckFailed at the field's path,
with text generated from the rule, such as an integer from 1 to 65535, unless Spec.expected
gives the field its own. The same rules reach the type's shape, so JSON Schema shows them as
minimum, maxLength and the like.
Implementation Spec<T>#
impl<T> Spec<T>Associated function of#
pub static fn of() -> SelfReturns the spec that keeps every field's own name and adds no rules.
Method rename#
pub static fn rename(self: Self, field: Intrinsic.FieldName<T>, wire: string<'static>) -> SelfReturns the spec in which field is called wire in the data format.
Method tag#
pub static fn tag(self: Self, name: string<'static>) -> SelfReturns the spec in which a union's variant is named by the field name, instead of type.
Details#
A union with a variant that has fields is written as an object holding the variant's name in
this field next to the variant's own fields, such as {"type": "Circle", "radius": 2}.
Method strict#
pub static fn strict(self: Self) -> SelfReturns the spec that rejects an object key no field names, as IssueReason.UnexpectedKey.
Details#
By default unknown keys are skipped, so a config written for a newer version still reads.
JSON Schema shows a strict type with additionalProperties: false.
Method between#
pub static fn between(self: Self, field: Intrinsic.FieldName<T>, min: i64, max: i64) -> SelfReturns the spec in which the number in field is from min to max, both included.
Method atLeast#
pub static fn atLeast(self: Self, field: Intrinsic.FieldName<T>, min: i64) -> SelfReturns the spec in which the number in field is at least min.
Method atMost#
pub static fn atMost(self: Self, field: Intrinsic.FieldName<T>, max: i64) -> SelfReturns the spec in which the number in field is at most max.
Method length#
pub static fn length(self: Self, field: Intrinsic.FieldName<T>, min: usize, max: usize) -> SelfReturns the spec in which the text in field has min to max characters.
Method items#
pub static fn items(self: Self, field: Intrinsic.FieldName<T>, min: usize, max: usize) -> SelfReturns the spec in which the list in field has min to max elements.
Method pattern#
pub static fn pattern(
self: Self,
field: Intrinsic.FieldName<T>,
source: string<'static>,
) -> SelfReturns the spec in which the text in field matches the regular expression source,
anywhere in the text unless source anchors it with ^ and $.
Details#
source uses silk.text.regex syntax, which is the JavaScript syntax JSON Schema's
pattern uses. An invalid expression is a compile error at the literal.
Method expected#
pub static fn expected(self: Self, field: Intrinsic.FieldName<T>, text: string<'static>) -> SelfReturns the spec in which a value of field that breaks a rule is reported as expecting
text, such as "at most an hour", instead of the text generated from the rule.
Method default#
pub static fn default(self: Self, field: Intrinsic.FieldName<T>, value: Literal) -> SelfReturns the spec in which field may be absent or null, and then holds value.
Details#
value is read as if the input held it, so a text default fills a unit variant or a type read
from text, such as Literal.Text {value: "Anonymous"}.
Method tagName#
pub static fn tagName(self: &Self) -> string<'static>Returns the name of the field that holds a union's variant name.
Method wireName#
pub static fn wireName(self: &Self, label: string<'static>) -> string<'static>Returns the name of the field label in the data format.
Method rulesOf#
pub static fn rulesOf(self: &Self, label: string<'static>) -> Intrinsic.StaticSequence<
Constraint
>Returns the rules of the field label, in the order they were added.
Method defaultOf#
pub static fn defaultOf(self: &Self, label: string<'static>) -> Option<Literal>Returns the default of the field label, if it has one.
Method isStrict#
pub static fn isStrict(self: &Self) -> boolReturns whether unknown keys are rejected.
KindOf#
pub struct KindOf<T>The kind of value a type's schema reads, and the text a missing value of it expects.
Details#
The type parameter says whose kind it is, as ShapeOf does. A spec refuses a rule the kind
cannot follow, such as Spec.between on a field that holds text, and a missing key reports
expected unless the field's rules say more.
Field value#
pub value: ValueKindThe kind of value read, or ValueKind.Unknown when the type does not say.
Field expected#
pub expected: string<'static>What the value is, such as an integer.
Implementation KindOf<T>#
impl<T> KindOf<T>Associated function of#
pub static fn of(value: ValueKind, expected: string<'static>) -> KindOf<T>Returns value and expected as the kind of T.
Schema#
pub interface SchemaA type that can be read from and written to any data format.
When to use#
Write impl Schema for T {} for a struct or union whose fields are all public and implement
Schema. Override spec to rename fields and declare their rules. Override read, write
and shape for a type whose wire form is not its fields, usually with Schemas.readVia,
Schemas.writeVia and Schemas.shapeVia.
Details#
The standard library implements it for bool, the integer types, f64, String, Bytes,
Box<T>, Option<T>, List<T> and Dictionary<T>, and for the silk.time types Instant,
PlainDate, PlainTime, PlainDateTime, PlainYearMonth, PlainMonthDay, Period and
UtcOffset, which are ISO 8601 text in every format.
Operation spec#
static fn spec() -> Spec<Self>Returns what the type's schema says beyond its declaration. The default renames nothing and adds no rules.
Operation kind#
static fn kind() -> KindOf<Self>Returns the kind of value the type reads. The default does not say, so every rule may apply
and a missing key expects a value.
When to use#
Override it next to read for a type read from one kind of value, usually as
Schemas.kindVia for a type read through a codec.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Self
! Issue | OutOfMemoryError
? &mut AllocatorReads a value. The default reads a struct from an object, a union of unit variants from its variant name, and any other union from an object tagged with its variant name.
Errors#
Issueif the input does not hold a value of the type.OutOfMemoryErrorif theAllocatorcannot supply the value.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the value. The default writes a struct as an object, a union of unit variants as its variant name, and any other union as an object tagged with its variant name.
Errors#
Issueif the format cannot hold the value.WriterErrorif theWriterfails.OutOfMemoryErrorif a codec needs memory that theAllocatorcannot supply.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds the type's wire form to shapes and returns its node. The default describes a struct
or union from its fields, variants, doc comments and spec, once per type.
When to use#
Override it next to read and write, usually as Schemas.shapeVia, when the type is read
through a codec, so its shape describes what read accepts.
Errors#
OutOfMemoryErrorif theAllocatorcannot grow the table.
Operation missing#
effect fn missing() -> Self
! IssueReturns the value of a field whose key is absent. The default fails, because the key is
required; Option returns None.
Errors#
IssuewithIssueReason.MissingKey.
Operation omitted#
fn omitted(self: &Self) -> boolReturns whether a field holding the value is left out when written. The default is false;
Option returns true for None.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorReturns whether the value follows constraint, a rule its field's spec declares. The default
accepts every value; numbers, String, List and Option test the rules that apply to them.
Errors#
OutOfMemoryErrorif testing a pattern needs memory that theAllocatorcannot supply.
Operation check#
fn check(self: &Self, checks: &mut Checks<Self>) -> ()Checks a value after it is read. The default accepts every value.
When to use#
Override it for a rule no single field can state, such as two fields that exclude each other,
with Checks.that. A rule about one field belongs in its Spec, where JSON Schema and
command line help can show it. A failed check becomes an Issue at the value's path.
Checks#
pub struct Checks<T>The checks of one value of T, run by Schema.check after the value is read.
Examples#
import silk.core.effect { Effect }
import silk.core.option { Option }
import silk.core.result { Result }
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.schema.issue { IssueReason, SchemaError }
import silk.schema.json { SchemaJson }
import silk.schema.schema { Checks, Schema }
import silk.text.string { String }
struct Login {
pub token: Option<String>,
pub password: Option<String>,
}
impl Schema for Login {
fn check(self: &Self, checks: &mut Checks<Login>) -> () {
checks.that(self.token.isSome() != self.password.isSome(), "a token or a password, not both")
}
}
effect fn load() -> Login ! SchemaError | OutOfMemoryError ? &mut Allocator {
return run SchemaJson.decode<Login>(b"{}")
}
pub effect fn main() -> i32 ! OutOfMemoryError {
let mut allocator = Allocator.systemAllocatorProvider()
return match run Effect.result(load()) |> Effect.provideMut<Allocator>(&mut allocator) {
Result<Login, SchemaError | OutOfMemoryError>.Failure {error: SchemaError {issue, ..}} =>
if issue.reason == IssueReason.CheckFailed { 0 } else { 1 }
_ => 2
}
}Gotchas#
One value records at most 16 failed checks; later ones are dropped.
Implementation Checks<T>#
impl<T> Checks<T>Associated function make#
pub fn make() -> Checks<T>Returns the checks with nothing failed yet.
Method that#
pub fn that(self: &mut Self, holds: bool, expected: string<'static>) -> ()Checks a condition on the whole value, such as two fields that must agree. expected says
what the value must be when holds is false.
Schemas#
pub struct SchemasThe owner of the functions that read, write and describe Schema types. It has no fields and
is never constructed.
Implementation Schemas#
impl SchemasAssociated function read#
pub effect fn read<T: Schema>(reader: &mut any SchemaReader) -> T
! Issue | OutOfMemoryError
? &mut AllocatorReads a T with its Schema implementation and runs its Schema.check.
Errors#
Issueif the input does not hold a value of the type.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function readVariant#
pub effect fn readVariant<U: Schema>(reader: &mut any SchemaReader, name: string) -> U
! Issue | OutOfMemoryError
? &mut AllocatorReads the variant of the union U whose wire name is name from an object of its fields,
such as a tool call whose name and arguments arrive apart.
Errors#
IssuewithIssueReason.UnknownVariantifUhas no variantname, or another issue if the object does not hold its fields.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function write#
pub effect fn write<T: Schema>(value: &T, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites value with its Schema implementation.
Errors#
Issueif the format cannot hold the value.WriterErrorif theWriterfails.
Associated function shape#
pub effect fn shape<T: Schema>() -> Shapes
! OutOfMemoryError
? &mut AllocatorReturns the shape of T: its wire form, and that of every type it uses.
Errors#
OutOfMemoryErrorif theAllocatorcannot supply the table.
Associated function shapeOf#
pub effect fn shapeOf<T: Schema>(shapes: &mut Shapes) -> ShapeRef
! OutOfMemoryError
? &mut AllocatorAdds the shape of T to shapes and returns its node, as a type's own shape does for the
types of its parts.
Errors#
OutOfMemoryErrorif theAllocatorcannot grow the table.
Associated function spec#
pub static fn spec<T: Schema>() -> Spec<T>Returns the spec of T.
Associated function kind#
pub static fn kind<T: Schema>() -> KindOf<T>Returns the kind of value T reads.
Associated function kindVia#
pub static fn kindVia<A, I: Schema>() -> KindOf<A>Returns the kind of the wire form I as the kind of A, for the kind of a type read
through a codec with Schemas.readVia.
Associated function readVia#
pub effect fn readVia<A, I: Schema, C: Codec<A, I>>(
codec: &C,
reader: &mut any SchemaReader,
) -> A
! Issue | OutOfMemoryError
? &mut AllocatorReads the wire form I and decodes it into an A with codec.
When to use#
Call it from the read of a type whose wire form is another type, such as a port written as
text. Its shape is then Schemas.shapeVia with the same codec.
Errors#
Issueif the input does not hold anI, or ifcodecrejects it. A codec's issue points at the wire value.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function writeVia#
pub effect fn writeVia<A, I: Schema, C: Codec<A, I>>(
codec: &C,
value: &A,
writer: &mut any SchemaWriter,
) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorEncodes value into the wire form I with codec and writes it.
Errors#
Issueif the format cannot hold the wire value.OutOfMemoryErrorifcodecneeds memory that theAllocatorcannot supply.WriterErrorif theWriterfails.
Associated function shapeVia#
pub effect fn shapeVia<A, I: Schema, C: Codec<A, I>>(codec: &C, shapes: &mut Shapes) -> ShapeOf<A>
! OutOfMemoryError
? &mut AllocatorAdds the shape of a type read through codec from the wire form I to shapes: the shape of
I, with the rules and text the codec reports through Codec.hints.
Errors#
OutOfMemoryErrorif theAllocatorcannot grow the table.
constraintText#
pub static fn constraintText(constraint: Constraint) -> string<'static>Returns the text a value that breaks constraint is reported with, such as
"an integer from 1 to 65535" or "text of 1 to 253 characters".
Implementation Schema for bool#
impl Schema for boolOperation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Boolean.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> bool
! Issue | OutOfMemoryError
? &mut AllocatorReads true or false.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites true or false.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.Boolean.
Implementation Schema for u64#
impl Schema for u64Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> u64
! Issue | OutOfMemoryError
? &mut AllocatorReads a number.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from 0 to u64.MAX.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for i64#
impl Schema for i64Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> i64
! Issue | OutOfMemoryError
? &mut AllocatorReads a number.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from i64.MIN to i64.MAX.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for f64#
impl Schema for f64Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> f64
! Issue | OutOfMemoryError
? &mut AllocatorReads a number.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number. A format that cannot hold a NaN or an infinity fails with an Issue.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.Float.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for String#
impl Schema for StringOperation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> String
! Issue | OutOfMemoryError
? &mut AllocatorReads text.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.Text.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a length in characters, or a pattern.
Implementation Schema for Instant#
impl Schema for InstantInstant is text in every format: an RFC 3339 date and time with an offset, such as 2026-11-19T18:36:22Z. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Instant
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for PlainDate#
impl Schema for PlainDatePlainDate is text in every format: a date, such as 2026-11-19. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> PlainDate
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for PlainTime#
impl Schema for PlainTimePlainTime is text in every format: a time of day, such as 18:36:22. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> PlainTime
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for PlainDateTime#
impl Schema for PlainDateTimePlainDateTime is text in every format: a date and time, such as 2026-11-19T18:36:22. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> PlainDateTime
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for PlainYearMonth#
impl Schema for PlainYearMonthPlainYearMonth is text in every format: a year and month, such as 2026-11. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> PlainYearMonth
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for PlainMonthDay#
impl Schema for PlainMonthDayPlainMonthDay is text in every format: a month and day, such as 11-19. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> PlainMonthDay
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for Period#
impl Schema for PeriodPeriod is text in every format: an ISO 8601 duration, such as P1Y2M3DT4H. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Period
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for UtcOffset#
impl Schema for UtcOffsetUtcOffset is text in every format: a UTC offset, such as +01:00. See silk.time.codec.TimeText.
Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Text.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> UtcOffset
! Issue | OutOfMemoryError
? &mut AllocatorReads text and parses it.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the ISO 8601 text.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds text with a note of the format.
Implementation Schema for Bytes#
impl Schema for BytesOperation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Bytes.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Bytes
! Issue | OutOfMemoryError
? &mut AllocatorReads binary data: the format's binary type, or Base64 text in a text format.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the bytes: as the format's binary type, or as Base64 text in a text format.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.Bytes.
Implementation Schema for Box<T>#
impl<T: Schema> Schema for Box<T>Operation kind#
static fn kind() -> KindOf<Self>Returns the contained schema's value kind and expected description.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Box<T>
! Issue | OutOfMemoryError
? &mut AllocatorReads and allocates the contained value, with the schema and errors of T.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the contained value without an extra object or field.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorReturns the shape of the contained value, without an extra object or field.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a constraint against the contained value.
Implementation Schema for Option<T>#
impl<T: Schema> Schema for Option<T>Operation kind#
static fn kind() -> KindOf<Self>Returns the kind of T.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> Option<T>
! Issue | OutOfMemoryError
? &mut AllocatorReads None from a null value, and Some from any other value.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the value of Some, or a null value for None. A None field is left out instead.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.Optional around the shape of T.
Operation missing#
effect fn missing() -> Option<T>
! IssueReturns None, so an Option field may be absent.
Operation omitted#
fn omitted(self: &Self) -> boolReturns true for None, so a None field is left out.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests the value of Some; None follows every rule.
Implementation Schema for List<T>#
impl<T: Schema> Schema for List<T>Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.List.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> List<T>
! Issue | OutOfMemoryError
? &mut AllocatorReads a list, element by element. A collecting reader records a failed element and goes on with the next.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the list, element by element.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds Shape.List of the shape of T.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a number of elements.
Implementation Schema for u8#
impl Schema for u8Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> u8
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from 0 to 255.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for u16#
impl Schema for u16Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> u16
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from 0 to 65535.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for u32#
impl Schema for u32Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> u32
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from 0 to 4294967295.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for usize#
impl Schema for usizeOperation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> usize
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from 0 to usize.MAX.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for i8#
impl Schema for i8Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> i8
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from -128 to 127.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for i16#
impl Schema for i16Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> i16
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from -32768 to 32767.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
Implementation Schema for i32#
impl Schema for i32Operation kind#
static fn kind() -> KindOf<Self>Returns ValueKind.Number.
Operation read#
effect fn read(reader: &mut any SchemaReader) -> i32
! Issue | OutOfMemoryError
? &mut AllocatorReads a number and fails with IssueReason.InvalidValue if it does not fit.
Operation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites the number.
Operation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorAdds an integer from -2147483648 to 2147483647.
Operation satisfies#
effect fn satisfies(self: &Self, constraint: Constraint) -> bool
! OutOfMemoryError
? &mut AllocatorTests a range.
DictionaryEntry#
pub struct DictionaryEntry<T>One owned key and typed value in a schema dictionary.
Field key#
pub key: StringThe member name as it appears in the document.
Field value#
pub value: TThe member's decoded value.
Dictionary#
pub struct Dictionary<T>An ordered object with arbitrary text keys and one schema for all values.
Implementation Dictionary<T>#
impl<T> Dictionary<T>Associated function make#
pub fn make() -> SelfCreates an empty dictionary.
Method entries#
pub fn entries(self: &Self) -> &[DictionaryEntry<T>]Borrows the members in document order.
Method find#
pub fn find(self: &Self, key: string) -> Option<&T>Finds a member by its exact key, preserving its ownership in the dictionary.
Method insert#
pub effect fn insert(self: &mut Self, key: String, value: T) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorAppends a new member, refusing duplicate keys.
Implementation Schema for Dictionary<T>#
impl<T: Schema> Schema for Dictionary<T>Operation kind#
static fn kind() -> KindOf<Self>Operation read#
effect fn read(reader: &mut any SchemaReader) -> Self
! Issue | OutOfMemoryError
? &mut AllocatorOperation write#
effect fn write(self: &Self, writer: &mut any SchemaWriter) -> ()
! Issue | WriterError | OutOfMemoryError
? &mut Allocator | &mut WriterOperation shape#
effect fn shape(shapes: &mut Shapes) -> ShapeOf<Self>
! OutOfMemoryError
? &mut AllocatorOperation missing#
effect fn missing() -> Self
! IssueAn absent dictionary field has no members.
Category: Data formats.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.