The Postcard Wire Specification

Foreword

If you think hard enough and long enough about serialization then you realize something remarkable: owwie ouch oof my thinking hurt

David Koloski, author of rkyv

Version and Stability

This document is a pre-release of version 1.1 of the Postcard Wire Specification, which describes the postcard wire format. It is not yet final.

Version 1.1 of the specification makes no changes to the postcard wire format itself. This specification version splits the wire format definition into layers, and clarifies and codifies behavior that was potentially unclear in version 1.0 of the specification.

Version 1.0 of this specification remains available as an archive at https://postcard.rs/wire/1.0/.

The postcard crate versions 1.x.y and postcard 2.x.y all implement the wire format described by the 1.x specifications, and will each produce the same encoding for the same value.

The postcard wire format is stable. A change to the encoding of any value would only be made in a new major version of this specification, and the postcard crate would only adopt it in a new major version of the crate.

Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 (RFC 2119, RFC 8174) when, and only when, they appear in all capitals, as shown here.

The recommendations in Implementation Considerations also use these key words, but are not tracked as requirements.

Terms such as type, value, encoding, message, encoder, decoder, atom, composite, element, field, variant, header, and schema have specific meanings in this specification, defined in the Glossary.

Each requirement of this specification is labelled with a tracey identifier, such as postcard[atom.varint.encoding.zigzag]. Implementations and tests refer to requirements by these identifiers, in comments. The first part of each identifier is the layer that the requirement belongs to: conformance, atom, comp (composites), schema, or serde.

Scope

This specification describes how a single message is encoded. It does not cover:

  • Framing, such as separating messages in a stream with COBS.
  • Integrity checks, such as a CRC or cryptographic digest appended to a message.
  • Versioning of messages or schemas, or how schemas are exchanged.

Libraries such as postcard provide framing and integrity checks as API features. They are not part of the specified wire format.

Non Self-Describing Format

Postcard is not a "Self Describing Format": a message contains only the encodings of its values, with no information about their types or names. The encoder and decoder of a message are expected to use the same schema, often from a shared Rust library of data types.

Organization of This Specification

This specification describes the wire format in the following layers:

  1. Atoms are types whose encoding is fully defined by this specification, such as integers, strings, and headers.
  2. Composites are types that contain values of other types chosen by the user, such as sequences, aggregates, and tagged unions.
  3. Schemas are the types used by both the encoder and decoder of a message, and the requirements that are checked against those types.
  4. Bindings describe how a library encodes its own types. The Serde Binding describes how each type of the Serde Data Model is encoded.
  5. Implementation Considerations describes concerns that the wire format does not cover, but which matter to authors of libraries based on the postcard wire format.

Within the postcard repository:

  1. The postcard-core crate encodes and decodes Atoms.
  2. The postcard crate implements Composites and the schema requirements, and uses postcard-core for Atoms. It also implements The Serde Binding.
  3. The postcard-schema crate describes the Schema of a Rust type as a value, which can be stored, sent, or compared at compile or runtime.
  4. The postcard-dyn crate encodes and decodes messages using a schema known only at runtime, converting them to and from JSON values.

Each crate is checked only against the requirements of the layers it implements, so neither crate's tracey coverage reaches 100% on its own. postcard-core covers the conformance and atom requirements, and postcard covers the composite, schema, and serde requirements. Together, they cover every requirement. postcard-dyn is not yet traced.

postcard-schema is traced against the separate Postcard Schema Specification, which also defines postcard-schema's Keys.

Conformance

An encoder produces messages as a sequence of bytes, and a decoder consumes them.

api.rs:18 wire.rs:795

When a decoder rejects a message, it MUST report an error, and MUST NOT produce a value from it.

flavors.rs:33 +1 wire.rs:720

A decoder MUST reject a message if its input ends before the message is fully decoded.

lib.rs:90 wire.rs:534 +1

A conforming encoder MUST only produce messages that meet all encoding requirements of this specification.

lib.rs:88 wire.rs:834

A conforming decoder MUST reject a message where this specification requires it, and MUST accept every other message that a conforming encoder can produce for the decoder's schema, unless the message exceeds one of the decoder's Resource Limits.

References

Document NameFull NameVersion
Serde BookThe Serde Bookserde v1.0.229
Unicode 14.0 Chapter 3The Unicode® Standard Core Specification, Chapter 3: Conformancev14.0
IEEE 754-2008IEEE Standard for Floating-Point Arithmetic2008
BCP 14Key words for use in RFCs to Indicate Requirement LevelsRFC 2119, RFC 8174

