Skip to main content

tuwunel_core/utils/
json.rs

1//! Serialization helpers for raw and canonical JSON values.
2//!
3//! The conversion functions bridge Serde values to Ruma's raw and canonical
4//! representations. A generic deserializer adapts string-backed fields to types
5//! implementing `FromStr`, and a lenient one reads a boolean that may arrive
6//! spelled as a string.
7
8use std::{borrow::Cow, fmt, io, marker::PhantomData, str::FromStr};
9
10use ruma::{
11	CanonicalJsonError, CanonicalJsonObject, canonical_json::try_from_json_map, serde::Raw,
12};
13use serde::{Deserialize, Deserializer, de::IgnoredAny};
14
15use crate::Result;
16
17/// An `io::Write` sink that counts bytes without buffering them.
18#[derive(Default)]
19struct Counter(usize);
20
21/// A boolean as a loosely typed source may spell it.
22#[derive(Deserialize)]
23#[serde(untagged)]
24enum LenientBool<'a> {
25	Bool(bool),
26	Str(#[serde(borrow)] Cow<'a, str>),
27	Other(IgnoredAny),
28}
29
30/// Serializes a value into Ruma's raw JSON representation.
31///
32/// The input is first converted to a `serde_json::Value`, then stored as
33/// `Raw<U>` without deserializing `U`. Serialization or JSON conversion
34/// failures are returned.
35pub fn to_raw<T: serde::Serialize, U>(input: T) -> Result<Raw<U>> {
36	Ok(serde_json::from_value(serde_json::to_value(input)?)?)
37}
38
39/// Converts a serializable value into a canonical JSON object.
40///
41/// The value must serialize to a JSON object. Serialization errors, non-object
42/// values, and data outside canonical JSON's representation are returned as
43/// `CanonicalJsonError`.
44pub fn to_canonical_object<T: serde::Serialize>(
45	value: T,
46) -> Result<CanonicalJsonObject, CanonicalJsonError> {
47	use CanonicalJsonError::SerDe;
48	use serde::ser::Error;
49
50	match serde_json::to_value(value).map_err(SerDe)? {
51		| serde_json::Value::Object(map) => try_from_json_map(map),
52		| _ => Err(SerDe(serde_json::Error::custom("Value must be an object"))),
53	}
54}
55
56/// Measures the length of a value's JSON serialization.
57///
58/// The value is written to a sink that counts bytes rather than retaining
59/// them, so the length costs no buffer. Serialization failures are returned.
60pub fn serialized_len<T: serde::Serialize>(value: &T) -> Result<usize> {
61	let mut counter = Counter::default();
62
63	serde_json::to_writer(&mut counter, value)?;
64
65	Ok(counter.0)
66}
67
68impl io::Write for Counter {
69	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
70		self.0 = self.0.saturating_add(buf.len());
71
72		Ok(buf.len())
73	}
74
75	fn flush(&mut self) -> io::Result<()> { Ok(()) }
76}
77
78/// Deserializes a string and parses it through `FromStr`.
79///
80/// Only string input is accepted. Parse failures become custom deserialization
81/// errors using their `Display` messages.
82pub fn deserialize_from_str<'de, D, T, E>(deserializer: D) -> Result<T, D::Error>
83where
84	D: Deserializer<'de>,
85	T: FromStr<Err = E>,
86	E: fmt::Display,
87{
88	struct Visitor<T: FromStr<Err = E>, E>(PhantomData<T>);
89
90	impl<T, Err> serde::de::Visitor<'_> for Visitor<T, Err>
91	where
92		T: FromStr<Err = Err>,
93		Err: fmt::Display,
94	{
95		type Value = T;
96
97		fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98			write!(formatter, "a parsable string")
99		}
100
101		fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
102		where
103			E: serde::de::Error,
104		{
105			v.parse().map_err(serde::de::Error::custom)
106		}
107	}
108
109	deserializer.deserialize_str(Visitor(PhantomData))
110}
111
112/// Deserializes an optional boolean that may arrive spelled as a string.
113///
114/// Null reads as `None`. A boolean reads as itself and a string as `true` only
115/// when it spells true in any letter case; every other value reads as `false`,
116/// so a malformed value neither passes for true nor fails the enclosing value.
117pub fn deserialize_lenient_bool<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
118where
119	D: Deserializer<'de>,
120{
121	Deserialize::deserialize(deserializer)
122		.map(|value: Option<LenientBool<'_>>| value.map(bool::from))
123}
124
125impl From<LenientBool<'_>> for bool {
126	fn from(value: LenientBool<'_>) -> Self {
127		match value {
128			| LenientBool::Bool(value) => value,
129			| LenientBool::Str(value) => value.eq_ignore_ascii_case("true"),
130			| LenientBool::Other(_) => false,
131		}
132	}
133}