Sub topic 14
Zero-copy deserialization with borrowed data
This chapter assumes you know Rust lifetimes, the Deserialize derive, and serde_json::from_str. Here you will see how a deserialized value can borrow from its input instead of copying it.
Owned and borrowed deserialization
Most examples use String fields. Deserializing into a String allocates memory and copies the text out of the input. If the input is already in memory and outlives your result, you can skip that copy. A &str field points straight into the input buffer.
Serde calls this zero-copy deserialization. The derive macro adds a lifetime to the Deserialize impl. That lifetime ties the result to the input.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Message<'a> {
from: &'a str,
body: &'a str,
}
fn main() -> Result<(), serde_json::Error> {
let input = String::from(r#"{"from":"ada","body":"hello"}"#);
let msg: Message = serde_json::from_str(&input)?;
println!("{msg:?}");
Ok(())
}msg borrows from input. The compiler will not let msg outlive input, so you cannot return it from a function that owns the input.
When borrowing fails
JSON strings can contain escapes such as \n or \". The text in the buffer then differs from the decoded string, so serde has to build a new String. A &str field cannot hold that, and deserialization fails with an error.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Message<'a> {
body: &'a str,
}
fn main() {
let input = r#"{"body":"line one\nline two"}"#;
let result = serde_json::from_str::<Message>(input);
println!("{result:?}"); // Err(... invalid type: string "line one\nline two", expected a borrowed string ...)
}A plain &str field is therefore only safe when you control the input and know it has no escapes.
Borrowing when possible with Cow
Cow<'a, str> solves this. It borrows when it can and allocates when it must. By default serde does not borrow into a Cow field. It always produces the owned variant. You opt in with #[serde(borrow)].
use serde::Deserialize;
use std::borrow::Cow;
#[derive(Debug, Deserialize)]
struct Record<'a> {
#[serde(borrow)]
name: Cow<'a, str>,
}
fn main() -> Result<(), serde_json::Error> {
let input = String::from(r#"{"name":"Ada"}"#);
let record: Record = serde_json::from_str(&input)?;
println!("{record:?}");
let escaped = String::from(r#"{"name":"A\tda"}"#);
let record: Record = serde_json::from_str(&escaped)?;
println!("{record:?}");
Ok(())
}Both calls succeed. The first name is Cow::Borrowed. The second is Cow::Owned, because the tab escape forced a new string.
The attribute is needed because the derive cannot assume a Cow should borrow. &str and &[u8] fields borrow automatically.
DeserializeOwned
Some APIs need a value that does not borrow from its input, for example when you read from a stream or return the value from a function. They use the bound DeserializeOwned, which means for<'de> Deserialize<'de>. A type with a borrowed field does not satisfy it.
| Source of input | Borrowing possible? |
|---|---|
| `from_str`, `from_slice` | Yes |
| `from_reader` | No, so use owned types |
| Value returned past the input's lifetime | No, so use owned types |
Exercise
Why does a Cow<'a, str> field need #[serde(borrow)], and what does the field contain after deserializing "A\tda" from JSON?
Show answer
The derive does not borrow into Cow fields unless you ask, because it cannot assume borrowing is wanted. Without the attribute the field is always owned. With it, serde borrows when the string has no escapes. The text "A\tda" contains an escape, so the field holds Cow::Owned with the decoded string.
Exercise
Why can't you deserialize a struct with a &str field using serde_json::from_reader?
Show answer
A reader streams bytes and has no buffer that outlives the result for the &str to point into. from_reader requires DeserializeOwned, which a type with borrowed fields does not satisfy.