License

The Postcard Wire Specification (this document) is licensed under the terms of the CC-BY-SA 4.0 license.

The full license text is in spec/tracey/LICENSE-CC-BY-SA in the postcard repository.

Portions of the Serde Data Model are included under the terms of the CC-BY-SA 4.0 license.

Atoms

An atom is a type whose encoding is fully defined by this specification. An atom contains no values of types defined by the user.

Atom Types

This specification defines the following atom types, where P is the pointer width, in bits, of the platform encoding or decoding the value.

TypeValuesEncoding
unitThe single value ()Zero bytes
booltrue or falseOne byte
u8Integers in 0..=(2^8 - 1)One byte
u16Integers in 0..=(2^16 - 1)varint(u16)
u32Integers in 0..=(2^32 - 1)varint(u32)
u64Integers in 0..=(2^64 - 1)varint(u64)
u128Integers in 0..=(2^128 - 1)varint(u128)
usizeIntegers in 0..=(2^P - 1)varint(usize)
i8Integers in -(2^7)..=(2^7 - 1)One byte
i16Integers in -(2^15)..=(2^15 - 1)varint(i16)
i32Integers in -(2^31)..=(2^31 - 1)varint(i32)
i64Integers in -(2^63)..=(2^63 - 1)varint(i64)
i128Integers in -(2^127)..=(2^127 - 1)varint(i128)
isizeIntegers in -(2^(P-1))..=(2^(P-1) - 1)varint(isize)
f32IEEE 754 "binary32" valuesFour bytes
f64IEEE 754 "binary64" valuesEight bytes
bytesAny number of bytesLength-prefixed
stringAny number of bytes that are valid UTF-8Length-prefixed
charA single Unicode scalar valueLength-prefixed

Headers, such as lengths and discriminants, are also atoms. A header only appears in the encoding of another type, and is not used directly in a schema.

varint-Encoded Integers

Integers other than u8 and i8 are encoded in a variable-length format, commonly known as unsigned LEB128, or "varint". varint(N) refers to the varint encoding of the integer type N, such as varint(u16).

de.rs:42 +2 wire.rs:105 +1

All varint(N) types MUST be encoded as a variable length stream of bytes, as follows:

  • The most significant bit of each byte is a "continuation" flag: 1 if another byte follows, and 0 on the last byte.
  • The seven least significant bits of each byte are data bits.
de.rs:43 +2 wire.rs:106 +1

All varint(N) types MUST be encoded in "little endian" order, meaning that the first byte contains the least significant seven data bits, and each following byte contains the next seven more significant data bits.

de.rs:68 +15 wire.rs:198 +1

Every integer type other than u8 and i8 MUST be encoded as a varint of its own type, such as varint(u16) for a u16, as listed in Atom Types.

Unsigned Integer Encoding

For example, the following 16-bit unsigned numbers would be encoded as follows:

DecHexvarint EncodedLength
00x00_00[0x00]1
1270x00_7F[0x7F]1
1280x00_80[0x80, 0x01]2
163830x3F_FF[0xFF, 0x7F]2
163840x40_00[0x80, 0x80, 0x01]3
163850x40_01[0x81, 0x80, 0x01]3
655350xFF_FF[0xFF, 0xFF, 0x03]3

Signed Integer Encoding

In Two's Complement form, every negative value has its most significant bit set, so a negative value encoded directly would always take the maximum encoded length.

varint.rs:160 +7 wire.rs:125 +2

A signed integer MUST be Zigzag encoded before it is encoded as a varint. The zigzag value of a signed integer n is 2n if n is zero or positive, and -2n - 1 if n is negative.

A decoder reverses this: a zigzag value z whose least significant bit is zero decodes as z / 2, and one whose least significant bit is one decodes as -(z / 2) - 1.

For example, the following 16-bit signed numbers would be encoded as follows:

DecHex*Zigzag (hex)varint EncodedLength
00x00_000x00_00[0x00]1
-10xFF_FF0x00_01[0x01]1
10x00_010x00_02[0x02]1
630x00_3F0x00_7E[0x7E]1
-640xFF_C00x00_7F[0x7F]1
640x00_400x00_80[0x80, 0x01]2
-650xFF_BF0x00_81[0x81, 0x01]2
327670x7F_FF0xFF_FE[0xFE, 0xFF, 0x03]3
-327680x80_000xFF_FF[0xFF, 0xFF, 0x03]3

