Hasty Briefsbeta

Bilingual

Serde's zero-copy borrowing can be treacherous

4 months ago
  • #Rust
  • #zero-copy
  • #serde
  • Be cautious when using &'a str or &'a [u8] with serde deserializers as it may lead to runtime errors if zero-copy deserialization isn't possible.
  • serde is Rust's standard serialization/deserialization framework, known for its flexibility and broad usage.
  • Zero-copy deserialization in serde allows returning borrowed references into input data, but fails with escaped characters in formats like JSON.
  • The issue with escaped characters (e.g., \n) in JSON inputs means serde cannot return a &str pointing to the original data, leading to runtime errors.
  • Workarounds include using String instead of &str or Cow<'a, str> with #[serde(borrow)] to handle cases where borrowing isn't possible.