[−][src]Struct serde_str_helpers::DeserBorrowStr
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]
impl<'de: 'a, 'a> Deserialize<'de> for DeserBorrowStr<'a>
[src]
pub fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
[src]
__D: Deserializer<'de>,
impl<'a> From<Cow<'a, str>> for DeserBorrowStr<'a>
[src]
impl<'a> From<DeserBorrowStr<'a>> for Cow<'a, str>
[src]
pub fn from(value: DeserBorrowStr<'a>) -> Self
[src]
impl<'a> From<DeserBorrowStr<'a>> for String
[src]
pub fn from(value: DeserBorrowStr<'a>) -> Self
[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]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
pub fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> DeserializeOwned for T where
T: for<'de> Deserialize<'de>,
[src]
T: for<'de> Deserialize<'de>,
impl<T> From<T> for T
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,