*: This column is represented as a sixteen bit, two's complement form

Maximum Encoded Length

varint.rs:22 wire.rs:208 +2

As varints encode seven data bits for every encoded byte, the maximum encoded length in bytes of a varint(N) is defined as ceil(W / 7), where W is the width of N in bits.

The following table expresses the maximum encoded length for each type:

TypeWidth (bits)Maximum encoded length (bytes)
u16163
i16163
u32325
i32325
u646410
i646410
u12812819
i12812819
usize16, 32, or 643, 5, or 10
isize16, 32, or 643, 5, or 10

Canonicalization

A varint(N) is canonical if it uses the fewest bytes that can encode its value.

ser.rs:16 +1 wire.rs:218

An encoder MUST always produce the canonical encoded form of a varint(N).

A decoder MUST accept a non-canonical varint(N) that meets atom.varint.decode.max-len and atom.varint.decode.max-value.

de.rs:45 wire.rs:300

A decoder MUST reject a varint(N) that is longer than the Maximum Encoded Length of N.

de.rs:46 +1 wire.rs:265 +2

A decoder MUST reject a varint(N) whose data bits form a value greater than the maximum value of the unsigned type with the same width as N.

For example, the zigzag value of an i16 cannot exceed the maximum value of a u16.

For example, in the following u16 encoded data:

DataEncoded FormCanonical?Accepted?
0[0x00]YesYes
0[0x80, 0x00]No*Yes
0[0x80, 0x80, 0x00]No*Yes
0[0x80, 0x80, 0x80, 0x00]No*No**
65535[0xFF, 0xFF, 0x03]YesYes
131071[0xFF, 0xFF, 0x07]—No***
65535[0xFF, 0xFF, 0x83, 0x00]No*No**
  • *: Contains excess encoding bytes
  • **: Exceeds the Maximum Encoded Length of the type
  • ***: Exceeds the maximum value of the encoded type

usize and isize

de.rs:96 +1 wire.rs:669

A usize MUST be encoded as the unsigned integer type matching the pointer width of the platform encoding it.

For example, on a platform with 32-bit pointers, usize maps to u32. On a platform with 64-bit pointers, usize maps to u64.

A usize encoded on one platform can be decoded on a platform with a different pointer width. As a result of atom.varint.decode.max-value, a decoder rejects a varint(usize) whose value exceeds the maximum value of its own usize. For example, 0x1_0000_0000usize, encoded on a 64-bit platform, is rejected on a 32-bit platform.

de.rs:149 +1 wire.rs:681

An isize MUST be encoded as the signed integer type matching the pointer width of the platform encoding it.

In the same way, a decoder rejects a varint(isize) whose zigzag value exceeds the maximum value of its own usize.

Fixed-Size Atoms

unit

ser.rs:30 wire.rs:9

A unit MUST be encoded as zero bytes.

de.rs:16 wire.rs:22

A decoder MUST decode a unit by consuming zero bytes.

bool

de.rs:23 +1 wire.rs:38

A bool MUST be encoded as a single byte, with the value 0x00 for false, and 0x01 for true.

de.rs:24 wire.rs:47

A decoder MUST reject a bool encoded as any byte other than 0x00 or 0x01.

u8

de.rs:35 +1 wire.rs:58

A u8 MUST be encoded as a single byte containing its value.

de.rs:36 wire.rs:67

A decoder MUST accept every value of a u8.

i8

de.rs:112 +1 wire.rs:89

An i8 MUST be encoded as a single byte, in two's complement form.

de.rs:113 wire.rs:78

A decoder MUST accept every value of an i8.

f32

An f32 is a "binary32" value, as defined in IEEE 754-2008.

de.rs:167 +1 wire.rs:332

An f32 MUST be encoded as its binary32 bit pattern, as four bytes in little-endian order.

For example, the float value -32.005859375f32 would be bitwise represented as 0xC200_0600u32, and encoded as [0x00, 0x06, 0x00, 0xC2].

de.rs:168 wire.rs:757

A decoder MUST accept every bit pattern of an f32. For a bit pattern that is not a NaN, it MUST produce the f32 with that bit pattern.

de.rs:169 wire.rs:758

For a NaN bit pattern, a decoder MUST produce a NaN, and SHOULD produce the f32 with that bit pattern.

