[][src]Struct serde_str_helpers::DeserBorrowStr

pub struct DeserBorrowStr<'a>(_);

This is a helper for deserializing using TryFrom more efficiently.

When using #[serde(try_from = "String"] when deserializing a value that doesn't neet to hold the string (e.g. an integer value) serde would allocate the string even if it doesn't have to.

A naive idea is to use std::borrow::Cow to solve it. Sadly, the implementation of Deserialize for Cow<'de, str> doesn't borrow the string, so it still allocates needlessly. This helper solves the issue.

Our DeserBorrowStr is written such that it borrows the str when possible, avoiding the allocation. It may still need to allocate, for example if string decoding (unescaping) has to be performed.

Example

use serde_derive::Deserialize;
use serde_str_helpers::DeserBorrowStr;
use core::convert::TryFrom;

#[derive(Deserialize)]
#[serde(try_from = "DeserBorrowStr")]
struct StringlyNumber(u64);

impl<'a> TryFrom<DeserBorrowStr<'a>> for StringlyNumber {
    type Error = core::num::ParseIntError;

    fn try_from(value: DeserBorrowStr<'a>) -> Result<Self, Self::Error> {
        value.parse().map(StringlyNumber)
    }
}

let x = serde_json::from_str::<StringlyNumber>("\"42\"").expect("Failed to deserialize");

assert_eq!(x.0, 42);

Trait Implementations

impl<'a> AsRef<str> for DeserBorrowStr<'a>[src]

impl<'a> Borrow<str> for DeserBorrowStr<'a>[src]

impl<'a> Deref for DeserBorrowStr<'a>[src]

type Target = str

The resulting type after dereferencing.

impl<'de: 'a, 'a> Deserialize<'de> for DeserBorrowStr<'a>[src]

impl<'a> From<Cow<'a, str>> for DeserBorrowStr<'a>[src]

impl<'a> From<DeserBorrowStr<'a>> for Cow<'a, str>[src]

impl<'a> From<DeserBorrowStr<'a>> for String[src]

Auto Trait Implementations

impl<'a> RefUnwindSafe for DeserBorrowStr<'a>

impl<'a> Send for DeserBorrowStr<'a>

impl<'a> Sync for DeserBorrowStr<'a>

impl<'a> Unpin for DeserBorrowStr<'a>

impl<'a> UnwindSafe for DeserBorrowStr<'a>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> DeserializeOwned for T where
    T: for<'de> Deserialize<'de>, 
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.