Sub topic 2
The serde data model as a common middle layer
This chapter assumes you know Rust structs, enums, and traits, and that you have read the overview of what serde does. It explains the idea that lets one set of Rust types work with many formats.
The problem the data model solves
Suppose you have M Rust types and N formats, such as JSON, TOML, and MessagePack. Writing code for every pair would take M × N pieces of code. Serde avoids this with a shared middle layer called the data model. It is a fixed list of shapes that data can take.
- Each Rust type describes itself in terms of the data model.
- Each format reads and writes the data model.
That leaves M + N pieces of code. A new type works with every existing format, and a new format works with every existing type.
What the data model contains
The data model has 29 types. You can group them as follows.
| Group | Types |
|---|---|
| Primitives | `bool`, `i8` to `i128`, `u8` to `u128`, `f32`, `f64`, `char` |
| Text and bytes | string, byte array |
| Absence | option, unit |
| Sequences | seq (variable length), tuple (fixed length) |
| Maps | map (arbitrary keys), struct (known field names) |
| Named wrappers | unit struct, newtype struct, tuple struct |
| Enum variants | unit variant, newtype variant, tuple variant, struct variant |
The data model describes the shape of data, not its Rust type. A Vec<u8> and a [i32; 3] both become a sequence or tuple. A HashMap<String, i32> becomes a map. A struct with named fields becomes a struct.
Seeing the mapping
The next program serializes three different Rust values. The format decides how each data model shape is written. JSON has no tuple struct, so it writes one as an array.
use serde::Serialize;
#[derive(Serialize)]
struct Point {
x: i32,
y: i32,
}
#[derive(Serialize)]
struct Pair(i32, i32);
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Point { x: 1, y: 2 })?); // {"x":1,"y":2}
println!("{}", serde_json::to_string(&Pair(1, 2))?); // [1,2]
println!("{}", serde_json::to_string(&Some(5u8))?); // 5
Ok(())
}Point is a data model struct, so JSON writes an object. Pair is a tuple struct, so JSON writes an array and drops the name. Some(5) is an option holding a value, and JSON writes just the value.
The Cargo.toml for this chapter needs serde with the derive feature and serde_json.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Where the layer lives in the code
The data model is not a Rust type that you build. It exists as the method set of two traits:
Serializemaps a Rust value onto the data model by calling methods such asserialize_structorserialize_seqon aSerializer.- A format implements
Serializer. Each method says how to write one data model shape.
Deserialization works in the other direction. A format implements Deserializer, and your type says which shape it expects. The next chapter covers these traits in detail.
Common mistakes
- Expecting identical output everywhere. The data model fixes the shapes, but each format chooses how to write them. An
Option::Nonebecomesnullin JSON. TOML has no null at all. - Assuming names always survive. A tuple struct's name is part of the data model, but JSON discards it. Formats may drop information that they cannot represent.
- Thinking of the model as an intermediate value. Serde does not build a tree of data model values in memory. Data passes straight from your type to the format, which is why serde is fast.
Exercise
How does serde avoid writing separate conversion code for every combination of Rust type and data format?
Show answer
Each Rust type maps itself onto the fixed set of data model shapes through the Serialize and Deserialize traits, and each format maps those shapes to and from its own syntax. Types and formats only meet at the data model, so adding a type or a format needs one new piece of code, not one per pairing.
Exercise
Which data model shape does struct Pair(i32, i32); use, and how does serde_json write Pair(1, 2)?
Show answer
It is a tuple struct. serde_json writes it as the JSON array [1,2], and the name Pair is not written.