Skip to content

Commit

Permalink
Distinguish between custom and flattened variant errors
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtoth committed Feb 2, 2024
1 parent ede9762 commit dce846a
Showing 1 changed file with 40 additions and 18 deletions.
58 changes: 40 additions & 18 deletions serde/src/private/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2587,17 +2587,43 @@ where
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatMapDeserializer<'a, 'de: 'a, E>(
pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>,
pub PhantomData<E>,
);
#[cfg_attr(any(feature = "std", feature = "alloc"), derive(Debug))]
pub enum FlatMapDeserializerError {
Message(String),
NoVariantFoundInFlattenedData(&'static str),
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E>
where
E: Error,
{
fn deserialize_other<V>() -> Result<V, E> {
impl Display for FlatMapDeserializerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FlatMapDeserializerError::Message(msg) => write!(f, "{}", msg),
FlatMapDeserializerError::NoVariantFoundInFlattenedData(name) => {
write!(f, "no variant of enum {} found in flattened data", name)
}
}
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl std::error::Error for FlatMapDeserializerError {}

#[cfg(any(feature = "std", feature = "alloc"))]
impl Error for FlatMapDeserializerError {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
FlatMapDeserializerError::Message(msg.to_string())
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub struct FlatMapDeserializer<'a, 'de: 'a>(pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>);

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de> FlatMapDeserializer<'a, 'de> {
fn deserialize_other<V>() -> Result<V, FlatMapDeserializerError> {
Err(Error::custom("can only flatten structs and maps"))
}
}
Expand All @@ -2617,11 +2643,8 @@ macro_rules! forward_to_deserialize_other {
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E>
where
E: Error,
{
type Error = E;
impl<'a, 'de> Deserializer<'de> for FlatMapDeserializer<'a, 'de> {
type Error = FlatMapDeserializerError;

fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
Expand All @@ -2645,10 +2668,9 @@ where
}
}

Err(Error::custom(format_args!(
"no variant of enum {} found in flattened data",
name
)))
Err(FlatMapDeserializerError::NoVariantFoundInFlattenedData(
name,
))
}

fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
Expand Down

0 comments on commit dce846a

Please sign in to comment.