f64

An f64 is a "binary64" value, as defined in IEEE 754-2008.

de.rs:179 +1 wire.rs:350

An f64 MUST be encoded as its binary64 bit pattern, as eight bytes in little-endian order.

For example, the float value -32.005859375f64 would be bitwise represented as 0xC040_00C0_0000_0000u64, and encoded as [0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x40, 0xC0].

de.rs:180 wire.rs:776

A decoder MUST accept every bit pattern of an f64. For a bit pattern that is not a NaN, it MUST produce the f64 with that bit pattern.

de.rs:181 wire.rs:777

For a NaN bit pattern, a decoder MUST produce a NaN, and SHOULD produce the f64 with that bit pattern.

Some platforms cannot preserve every NaN bit pattern. For example, a signalling NaN can become a quiet NaN when it is loaded into a floating point register, and some languages represent every NaN with the same bit pattern.

Length-Prefixed Atoms

A length-prefixed atom contains a Length, followed by that many bytes.

bytes

de.rs:191 +1 wire.rs:409

A bytes value MUST be encoded as a Length, followed by its bytes.

string

de.rs:201 +1 wire.rs:428

A string MUST be encoded as a Length, followed by its UTF-8 bytes.

de.rs:202 wire.rs:446

A decoder MUST reject a string whose bytes are not well-formed UTF-8, as defined by Unicode 14.0 Chapter 3 Section 3.9, Definition D92 and Table 3-7.

char

de.rs:210 +1 wire.rs:368

A char MUST be encoded in UTF-8 form, as a string.

de.rs:211 wire.rs:380

A decoder MUST reject a char whose string does not contain exactly one Unicode scalar value.

A Unicode scalar value is defined by Unicode 14.0 Chapter 3 Section 3.9, Definition D76, as any code point other than a surrogate: 0x0000..=0xD7FF or 0xE000..=0x10FFFF.

Headers

A header is an atom whose value determines the number or type of the values that follow it, in a Composite or a length-prefixed atom.

The bool that begins an Option is also considered a header, as it determines whether a value follows it.

Length

de.rs:263 +1 wire.rs:470

A length MUST be encoded as a varint(usize), containing the number of elements (for sequences), or bytes (for length-prefixed atoms), that follow it.

This specification does not limit a length, other than to the maximum value of usize. See Lengths.

Discriminant

de.rs:252 +1 wire.rs:461

A discriminant MUST be encoded as a varint(u32).

Composites

A composite is a type that contains values of other types chosen by the user. For example, an aggregate containing a bool, a u8, and an f32.

A composite is encoded as its Header, if it has one, followed by the values it contains.

Aggregate

An aggregate is a type with a fixed number of elements, each of which can be of a different type.

deserializer.rs:617 +5 composites.rs:14 +3

An aggregate MUST be encoded as its elements, in their order of definition.

As a result, the number of elements in an aggregate is not encoded, and an aggregate with no elements is encoded as zero bytes.

Sequence

A sequence is a type with a variable number of elements.

deserializer.rs:599 +3 composites.rs:54 +1

A sequence MUST be encoded as a Length, containing the number of elements, followed by each element in order.

deserializer.rs:208 +1 composites.rs:61

A decoder MUST decode exactly as many elements as the sequence's Length contains.

See Lengths and Nesting for limiting the length of a sequence or the nesting depth of composites.

Tagged Union

A tagged union is a type with several variants. A value of a tagged union contains a discriminant, which identifies a variant, and a value of that variant.

deserializer.rs:773 +4 composites.rs:89 +1

A tagged union MUST be encoded as a Discriminant identifying its variant, followed by the value of that variant.

The Schema defines the discriminant of each variant.

Option

An option is a type that contains zero or one value of another type.

deserializer.rs:540 +2 composites.rs:97 +2

An option MUST be encoded as a bool, which is true if a value is present, followed by the value if it is present.

Schemas

A schema is the type used by the encoder and decoder of a message, along with names for its types, fields, and variants. Names are never encoded.

The requirements in this chapter are checked against a specific schema, rather than against the bytes alone (Atoms) or the shape of a composite (Composites).

Types

deserializer.rs:281 schemas.rs:57

A decoder MUST decode each value as the type that the schema defines for it.

Aggregates

deserializer.rs:618 +3 schemas.rs:16

A decoder MUST decode exactly as many elements of an Aggregate as the schema defines.

Tagged Unions

