use std::{fmt, marker::PhantomData, str::FromStr}; use ruma::{CanonicalJsonError, CanonicalJsonObject, canonical_json::try_from_json_map}; use crate::Result; /// Fallible conversion from any value that implements `Serialize` to a /// `CanonicalJsonObject`. /// /// `value` must serialize to an `serde_json::Value::Object`. pub fn to_canonical_object( value: T, ) -> Result { use CanonicalJsonError::SerDe; use serde::ser::Error; match serde_json::to_value(value).map_err(SerDe)? { | serde_json::Value::Object(map) => try_from_json_map(map), | _ => Err(SerDe(serde_json::Error::custom("Value must be an object"))), } } pub fn deserialize_from_str<'de, D, T, E>(deserializer: D) -> Result where D: serde::de::Deserializer<'de>, T: FromStr, E: fmt::Display, { struct Visitor, E>(PhantomData); impl serde::de::Visitor<'_> for Visitor where T: FromStr, Err: fmt::Display, { type Value = T; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "a parsable string") } fn visit_str(self, v: &str) -> Result where E: serde::de::Error, { v.parse().map_err(serde::de::Error::custom) } } deserializer.deserialize_str(Visitor(PhantomData)) }