2025-04-27 02:39:28 +00:00
|
|
|
use std::{fmt, marker::PhantomData, str::FromStr};
|
2024-05-27 20:05:33 +00:00
|
|
|
|
2025-09-23 04:26:55 +00:00
|
|
|
use ruma::{
|
|
|
|
|
CanonicalJsonError, CanonicalJsonObject, canonical_json::try_from_json_map, serde::Raw,
|
|
|
|
|
};
|
2024-05-27 20:05:33 +00:00
|
|
|
|
|
|
|
|
use crate::Result;
|
|
|
|
|
|
2025-09-23 04:26:55 +00:00
|
|
|
/// Perform a round-trip through serde_json starting with a native type T and
|
|
|
|
|
/// ending with a Ruma Raw<U> which is usually just T.
|
|
|
|
|
pub fn to_raw<T: serde::Serialize, U>(input: T) -> Result<Raw<U>> {
|
|
|
|
|
Ok(serde_json::from_value(serde_json::to_value(input)?)?)
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-27 20:05:33 +00:00
|
|
|
/// Fallible conversion from any value that implements `Serialize` to a
|
|
|
|
|
/// `CanonicalJsonObject`.
|
|
|
|
|
///
|
|
|
|
|
/// `value` must serialize to an `serde_json::Value::Object`.
|
2024-12-15 00:05:47 -05:00
|
|
|
pub fn to_canonical_object<T: serde::Serialize>(
|
|
|
|
|
value: T,
|
|
|
|
|
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
|
2025-04-27 02:39:28 +00:00
|
|
|
use CanonicalJsonError::SerDe;
|
2024-05-27 20:05:33 +00:00
|
|
|
use serde::ser::Error;
|
|
|
|
|
|
2025-04-27 02:39:28 +00:00
|
|
|
match serde_json::to_value(value).map_err(SerDe)? {
|
2024-12-15 00:05:47 -05:00
|
|
|
| serde_json::Value::Object(map) => try_from_json_map(map),
|
2025-04-27 02:39:28 +00:00
|
|
|
| _ => Err(SerDe(serde_json::Error::custom("Value must be an object"))),
|
2024-05-27 20:05:33 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-27 02:39:28 +00:00
|
|
|
pub fn deserialize_from_str<'de, D, T, E>(deserializer: D) -> Result<T, D::Error>
|
|
|
|
|
where
|
2024-12-15 00:05:47 -05:00
|
|
|
D: serde::de::Deserializer<'de>,
|
|
|
|
|
T: FromStr<Err = E>,
|
|
|
|
|
E: fmt::Display,
|
2025-04-27 02:39:28 +00:00
|
|
|
{
|
|
|
|
|
struct Visitor<T: FromStr<Err = E>, E>(PhantomData<T>);
|
|
|
|
|
|
|
|
|
|
impl<T, Err> serde::de::Visitor<'_> for Visitor<T, Err>
|
|
|
|
|
where
|
|
|
|
|
T: FromStr<Err = Err>,
|
|
|
|
|
Err: fmt::Display,
|
|
|
|
|
{
|
2024-05-27 20:05:33 +00:00
|
|
|
type Value = T;
|
|
|
|
|
|
|
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
write!(formatter, "a parsable string")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
|
|
|
|
where
|
|
|
|
|
E: serde::de::Error,
|
|
|
|
|
{
|
|
|
|
|
v.parse().map_err(serde::de::Error::custom)
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-04-27 02:39:28 +00:00
|
|
|
|
|
|
|
|
deserializer.deserialize_str(Visitor(PhantomData))
|
2024-05-27 20:05:33 +00:00
|
|
|
}
|