A schema defines a distinct discriminant for each variant of a tagged union.

deserializer.rs:774 schemas.rs:44

A decoder MUST reject a Tagged Union whose Discriminant does not identify a variant that the schema defines.

Value Constraints

A type may constrain acceptable values further, such as a non-zero integer, or a collection with a maximum capacity. This specification does not define these constraints. A value that does not meet them is reported as an error, either while it is decoded or after.

Resource Limits

A decoder may also limit the resources it uses to decode a message, such as the number of elements it decodes, or how deeply composites nest (see Security). A message that exceeds such a limit is reported as an error, in the same way as a value that does not meet its type's constraints, even though a conforming encoder can produce it. These limits are chosen by each decoder, and are not defined by this specification.

The Serde Binding

This chapter describes how each type of the Serde Data Model is encoded. serde calls encoding serialization, and decoding deserialization.

With serde, a type's Serialize and Deserialize implementations are its Schema. For requirements checked against a schema, such as rejecting an unknown discriminant, a decoder is a serde Deserializer together with the Deserialize implementation of the type being decoded.

Tagged Unions

A Rust enum is a Tagged Union. In the Serde Data Model, a variant is identified by its variant_index, which serde_derive sets to the variant's position within the enum, starting at zero. Rust's own discriminant values, such as A = 5, and the #[repr] of an enum, are not used.

deserializer.rs:775 +4 serde_mapping.rs:422

The Discriminant of a serde variant MUST be its variant_index.

Serde Data Model Types

Each section below quotes the Serde Data Model's description of one or more of its types, followed by the postcard type each is encoded as.

Primitive Types

  • 14 primitive types
    • bool
    • i8, i16, i32, i64, i128
    • u8, u16, u32, u64, u128
    • f32, f64
    • char
deserializer.rs:306 +1 serde_mapping.rs:30

A serde bool MUST be encoded as a postcard bool.

deserializer.rs:319 +1 serde_mapping.rs:44

A serde i8 MUST be encoded as a postcard i8.

deserializer.rs:331 +1 serde_mapping.rs:59

A serde i16 MUST be encoded as a postcard i16.

deserializer.rs:344 +1 serde_mapping.rs:76

A serde i32 MUST be encoded as a postcard i32.

deserializer.rs:357 +1 serde_mapping.rs:93

A serde i64 MUST be encoded as a postcard i64.

deserializer.rs:370 +1 serde_mapping.rs:110

A serde i128 MUST be encoded as a postcard i128.

deserializer.rs:383 +1 serde_mapping.rs:126

A serde u8 MUST be encoded as a postcard u8.

deserializer.rs:396 +1 serde_mapping.rs:134

A serde u16 MUST be encoded as a postcard u16.

deserializer.rs:409 +1 serde_mapping.rs:148

A serde u32 MUST be encoded as a postcard u32.

deserializer.rs:422 +1 serde_mapping.rs:162

A serde u64 MUST be encoded as a postcard u64.

deserializer.rs:435 +1 serde_mapping.rs:176

A serde u128 MUST be encoded as a postcard u128.

deserializer.rs:448 +1 serde_mapping.rs:190

A serde f32 MUST be encoded as a postcard f32.

deserializer.rs:461 +1 serde_mapping.rs:197

A serde f64 MUST be encoded as a postcard f64.

deserializer.rs:474 +1 serde_mapping.rs:206

A serde char MUST be encoded as a postcard char.

serde has no usize or isize type, and serializes the Rust usize and isize types as u64 and i64. The serde binding therefore does not use the usize and isize atoms: a Rust usize follows the requirements for u64, including its Maximum Encoded Length, on every platform. Lengths are still encoded as varint(usize).

string

  • string
    • UTF-8 bytes with a length and no null terminator. May contain 0-bytes.
    • When serializing, all strings are handled equally. When deserializing, there are three flavors of strings: transient, owned, and borrowed. This distinction is explained in Understanding deserializer lifetimes and is a key way that Serde enabled efficient zero-copy deserialization.
deserializer.rs:487 +3 serde_mapping.rs:217 +1

A serde string MUST be encoded as a postcard string.

All three flavors of a serde string are decoded from the same postcard encoding.

byte array

  • byte array - [u8]
    • Similar to strings, during deserialization byte arrays can be transient, owned, or borrowed.
deserializer.rs:513 +2 serde_mapping.rs:241

A serde byte array MUST be encoded as a postcard bytes value.

