maciejhirsz / beef

Faster, more compact implementation of std::borrow::Cow
https://crates.io/crates/beef
Apache License 2.0
338 stars 17 forks source link

Specialize Deserialize to always borrow `Cow<str>` #44

Closed maciejhirsz closed 3 years ago

maciejhirsz commented 3 years ago

Since beef::Cow is only compatible with str and [T], we can specialize the serde::Deserialize for Cow<str> so that it always borrows when possible. This has the advantage over std::borrow::Cow when deserializing into Cow<str> directly:

let json = r#""foo""#;
let std_cow: std::borrow::Cow<str> = serde_json::from_str(json).unwrap(); // will always deserialize to `Cow::Owned` with an allocation
let beef_cow: beef::Cow<str> = serde_json::from_str(json).unwrap(); // will be borrowed since `foo` can be borrowed from the `json` slice