#Serde
Status: standard library specification draft.
This chapter defines the part of std.serde that lib/std writes in
ordinary hd over the language tier:
- the data model: what each
Serializercall writes, and what eachDeserializercall reads; - what a derived
SerializeorDeserializecalls, through the traits' templates; - the standard implementations of both traits.
The language tier keeps the module's declarations and what opting in means
(Serialization), since the host
boundary reads the implementation's output, not the field tree
(module.boundary.out).
#Data Model
A format sees one value as a tree of calls on its writer:
use std.serde.{Serialize, Serializer}
fn write_pair[W < Serializer](out: &mut W, name: string, count: i64) -> Result[void, W::Error]:
out.begin_list(2)?
out.text(name)?
out.int(count)?
out.end_list()| Rule | Value | Serializer calls |
|---|---|---|
| std-serde.model.nullNull | an absent value | null() |
| std-serde.model.boolBoolean | false or true |
bool(value) |
| std-serde.model.intSigned | an integer that fits i64 |
int(value) |
| std-serde.model.uintUnsigned | an integer of an unsigned type | uint(value) |
| std-serde.model.floatFloat | any f64, NaN and infinities included |
float(value) |
| std-serde.model.textText | a string |
text(value) |
| std-serde.model.listList | items in order | begin_list(len), one value per item, end_list() |
| std-serde.model.map-scalar-keysMap | entries in order, each with a MapKeyValue key |
begin_map(len), then per entry map_key(k) and one value, then end_map() |
| std-serde.model.data-recordData record | a struct value | begin_data(facts, v), then per member member(m) and one value, then end_data() |
| std-serde.model.enum-recordEnum record | a unit, named, or mixed enum variant | begin_variant(facts, v), then per member member(m) and one value, then end_variant() |
| std-serde.model.required-newtype-variantNewtype variant | an enum variant with one direct payload | begin_newtype_variant(facts, v), then the payload value, then end_variant(); the hook is required, so each format must support the shape or return its own error |
| std-serde.model.required-tuple-variantTuple variant | an enum variant with several direct payloads | begin_tuple_variant(facts, v, len), then the payload values in order, then end_variant(); the hook is required, so each format must support the shape or return its own error |
- std-serde.model.one-valueA
serializecall writes exactly one value of the table: one scalar call, or one begin call, its contents, and the matching end call. - std-serde.model.container-lenThe
lenofbegin_list,begin_map, orbegin_tuple_variantis the number of items, entries, or direct payload values that follow. - std-serde.model.variant-args.local-ref
begin_variant(facts: Facts, v: &VariantInfo)receives the type-level facts and a local reference to the variant's metadata. - std-serde.model.data-args.local-ref
begin_data(facts: Facts, v: &VariantInfo)receives the type-level facts and a local reference to the struct variant's metadata. Its default callsbegin_variant(facts, v), andend_data's default callsend_variant. - std-serde.model.data-variantA struct value has one variant, whose
of_datais true. - std-serde.model.member-args.local-ref
member(m: &Member)receives a local reference to the metadata of the member whose value follows. - std-serde.model.member-factsThe member's facts are those visible to its derivation, as
annot.structure.per-derivationspecifies. - std-serde.model.errorsA writer's first
.Errends the write. Every standard implementation returns it unchanged, and calls nothing after it. - std-serde.model.ref-receiversEvery method of
SerializerandDeserializertakes&mut self, andserializeanddeserializetake the writer or reader as&mut Wor&mut R. So a format's writer or reader is a struct that changes in place, and its caller reads the struct's fields after the call.
Why. Sixteen calls cover JSON's kinds, and the variant calls keep names and facts, which a format needs to choose a key or a tag. Fewer calls than serde's 29 keep a format small, and a binary format can still tell
intfromuint.
#Reading
A Deserializer reads the same tree, one call per value:
| Rule | Call | Returns |
|---|---|---|
std-serde.read.peekpeek |
peek() |
the ValueKind of the next value, without reading it; an absent value is Null |
std-serde.read.is-nullis_null |
is_null() |
true when the next value is null or absent, which reads it; false otherwise, which leaves it |
| std-serde.read.scalarScalars | bool, int, uint, float, text |
the next value, when it is of that kind and fits the result type |
| std-serde.read.listList | begin_list(), then next_item() before each item |
next_item is true when an item follows, and false after the last |
| std-serde.read.map-scalar-keysMap | begin_map(), then next_map_key() before each entry |
next_map_key is the entry's MapKeyValue, or .None after the last |
| std-serde.read.data-recordData record | begin_data(facts, choices), then the calls for its members, then end_data() |
begin_data is the index of the one struct variant; its default calls begin_variant, and end_data's default calls end_variant |
| std-serde.read.enum-recordEnum record | begin_variant(facts, choices), then the calls for its payload, then end_variant() |
begin_variant is the index in choices of the variant read |
| std-serde.read.required-newtype-variantNewtype variant | begin_variant(facts, choices), begin_newtype_variant(), then the direct payload value, then end_variant() |
begin_variant selects the variant; begin_newtype_variant is required, so each format must position the reader at the direct payload or return its own error |
| std-serde.read.tuple-variantTuple variant | begin_variant(facts, choices), begin_tuple_variant(len), then next_item() before each direct payload value, then end_variant() |
begin_variant selects the variant; begin_tuple_variant positions a payload of exactly len items |
std-serde.read.invalidinvalid |
invalid(expected) |
the format's error for the value just read, which does not fit expected |
std-serde.read.absentis_absent |
is_absent() |
true when the member that member(m) just positioned has no value at all, which reads nothing; the trait's default body gives false |
std-serde.read.keyedkeyed |
keyed() |
true for a reader that names a record's members itself through next_field; the trait's default body gives false |
std-serde.read.next-fieldnext_field |
next_field(members, id, facts, guess) |
the index in members of the member that the record's next key names, or .None after its last key; a key that names no unskipped member is skipped with its value; the trait's default body is invalid("keyed record") |
std-serde.read.absent-fieldabsent_field |
absent_field(m, facts) |
nothing; after it, is_absent and is_null are true and any other read is the format's missing-member error |
std-serde.read.duplicate-fieldduplicate_field |
duplicate_field() |
the format's error for a key that names a member an earlier key of the same record named; the trait's default body gives invalid("unique key") |
std-serde.read.skipskip |
skip() |
nothing: it reads one value of any kind and drops it; the trait's default body reads the value through peek and the calls of its kind |
- std-serde.read.one-valueA
deserializecall reads exactly one value. - std-serde.read.expectedEach scalar call's
expectednames the type being read, as"u8". A format's error for a value of another kind may report it. - std-serde.read.member.local-refA
member(m: &Member)call positions the next value of that member, which the format may report as absent. - std-serde.read.choice-metadata
choicesholds theVariantInfoof every variant offered tobegin_variant, in declaration order.begin_datareceives a list containing the struct's one variant. - std-serde.read.tuple-variant-default
Deserializer's defaultbegin_tuple_variantrejects the value throughinvalid("tuple variant"), so a format must opt in to tuple variants. - std-serde.read.next-field.args
next_field'sidis the record's member directory id,annot.structure.members.id, so every record of one type passes the sameid.guessis the index of the member after the one the previous key named, or 0 before the first key.
use std.serde.Deserializer
fn read_text_or_empty[R < Deserializer](input: &mut R) -> Result[string, R::Error]:
match input.peek()?:
.Text => input.text("string")
_ => .Ok("")Note.
peeklets a value that holds any kind, such as aJson, read itself. A format that is not self-describing may return an error frompeek.
Why.
skipis serde'sIgnoredAny: a hand-written key loop passes a key it does not know with no type to read its value into.
#Derived Implementations
The templates drive a format's
writer or reader with a value's members. For the Session of
Serialization:
| Value | Serializer calls of derived serialize |
|---|---|
Session { user: "ada", token: "t", expires_at: 9 } |
begin_data, member for user, text("ada"), member for token, text("t"), member for expires_at, int(9), end_data() |
- std-serde.derive.serialize.template
std.serdedeclares the template ofSerialize, which@derive(Serialize)instantiates. - std-serde.derive.serialize.data-and-enum-formsDerived
serializewrites every included walked member in declaration order. A struct usesbegin_data,member(m)before each value, andend_data. A unit, named, or mixed positional-and-named enum variant usesbegin_variant,member(m)before each value, andend_variant. A pure positional variant uses this derivation's included positional-member count. Zero uses the unit record form, one usesbegin_newtype_variant, and more usesbegin_tuple_variantwith that count. Every enum form ends withend_variant. - std-serde.derive.deserialize.template
std.serdedeclares the template ofDeserialize, which@derive(Deserialize)instantiates. - std-serde.derive.deserialize.data-and-enum-formsDerived
deserializeoffers a struct's one variant tobegin_data, reads every unskipped built member in declaration order throughmember(m), and callsend_data. For an enum it offers every variant tobegin_variant, selects the same included-member form as serialization, reads every unskipped built member in declaration order, and callsend_variant. Enum record forms callmember(m)before each value, a newtype form reads its direct value, and a tuple form callsnext_item()before each direct value. - std-serde.derive.deserialize.keyed-orderWhen the reader's
keyed()istrue, a struct or an enum record form reads its unskipped built members in the ordernext_fieldnames them, in place of declaration order andmember(m). After the last key it callsabsent_field(m, facts)for each unskipped built member no key named, in declaration order, and then reads that member. - std-serde.derive.deserialize.keyed-duplicateWhen
next_fieldnames a member that an earlier key of the same record named, deriveddeserializereturnsduplicate_field()'s error and reads nothing more. - std-serde.derive.deserialize.keyed-defaultFor a keyed reader,
is_absent()is asked after a member is named or offered throughabsent_field, in place of aftermember(m); an absent defaulted member then takes its declared default. - std-serde.derive.deserialize.unskipped-defaultAfter
member(m), derived deserialization asksis_absent()for an unskipped defaulted member, using its declared default instead ofdeserializewhen absent. - std-serde.derive.omittedA member omitted with
= passis not written. Reading fills it with its declared default, asannot.omit.defaultstates. - std-serde.derive.sharedShared constructor data is not a member, so it is neither written nor read.
use std.serde.{Serialize, Deserialize}
use std.structure.Structure
struct Cache:
hits: i64
struct Session:
pub user: string
token: string
cache: Cache = Cache { hits: 0 }
impl Serialize for Session by Structure:
cache = pass
impl Deserialize for Session by Structure:
cache = passNote. The two blocks above leave
cacheout of every format. Their member lines agree, so they get noderivation-line-driftwarning.
#Member Names
A member's wire name is its name in a document format.
For example, @rename("total") on total_cents: i64 uses the key total.
-
std-serde.rename.fact
std.serdeexports the field factRenamewith the public fieldname: string. -
std-serde.rename.constructor
rename(name: string) -> Renameconstructs a fact with that name. -
std-serde.member-name.precedenceA member's wire name uses its
Rename.namefirst, its container'sRenameAllstyle second, and its source name otherwise. -
std-serde.rename.metadata
Member.nameretains the source member name, and document formats readRenamefromMember.facts. -
std-serde.member-name.helper.local-ref
member_name(member: &Member, container: Facts) -> stringreturns that member's wire name. -
std-serde.member-name.formatsStandard serializers and deserializers use
member_namefor document or capture-group names. -
std-serde.rename-all.styles
RenameCaseis anEqandDebugenum with the eight style variants in the table. -
std-serde.rename-all.fact
RenameAllis a data-type and enum fact with the public fieldstyle: RenameCase. -
std-serde.rename-all.constructor
rename_all(style: RenameCase) -> RenameAllconstructs the fact. -
std-serde.rename-all.conversionStyle conversion follows the table, applying ASCII case changes to a member's written name.
-
std-serde.rename-all.containerA standard format's container facts are the current record's or enum's per-derivation facts supplied to
begin_variant. -
std-serde.rename-all.map-key-valuesA
RenameAllstyle does not change a map key's scalar value or text.
RenameCase variant |
Style | Conversion | order_id becomes |
|---|---|---|---|
Lowercase |
lowercase |
Keep the name | order_id |
Uppercase |
UPPERCASE |
Uppercase ASCII letters | ORDER_ID |
PascalCase |
PascalCase |
Remove underscores and uppercase each word's first character in ASCII | OrderId |
CamelCase |
camelCase |
PascalCase, then lowercase its first character in ASCII | orderId |
SnakeCase |
snake_case |
Keep the name | order_id |
ScreamingSnakeCase |
SCREAMING_SNAKE_CASE |
Uppercase ASCII letters | ORDER_ID |
KebabCase |
kebab-case |
Replace underscores with hyphens | order-id |
ScreamingKebabCase |
SCREAMING-KEBAB-CASE |
Uppercase ASCII letters and replace underscores with hyphens | ORDER-ID |
For example, @rename_all(.CamelCase) on OrderPaid gives the member
order_id the wire name orderId; a field's explicit @rename wins.
Why. Document names belong to the serialization view; preserving the source name lets other adapters, such as environment readers, name fields independently.
#Enum Names And Tagging
An enum's EnumTagging fact selects how a document format represents its
variants. With no fact, the format keeps its ordinary externally tagged form.
- std-serde.rename.variant-fact
Renameis also a variant fact. A variant's wire name uses itsRename.namefirst, its enum'sRenameAllstyle second, and its source name otherwise; a style converts a PascalCase variant at its ASCII word boundaries as the table gives. - std-serde.rename.variant-helper
variant_name(variant: &VariantInfo, container: Facts) -> stringreturns the variant's wire name without changingVariantInfo.name. - std-serde.enum-tagging.fact
EnumTaggingis an enum fact with variantsInternal(tag: string),Adjacent(tag: string, content: string), andUntagged. - std-serde.enum-tagging.constructors
tag(tag: string, content: string? = .None) -> EnumTagginggivesInternal(tag)whencontentis absent andAdjacent(tag, content)when it is present;untagged() -> EnumTagginggivesUntagged. - std-serde.enum-tagging.static-namesA tagging fact is written with
tag,untagged, or anEnumTaggingvariant directly. A writtentagorcontentargument and an internal-form memberRename.nameare string literals. Another computed tagging fact or name is an error at that expression. Error:enum-tag-name-not-static. - std-serde.enum-tagging.declaration-factSerialization and deserialization read tagging only from the enum declaration facts after its no-trait metadata block. A direct
EnumTaggingvalue in aSerializeorDeserializederivation'sSelffacts, or a per-traitSelf = [...]replacement that removes declaration tagging, is an error at that value or replacement. Error:enum-tagging-not-on-declaration. - std-serde.enum-tagging.computed-listA tagging value hidden in a computed fact list, in either a no-trait metadata block or a
SerializeorDeserializederivation block, is unchecked and its behavior is unspecified. - std-serde.enum-tagging.adjacent-distinctAn adjacent form's tag and content names differ. Equal names are an error at
content. Error:enum-tag-name-conflict. - std-serde.enum-tagging.internal-shapesInternal tagging accepts a unit, named-record, or mixed named-and-positional record variant, and a newtype variant whose payload is a struct or
Map[string, V]. A tuple variant, or a newtype over a scalar, list, tuple, non-string-key map, or unresolved generic, is an error at the variant or payload type. Error:invalid-internal-tagged-variant. - std-serde.enum-tagging.internal-name-conflictAn internal tag differs from every statically known member wire name. A collision is an error at the member. Error:
enum-tag-name-conflict. - std-serde.enum-tagging.view-name-conflictA directly written per-trait
RenameAllthat changes an effective payload-member wire name makes that name differ from the declaration tagging's tag and adjacent content names. A collision is an error at that per-trait fact. Error:enum-tag-name-conflict. - std-serde.enum-tagging.view-rename-all-staticOn an enum with declaration tagging, a directly written per-trait
RenameAll.stylenames aRenameCasevariant directly. A computed style is an error at the style expression. Error:enum-tag-name-not-static. - std-serde.enum-tagging.internal-all-variantsInternal-shape and name checks cover every declared variant, whether or not a program constructs or reads it.
- std-serde.enum-tagging.untagged-orderDerived untagged deserialization tries variants in declaration order. A failed candidate restores the complete deserializer value before the next candidate, including its position and path state. The first successful candidate wins.
- std-serde.enum-tagging.untagged-failureWhen no untagged candidate succeeds, deserialization returns one
invalid("variant")error at the enum's original input position. It does not select or aggregate a candidate error.
| Variant source | Lowercase |
Uppercase |
PascalCase |
CamelCase |
SnakeCase |
ScreamingSnakeCase |
KebabCase |
ScreamingKebabCase |
|---|---|---|---|---|---|---|---|---|
UnitValue |
unitvalue |
UNITVALUE |
UnitValue |
unitValue |
unit_value |
UNIT_VALUE |
unit-value |
UNIT-VALUE |
Why. Static checks remove the internally tagged forms whose JSON representation would otherwise be ambiguous or fail only for a reached variant. Copying an ordinary generic deserializer value gives retry a format-neutral checkpoint without adding a public protocol.
#Map Keys
MapKey converts a map key to and from a format-neutral scalar:
use std.serde.{MapKey, MapKeyValue}
struct Language:
code: string
impl MapKey for Language:
fn to_key(&self) -> MapKeyValue: MapKeyValue.Text(self.code)
fn from_key(value: MapKeyValue) -> Language?:
match value:
.Text(code) => .Some(Language { code: code })
_ => .None- std-serde.map-key.value
MapKeyValueis the public enumBool(bool),Int(i64),Uint(u64), andText(string). - std-serde.map-key.trait
MapKeydeclaresto_key(&self) -> MapKeyValueandfrom_key(value: MapKeyValue) -> Self?. - std-serde.map-key.format-neutralA serializer receives the scalar from
to_key, and a deserializer givesfrom_keythe scalar it read. - std-serde.map-key.writer-default
Serializer.map_keydefaults tokeywith the scalar's canonical text. - std-serde.map-key.reader-default
Deserializer.next_map_keydefaults to wrappingnext_key's text inMapKeyValue.Text. - std-serde.map-key.builtins
string, every integer type,char, andboolimplementMapKeywith their matching scalar kind. - std-serde.map-key.user-textA user implementation uses
Textfor its public text representation and accepts that representation fromText. - std-serde.map-key.derive-template
std.serdedeclares the template ofMapKey, which@derive(MapKey)instantiates. - std-serde.map-key.derive-shapesDerived
MapKeyaccepts a payload-free enum or an empty struct and uses the selected variant or struct name asText. - std-serde.map-key.derive-payload-rejectDerived
MapKeyrejects an enum variant or struct that has a member. - std-serde.map-key.no-standard-implFloats, lists, and other user data types have no standard
MapKeyimplementation.
Why. The scalar enum gives a binary format native integer and boolean keys without adding one key-writer protocol per format.
#Absent Optional Members
The typed SkipNone fact omits an optional member only when it is absent.
For example, @skip_none() on note: string? omits the key for .None.
- std-serde.skip-none.fact.phantom
std.serdeexports the member-typed field factSkipNone[F]for the field typeF. It has no value field;Frecords only which member type the fact may annotate. - std-serde.skip-none.constructor
skip_none[T]() -> SkipNone[T?]constructs the fact for an optional field, checked byannot.typed-fact.check. - std-serde.skip-none.absence.default
Serializedeclaresis_absent(&self) -> bool, whose default body returnsfalse. - std-serde.skip-none.absence.optionalThe standard
Serializeimplementation forT?overridesis_absentto returntrueexactly for.None. - std-serde.skip-none.named-omit.v2Derived serialization omits a named member with a
SkipNone[F]fact when statically dispatchedSerialize.is_absent()returnstrue. It calls neither the value's serializer nor the format'smember. - std-serde.skip-none.presentA marked
.Some(value)is written normally, including.Some(.None)as a present member whose value is null. - std-serde.skip-none.read
SkipNonedoes not change deserialization, so absent keys follow the ordinary optional and declared-default rules. - std-serde.skip-none.ordinaryAn unmarked optional member still writes
.Noneas null. - std-serde.skip-none.positional-errorA positional enum payload member with a known
SkipNonefact is an error under a derivedSerialize. Error:member-not-derivable.
Why. The fact is data-free, and the member's already-required
Serializeimplementation answers the absence query before the format sees the member. Every serializer receives the same view without an indirect predicate call or confusion between a present null and an absent optional.
Why. A named member's key identifies which optional value is absent. A positional payload has no key, so omitting a value would make every later position ambiguous to a reader.
#Skipped Members
The Skip field fact omits a member from its serde view.
For example, @skip() on cached: usize = 0 leaves the cache out of documents.
- std-serde.skip.fact
std.serdeexports the field factSkipwith no fields. - std-serde.skip.constructor
skip() -> Skipconstructs the fact. - std-serde.skip.writeDerived serialization omits a member with
Skipwithout calling its serializer or the format'smembermethod for it. - std-serde.skip.named-read-defaultDerived deserialization fills a skipped named member from its declared default without positioning or decoding its input, even when a key is present.
- std-serde.skip.positional-read-defaultDerived deserialization fills a skipped positional payload member with
T::default(), whereTis that member's type, without positioning or decoding its input. - std-serde.skip.impl-factThe walker of derived serialization and the source of derived deserialization carry
skips::[Skip](). Soannot.impl-fact.skipsomits a member whose known facts holdSkip. - std-serde.skip.no-boundA skipped field's type need not implement
SerializeorDeserialize. - std-serde.skip.named-no-defaultUnder a derived
Deserialize, a skipped named member without a declared default is an error at the opt-in. Error:omitted-member-without-default. - std-serde.skip.positional-no-defaultUnder a derived
Deserialize, a skipped positional payload member whose type does not implementDefaultis an error at the opt-in. The diagnostic hint names the requiredDefaultimplementation. Error:omitted-member-without-default. - std-serde.skip.named-unknown-factA
Skipthat only an opaque fact list or a spread attaches to a named member is read when the program runs. The member keeps both bounds, and reading it without a declared default returns a deserializer error naming the member. - std-serde.skip.positional-opaque-errorA positional payload member with an opaque fact list or spread is an error under derived
SerializeorDeserialize, because the compiler cannot know whether it contains a shape-changingSkiporSkipNonefact. Error:member-not-derivable. - std-serde.skip.positional-formA known
Skipremoves a positional payload member from the count that selects the derived unit, newtype, or tuple form and from a tuple form'slen.
Why. A skipped member is never written or read, so its type owes serde nothing. Saying so on the walker and source keeps the rule in library code.
#Regular Walks
A format can write a value directly when it knows the walk ahead of time.
Serialize.regular() says so for a type:
use std.json.encode
@derive(Serialize)
struct Point:
x: i32
y: i32
encode(Point { x: 1, y: 2 }) # Point::regular() is true: TextWriter alone writes it- std-serde.regular
Serializedeclaresregular() -> bool,falseby default. It istrueonly when every value of the type makes a regular walk. - std-serde.regular.walkA regular walk writes one value, a key before each map or member value, a new key each time in its object, and each end after its begin.
- std-serde.regular.stdThe scalars,
Json,Duration,Timestamp, andInstantanswertrue.T?, the references,List[T], andSet[T]answerT::regular(). - std-serde.regular.std.pairs
Result[T, E]answersT::regular() && E::regular().Map[K, V]answersK::distinct() && V::regular(). - std-serde.regular.deriveA derived implementation answers
truewhen the type, its variants, and its walked members carry no facts and every member type is regular. - std-serde.regular.distinct
MapKeydeclaresdistinct() -> bool,falseby default: whether two different keys always give different scalars. The standard and derived implementations answertrue. - std-serde.regular.recursiveA recursive type asks its own
regular()again; that call istruebyannot.bound.recursive.flag.
Why. A fact can rename two members to one key, and a hand-written implementation can write anything. Both answer
false, so a format keeps its general path for them.
#Standard Implementations
std.serde implements both traits for these types:
| Rule | Type | serialize writes |
deserialize reads, with expected |
|---|---|---|---|
| std-serde.std.boolBoolean | bool |
bool |
bool, "bool" |
| std-serde.std.textString | string |
text |
text, "string" |
| std-serde.std.charCharacter | char |
text of that one character |
text of exactly one character, "char" |
| std-serde.std.signedSigned integers | i8, i16, i32, and i64 |
int |
int within the type's range, the type's name |
| std-serde.std.unsignedUnsigned integers | u8, u16, u32, u64, and usize |
uint |
uint within the type's range, the type's name |
| std-serde.std.floatFloats | f32 and f64 |
float of the value as an f64 |
float, the type's name |
| std-serde.std.optionalOptional | T?, where T implements the trait |
null for .None, and the payload for .Some |
.None when is_null is true, and .Some of what T reads otherwise |
| std-serde.std.resultResult | Result[T, E], where T and E implement the trait |
a newtype variant named Ok with the T payload, or one named Err with the E payload |
the corresponding newtype variant and direct payload |
| std-serde.std.listList | List[T], where T implements the trait |
a list of the items, in order | a list, item by item |
| std-serde.std.map-key-entriesMap | Map[K, V], where K implements Eq, Hash, and MapKey, and V implements the trait |
a map of the scalar-keyed entries, in the map's iteration order | a map, entry by entry, in its order |
| std-serde.std.set-elementsSet | Set[T], where T implements the trait |
a list of the elements, in the set's iteration order | a list, element by element; a repeated element keeps one entry |
| std-serde.std.tupleTuple | a tuple type whose members implement the trait | a list of the members, in order | a list with one item per member, in order |
| std-serde.std.counted-referenceCounted reference | *T and *mut T, where T implements the trait |
what T writes for the value the reference refers to |
a new object that holds what T reads |
- std-serde.std.rangeA value that its scalar call reads but the type cannot hold is the reader's
invalid(expected)error. That is an integer outside the type's range, achartext of another length, or anf32past its finite range. The range ofusizeis the target's, bytypes.usize.width, so on the Wasm32 target it is that ofu32. - std-serde.std.float-readAn
f32reads the nearestf32to thef64it reads. - std-serde.std.tuple-lengthA tuple reads exactly one list item per member. A list with fewer items, or with items left after the last member, is the reader's
invalid(expected)error, so JSON reports it at the path of the list or of the first extra item. - std-serde.std.tuple-restA rest element is one member of type
List[T], byannot.walk.rest.default. So(i32, List[i32]...)writes[1, [2, 3]], a list whose last item is the rest list. - std-serde.std.map-key-boundA
Map[K, V]implements a serde trait only whenKimplementsEq,Hash, andMapKeyandVimplements that serde trait. - std-serde.std.local-reference
&Tand&mut TimplementSerializewhenTdoes, and write whatTwrites for the value they refer to. They do not implementDeserialize, since reading makes a new object, which only a counted reference refers to. - std-serde.std.reference.staticThe reference implementations bound
Tby'static, since reading one keeps the value in a new object (Generic Locality). - std-serde.std.map-key-missingUsing a map key without
MapKeywhere a serde trait is required is an error. Error:unsatisfied-trait-bound.
use std.serde.Serialize
@derive(Eq, Hash)
struct Point:
x: i32
y: i32
fn send[T < Serialize](value: T) -> void:
pass
fn send_points(points: Map[Point, i32]) -> void:
send(points) # error: unsatisfied-trait-boundNote.
T??loses a layer:.Some(.None)writesnull, which reads back as.None.
Why. A format decides whether a key scalar is native or text. The key type owns the conversion, so every format sees the same value.
See also: Serialization, Typed JSON, Time, Boundary Encoding.