Sub topic 14
Zero-copy deserialization with borrowed data
This chapter assumes you know Rust lifetimes, can derive Serialize and Deserialize, and have used serde_json::from_str. Zero-copy deserialization lets a struct hold references into the input text instead of its own String allocations. You will see when serde does this, when it can't, and how to handle input that sometimes forces a copy.
Why copy at all?
A normal derived struct with String fields allocates a new heap buffer for each string and copies the bytes into it. The struct is then independent of the input. You can drop the input and keep the struct.
If the input text is already in memory and outlives the parsed value, those copies are wasted work. A parsed &str can point at the bytes inside the original JSON text. That is zero-copy deserialization. It saves allocations and memcpy calls, which matters when you parse many small records or large documents.
The cost is a lifetime. The parsed struct borrows from the input, so it cannot outlive it.
The `'de` lifetime
The Deserialize trait has a lifetime parameter:
trait Deserialize<'de>: Sized {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>;
}'de is the lifetime of the input data. A type may borrow from the input for at most 'de. When you derive Deserialize on a struct with its own lifetime parameter, such as Person<'a>, the derive adds a bound saying 'de outlives 'a. A struct without borrowed fields implements Deserialize<'de> for every 'de, so it doesn't care where the input lives.
Borrowing a `&str`
Fields of type &str and &[u8] borrow automatically. No attribute is needed.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Person<'a> {
name: &'a str,
city: &'a str,
}
fn main() -> Result<(), serde_json::Error> {
let input = String::from(r#"{"name":"Ada","city":"London"}"#);
let person: Person = serde_json::from_str(&input)?;
println!("{person:?}");
Ok(())
}Here person.name points directly into input. No new string was allocated for "Ada". The compiler enforces the lifetime link. If you drop or modify input while person is still in use, the code won't compile.
When borrowing fails: escape sequences
JSON strings can contain escapes such as \n or \". The text in the input is then different from the string's value. The input holds a backslash followed by an n, but the parsed string needs a real newline. serde_json must build a new buffer to hold the unescaped value, so it can't hand out a reference into the input.
A plain &str field can only be borrowed, so this is a runtime error:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Person<'a> {
name: &'a str,
city: &'a str,
}
fn main() {
let input = r#"{"name":"Ada \"A\"","city":"London"}"#;
let result: Result<Person, _> = serde_json::from_str(input);
match result {
Ok(person) => println!("{person:?}"),
// invalid type: string "Ada \"A\"", expected a borrowed string at ...
Err(err) => println!("error: {err}"),
}
}The type compiles, and the same struct succeeds on {"name":"Ada","city":"London"}. Whether it works depends on the data. That is the main trap of &str fields: a parser that passes your tests can fail in production when a name contains a quote or a Unicode escape.
`Cow<str>`: borrow when possible, allocate when needed
std::borrow::Cow ("clone on write") holds either a borrowed reference or an owned value. It fits this problem. serde can borrow when the string has no escapes and fall back to an owned String when it must.
There is a catch. Cow fields do not borrow by default. Without an attribute, serde always produces Cow::Owned, which is correct but allocates every time. You must 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 kind(value: &Cow<str>) -> &'static str {
match value {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
}
}
fn main() -> Result<(), serde_json::Error> {
let plain = r#"{"name":"Ada"}"#;
let escaped = r#"{"name":"Ada\nLovelace"}"#;
let a: Record = serde_json::from_str(plain)?;
let b: Record = serde_json::from_str(escaped)?;
println!("{}", kind(&a.name)); // borrowed
println!("{}", kind(&b.name)); // owned
Ok(())
}Both inputs parse. Only the one with an escape allocates. In most real data, escapes are rare, so most strings stay zero-copy.
Which field types borrow?
| Field type | Borrows? | Notes |
|---|---|---|
| `String` | No | Always allocates. Independent of the input. |
| `&'a str` | Yes, implicitly | Fails at runtime if the string contains escapes. |
| `&'a [u8]` | Yes, implicitly | Works with formats that expose raw bytes. |
| `Cow<'a, str>` | Only with `#[serde(borrow)]` | Borrowed when possible, owned otherwise. |
| `Vec<&'a str>` | Only with `#[serde(borrow)]` | Each element is borrowed, so each must be escape-free. |
For the last two rows, #[serde(borrow)] tells the derive to add the 'de: 'a bound for that field and to use a borrowing code path.
The input source matters
Borrowing is possible only when the whole input sits in memory and the deserializer can point into it.
serde_json::from_strandserde_json::from_slicecan borrow, because they read from a slice.serde_json::from_readercannot. It reads from a stream such as a file or socket in chunks and has nothing stable to point into. It requires a type that does not borrow.
The trait bound that expresses "owns all its data" is DeserializeOwned. It means for<'de> Deserialize<'de>: the type can be built from input of any lifetime, so it can't hold references into it.
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::io::Read;
#[derive(Debug, Deserialize)]
struct Person {
name: String,
}
fn load<T: DeserializeOwned, R: Read>(reader: R) -> serde_json::Result<T> {
serde_json::from_reader(reader)
}
fn main() -> serde_json::Result<()> {
let bytes: &[u8] = br#"{"name":"Ada"}"#;
let person: Person = load(bytes)?;
println!("{person:?}");
Ok(())
}If you wrote load::<Person<'_>, _> with a borrowing struct, the compiler would reject it because Person<'_> does not satisfy DeserializeOwned. Library code that deserializes from arbitrary readers usually takes this bound.
Lifetimes in practice
Borrowed structs spread lifetimes through your code. Three habits keep this manageable.
- Keep the input buffer alive in the same scope as the parsed value. Read the file into a
Stringinmain, then parse and process there. - Don't return a borrowed struct from a function that created the input locally. The input would be dropped on return. Either take the input as a parameter (
fn parse<'a>(input: &'a str) -> Result<Person<'a>, _>) or convert to an owned type before returning. - To store a parsed value long-term, convert it. Call
to_string()orinto_owned()on the borrowed fields, or deserialize into a separate owned struct.
Edge cases and gotchas
- Untagged and internally tagged enums. Serde buffers the input internally to try variants or find the tag. Borrowed fields inside such enums often can't borrow from the original input, and
&strfields may fail or need extra care. UseCowwith#[serde(borrow)]or owned types there, and test it. #[serde(flatten)]. Flattening uses the same internal buffering, with the same effect on borrowing.- Other formats. Whether a borrow succeeds depends on the format crate. Formats with binary strings, such as bincode, often borrow without escape problems. Formats with text escaping, like JSON and TOML, can force owned values.
- Measure first. For small inputs the allocation cost is usually negligible. Borrowed lifetimes make the API harder to use, so adopt them where profiling shows parsing is a bottleneck.
Exercise
A struct has the field title: Cow<'a, str> with no attributes, and it is parsed with serde_json::from_str from JSON that has no escapes in the title. Is the resulting value Cow::Borrowed or Cow::Owned? What single change makes the other case happen?
Show answer
It is Cow::Owned. Without #[serde(borrow)], serde deserializes Cow fields into owned values. Adding #[serde(borrow)] to the field makes the escape-free title Cow::Borrowed, pointing into the input text.
Exercise
You write a function fn read_person<R: std::io::Read>(reader: R) -> serde_json::Result<Person<'static>> that calls serde_json::from_reader, where Person<'a> has name: &'a str. Why can't this work, and what should you change?
Show answer
from_reader reads from a stream and has no persistent buffer to borrow from, so it requires a type that implements DeserializeOwned. A struct with &str fields does not. Change name to String (or Cow<'static, str> that is always owned), or read the whole input into a String first and call from_str with a lifetime tied to that buffer.