All three flavors of a serde byte array are decoded from the same postcard encoding.

option

  • option
    • Either none or some value.
deserializer.rs:539 +2 serde_mapping.rs:250

A serde option MUST be encoded as an Option.

unit

  • unit
    • The type of () in Rust. It represents an anonymous value containing no data.
deserializer.rs:558 +1 serde_mapping.rs:257

A serde unit MUST be encoded as a postcard unit.

unit_struct

  • unit_struct
    • For example struct Unit or PhantomData<T>. It represents a named value containing no data.
deserializer.rs:572 +1 serde_mapping.rs:266

A serde unit_struct MUST be encoded as a postcard unit.

unit_variant

  • unit_variant
    • For example the E::A and E::B in enum E { A, B }.
deserializer.rs:726 +1 serde_mapping.rs:280

A serde unit_variant MUST be encoded as a Tagged Union whose variant's value is a postcard unit.

newtype_struct

  • newtype_struct
    • For example struct Millimeters(u8).
deserializer.rs:585 +1 serde_mapping.rs:289

A serde newtype_struct MUST be encoded as the value it contains.

newtype_variant

  • newtype_variant
    • For example the E::N in enum E { N(u8) }.
deserializer.rs:732 +1 serde_mapping.rs:295

A serde newtype_variant MUST be encoded as a Tagged Union whose variant's value is the value it contains.

seq

  • seq
    • A variably sized heterogeneous sequence of values, for example Vec<T> or HashSet<T>. When serializing, the length may or may not be known before iterating through all the data. When deserializing, the length is determined by looking at the serialized data. Note that a homogeneous Rust collection like vec![Value::Bool(true), Value::Char('c')] may serialize as a heterogeneous Serde seq, in this case containing a Serde bool followed by a Serde char.
deserializer.rs:598 +1 serde_mapping.rs:301

A serde seq MUST be encoded as a Sequence of its elements.

serializer.rs:367 +1 serde_mapping.rs:377

When a seq or map is serialized without a known length, a serializer MUST either report an error, or buffer its elements until its length is known.

Its Length is encoded before its elements, so it cannot be encoded until the length is known.

tuple

  • tuple
    • A statically sized heterogeneous sequence of values for which the length will be known at deserialization time without looking at the serialized data, for example (u8,) or (String, u64, Vec<T>) or [u64; 10].
deserializer.rs:616 +1 serde_mapping.rs:308

A serde tuple MUST be encoded as an Aggregate of its elements.

tuple_struct

  • tuple_struct
    • A named tuple, for example struct Rgb(u8, u8, u8).
deserializer.rs:634 +1 serde_mapping.rs:318

A serde tuple_struct MUST be encoded as an Aggregate of its elements.

tuple_variant

  • tuple_variant
    • For example the E::T in enum E { T(u8, u8) }.
deserializer.rs:741 +1 serde_mapping.rs:324

A serde tuple_variant MUST be encoded as a Tagged Union whose variant's value is an Aggregate of its elements.

map

  • map
    • A variably sized heterogeneous key-value pairing, for example BTreeMap<K, V>. When serializing, the length may or may not be known before iterating through all the entries. When deserializing, the length is determined by looking at the serialized data.
deserializer.rs:648 +1 serde_mapping.rs:330

A serde map MUST be encoded as a Sequence of (key, value) Aggregates.

This specification does not require the keys of a map to be unique or ordered, and the type being decoded determines what happens to a repeated key. For example, serde's HashMap and BTreeMap implementations keep the last value for a repeated key, and BTreeMap serializes its pairs in key order.

struct

  • struct
    • A statically sized heterogeneous key-value pairing in which the keys are compile-time constant strings and will be known at deserialization time without looking at the serialized data, for example struct S { r: u8, g: u8, b: u8 }.
deserializer.rs:666 +1 serde_mapping.rs:343

A serde struct MUST be encoded as an Aggregate of its fields.

deserializer.rs:667 +1 serde_mapping.rs:536

A deserializer MUST present a serde struct or struct_variant to its visitor as a sequence of its fields, in order, by calling visit_seq.

struct_variant

  • struct_variant
    • For example the E::S in enum E { S { r: u8, g: u8, b: u8 } }.
deserializer.rs:752 +1 serde_mapping.rs:349

A serde struct_variant MUST be encoded as a Tagged Union whose variant's value is an Aggregate of its fields.

Human-Readable Formats

