federation-api: Move Visitor declaration into deserialize function

This commit is contained in:
Jonas Platte 2020-12-15 14:35:46 +01:00
parent 212153ea5f
commit 87e821094c
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67

View File

@ -7,6 +7,12 @@ use serde::{
Deserialize, Serialize, Deserialize, Serialize,
}; };
#[derive(Deserialize, Serialize)]
struct WrappedError {
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
pub fn serialize<S>( pub fn serialize<S>(
response: &BTreeMap<EventId, Result<(), String>>, response: &BTreeMap<EventId, Result<(), String>>,
serializer: S, serializer: S,
@ -33,39 +39,33 @@ pub fn deserialize<'de, D>(
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
deserializer.deserialize_map(PduProcessResponseVisitor) struct PduProcessResponseVisitor;
}
#[derive(Deserialize, Serialize)] impl<'de> Visitor<'de> for PduProcessResponseVisitor {
struct WrappedError { type Value = BTreeMap<EventId, Result<(), String>>;
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
struct PduProcessResponseVisitor; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("A map of EventIds to a map of optional errors")
impl<'de> Visitor<'de> for PduProcessResponseVisitor { }
type Value = BTreeMap<EventId, Result<(), String>>;
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { where
formatter.write_str("A map of EventIds to a map of optional errors") M: MapAccess<'de>,
} {
let mut map = BTreeMap::new();
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where while let Some((key, value)) = access.next_entry::<EventId, WrappedError>()? {
M: MapAccess<'de>, let v = match value.error {
{ None => Ok(()),
let mut map = BTreeMap::new(); Some(error) => Err(error),
};
while let Some((key, value)) = access.next_entry::<EventId, WrappedError>()? { map.insert(key, v);
let v = match value.error { }
None => Ok(()), Ok(map)
Some(error) => Err(error),
};
map.insert(key, v);
} }
Ok(map)
} }
deserializer.deserialize_map(PduProcessResponseVisitor)
} }
#[cfg(test)] #[cfg(test)]