Improved serde support

main
Pantonshire 3 years ago
parent 0b4dbc6bc5
commit 45ae1c68eb

@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[features]
default = ["std", "serde"]
default = ["std"]
alloc = ["serde?/alloc"]
std = ["serde?/std"]

@ -5,11 +5,16 @@ use core::{
fmt,
hash::{Hash, Hasher},
ops,
str::FromStr,
str::{self, from_utf8},
};
#[cfg(not(feature = "std"))]
use alloc::{borrow::Cow, boxed::Box, string::String};
use alloc::{
borrow::{Cow, ToOwned},
boxed::Box,
string::String,
vec::Vec,
};
#[cfg(feature = "std")]
use std::borrow::Cow;
@ -292,7 +297,7 @@ impl<const N: usize> Hash for InliningString<N> {
}
}
impl<const N: usize> FromStr for InliningString<N> {
impl<const N: usize> str::FromStr for InliningString<N> {
type Err = Infallible;
#[inline]
@ -331,7 +336,53 @@ impl<'de, const N: usize> serde::Deserialize<'de> for InliningString<N> {
where
D: serde::Deserializer<'de>,
{
serde::Deserialize::deserialize(deserializer).map(Self::new::<Cow<'de, str>>)
use serde::de::{Error, Unexpected, Visitor};
struct InliningStringVisitor<const N: usize>;
impl<'de, const N: usize> Visitor<'de> for InliningStringVisitor<N> {
type Value = InliningString<N>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a string")
}
fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
#[cfg(feature = "std")] {
println!("visit &str \"{}\"", v);
}
Ok(Self::Value::new(v))
}
fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
#[cfg(feature = "std")] {
println!("visit String \"{}\"", v);
}
Ok(Self::Value::new(v))
}
fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
#[cfg(feature = "std")] {
println!("visit &[u8] {:?}", v);
}
str::from_utf8(v)
.map(Self::Value::new)
.map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
}
fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
#[cfg(feature = "std")] {
println!("visit Vec<u8> {:?}", v);
}
String::from_utf8(v)
.map(Self::Value::new)
.map_err(|err| {
Error::invalid_value(Unexpected::Bytes(&err.into_bytes()), &self)
})
}
}
deserializer.deserialize_string(InliningStringVisitor)
}
}

Loading…
Cancel
Save