serde lets a type use a different representation in human-readable formats, such as a string for an IP address.

deserializer.rs:285 +1 serde_mapping.rs:466

A serializer and a deserializer MUST return false from is_human_readable.

Equivalent Encodings

Several serde types are encoded as the same postcard type, and so have the same encoding. For example, a tuple, a tuple_struct, and a struct with the same elements are each an Aggregate, and a map and a seq of (key, value) tuples are each a Sequence of aggregates. See Wire Compatibility for the postcard types that share an encoding.

Serde Features That Need a Self-Describing Format

Postcard does not support serde features that use deserialize_any. See Serde Attributes for the attributes that use it, and others that cause issues.

As postcard is not self-describing, deserializers do not support the following hints:

deserializer.rs:292 serde_mapping.rs:391

A deserializer MUST report an error when asked to deserialize_any.

deserializer.rs:696 serde_mapping.rs:401

A deserializer MUST report an error when asked to deserialize_identifier.

deserializer.rs:709 serde_mapping.rs:411

A deserializer MUST report an error when asked to deserialize_ignored_any.

Serde Attributes

This section is informative, and contains no requirements. The attributes were checked with serde_derive 1.0.229, apart from those that only change the generated code.

Attributes Believed to Cause Issues With Postcard

The following attributes can make encoding and decoding disagree, or cause an error.

#[serde(tag = "...")] on an enum, and #[serde(untagged)] on an enum or a variant

Decoding uses deserialize_any, which reports an error.

#[serde(tag = "...")] on a struct

The tag is encoded as an extra string before the fields, but not expected when decoding, so the fields decode as the wrong values.

#[serde(tag = "...", content = "...")], #[serde(field_identifier)], and #[serde(variant_identifier)]

Decoding uses deserialize_identifier, which reports an error.

#[serde(other)]

On an enum without tag, a discriminant that the decoding type does not define decodes as the other variant. The value of the unknown variant is not decoded, so the values that follow it decode as the wrong values. On an enum with tag, or with tag and content, decoding reports an error, as above.

#[serde(flatten)]

Encoding serializes a map with an unknown length, which reports an error.

#[serde(skip_serializing)] on a field, and #[serde(skip_serializing_if = "...")]

The field is not encoded, but is decoded, so the message fails to decode, or decodes as the wrong value using the bytes that follow it. For skip_serializing_if, this happens whenever the condition holds.

#[serde(skip_deserializing)] on a field

The field is encoded, but not decoded, so the fields after it decode as the wrong values.

#[serde(skip)] or #[serde(skip_deserializing)] on a variant

An encoder uses each variant's position among all of the variants, while a decoder leaves out the skipped variant. A variant after a skipped one fails to decode, or decodes as the wrong variant.

Attributes Believed Not to Cause Issues With Postcard

The following attributes are believed not to cause errors, or a mismatch between encoding and decoding:

  • serde(transparent)
  • serde(from = "..."), serde(try_from = "..."), serde(into = "...")
  • serde(deny_unknown_fields)
  • serde(default), serde(default = "...")
  • serde(rename = "..."), serde(rename_all = "..."), serde(rename_all_fields = "...")
  • serde(alias = "...")
  • serde(skip), on a field
  • serde(skip_serializing), on a variant
  • serde(with = "..."), serde(serialize_with = "..."), serde(deserialize_with = "..."), when they encode and decode the same type
  • serde(bound = "..."), serde(crate = "..."), serde(expecting = "..."), serde(remote = "..."), serde(getter = "..."), and serde(borrow), which only change the generated code

Implementation Considerations

This chapter describes concerns that the wire format does not cover. It contains no requirements.

Security

Decoders often decode messages from untrusted sources.

The limits recommended below are Resource Limits: a message that exceeds one is rejected, even if it would otherwise be considered valid.

Lengths

A decoder SHOULD NOT allocate memory based on a Length before checking it against the bytes remaining, or against its own limit.

Checking a length against the bytes remaining does not limit the time spent decoding. An element can be encoded as zero bytes, such as a unit or an empty Aggregate, so a short message can contain a sequence of many such elements. A decoder SHOULD limit the number of elements it decodes from an untrusted message.

Nesting

A schema that contains itself, such as a tree, can nest without limit. A decoder that recurses for each level of nesting can overflow its stack. A decoder SHOULD limit how deeply it nests when decoding untrusted messages.

Malformed Messages

