Crate serde_detach

Source
Expand description

Nudges Serde to deserialise into fully owned ('static) instances where this is possible.

This is primarily useful when you have a structure that can optionally borrow the input (Think [Cow<str>] or [Cow<[u8]>].), but a deserialiser that requires [DeserializeOwned] (which unfortunately seems to be common).

Deserialising borrow-only types (like plain references) naturally leads to a runtime error with this method.

§Example

Given:

use {
    serde_detach::detach,
    serde_object::Object,
    serde_taml::de::from_str,
};

let input = "key: \"value\"".to_string();

This does not compile, since [Object] tries to borrow from the input:

# use {serde_detach::detach, serde_object::Object, serde_taml::de::from_str};
# let input = "key: \"value\"".to_string();
let object: Object<'static> = from_str(&input, &mut ())?;
//          ---------------            ^^^^^^ borrowed value does not live long enough
//          |
//          type annotation requires that `input` is borrowed for `'static`
# Ok::<_, serde_taml::de::Error>(())

This works:

# use {serde_detach::detach, serde_object::Object, serde_taml::de::from_str};
# let input = "key: \"value\"".to_string();
let object: Object<'static> = from_str(&input, &mut ()).map(detach)?;
# Ok::<_, serde_taml::de::Error>(())

Structs§

Functions§

  • Gently nudges the compiler into deserialising as Detach<T> and unwraps it.