A decoder that panics or aborts on a malformed message, instead of reporting an error (see Conformance), can be made to crash by any sender.

Hash Collisions

A map decoded into a hash table uses keys chosen by the sender, who can choose keys whose hashes collide, so that decoding takes excessive time. The type being decoded chooses the hasher, not this specification. A decoder SHOULD use a hasher that the sender cannot predict, such as the RandomState hasher used by default in Rust's HashMap.

Interoperability

Comparing Encoded Messages

As decoders accept non-canonical varints (see Canonicalization), equal values can have different encodings. Floats are encoded bit for bit, so values that compare equal, such as 0.0 and -0.0, also have different encodings. A collection encoded in an unspecified order, such as a HashMap encoded in iteration order, can also encode equal values differently. Comparing or hashing encoded messages does not compare their values.

Message Boundaries

A message does not contain its own length. A decoder MAY stop at the end of a message, without decoding the bytes that follow it, so messages can be concatenated. The application decides whether bytes left after a message are an error.

Schema Evolution

Adding, removing, or reordering fields or variants generally changes how a schema's values are encoded, so the new schema is no longer wire compatible with the previous one. Users who need compatible revisions of a schema are responsible for keeping them compatible.

Wire Compatibility

Two schemas are wire compatible if they are identical once all names are removed. Messages of one can be decoded as the other, subject to any Value Constraints.

Schemas that differ only by replacing a type with another type of the same encoding are also wire compatible, for the values whose encodings match. For example, the following types have the same encoding as each other:

  • bytes, and a Sequence of u8.
  • string, and bytes containing the same bytes. bytes decode as a string only if they are valid UTF-8.
  • char, and a string containing it. A string decodes as a char only if it contains exactly one Unicode scalar value.
  • Unsigned integers of different widths, such as u16 and u32, other than u8. A value decodes as the narrower type only if it fits. The same applies to signed integers other than i8.
  • unit, and an Aggregate with no elements.
  • An aggregate with one element, and that element.
  • bool, and a Tagged Union whose variants with discriminants 0 and 1 each contain unit.
  • An Option, and a tagged union whose variant with discriminant 0 contains unit, and whose variant with discriminant 1 contains the option's value.

Glossary

These words have specific meanings throughout this specification.

Aggregate

A Composite with a fixed number of elements, each of which can be of a different type, such as a struct or tuple. See Aggregate.

Atom

A type whose encoding is fully defined by this specification. An atom contains no values of types defined by the user. See Atoms.

Byte

An octet: eight bits.

Composite

A type that contains values of other types chosen by the user: an aggregate, a sequence, a tagged union, or an option. See Composites.

Decoder

Something that decodes a message, and either produces a value or rejects the message. In the Serde Binding, a decoder is a serde Deserializer together with the Deserialize implementation of the type being decoded.

Discriminant

The Header of a tagged union: a varint(u32) that identifies one of its variants. See Discriminant.

Element

A value contained in an aggregate or a sequence.

Encoder

Something that produces the encoding of a value. In the Serde Binding, a serde Serializer is an encoder.

Encoding

The bytes that represent a value. A value that is encoded as another type has the same encoding as the corresponding value of that type.

Field

A named element, such as one in a struct.

Header

An atom whose value determines the number or type of the values that follow it, in a composite or a length-prefixed atom: a length, a discriminant, or the bool of an option. See Headers.

Length

The Header of a sequence or a length-prefixed atom: a varint(usize) containing the number of elements, or bytes, that follow it. See Length.

Length-Prefixed Atom

An atom that contains a Length, followed by that many bytes: a bytes value, a string, or a char. See Length-Prefixed Atoms.

Message

The encoding of a single value of a schema.

Option

A Composite that contains zero or one value of another type. See Option.

Schema

The type used by the encoder and decoder of a message, along with names for its types, fields, and variants. Names are never encoded. See Schemas.

Sequence

A Composite with a variable number of elements. See Sequence.

Tagged Union

A Composite with several variants. Each of its values contains a Discriminant that identifies a variant, and a value of that variant. Known in Rust as an enum. See Tagged Union.

Type

A set of possible values, and how each value is encoded. Atoms, composites, and schemas are all types. A requirement that refers to a type applies to every value of that type.

Value

A single instance of a type.

Variant

One of the alternative types of a tagged union.

varint

The variable-length encoding of an integer, written varint(N) for an integer type N. See varint-Encoded Integers.