Skip to main content

zaun_community_protocol/
json.rs

1//! JSON conventions shared by every module (specification §2, §3.6, §7).
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4
5/// `#[serde(with = "crate::json::u64_decimal")]`: a `u64` as a JSON decimal string, because
6/// JavaScript numbers lose bits above 2^53 (permission sets, ADR-0006).
7///
8/// Decoding accepts only canonical decimals: ASCII digits, no sign, no leading zeros (except
9/// `"0"`), no whitespace, at most `u64::MAX`.
10pub mod u64_decimal {
11    use super::{Deserialize, Deserializer, Serializer};
12    use serde::de::Error as _;
13
14    /// Serializes as a decimal string.
15    ///
16    /// # Errors
17    /// Only the serializer's own errors.
18    pub fn serialize<S: Serializer>(value: &u64, s: S) -> Result<S::Ok, S::Error> {
19        s.serialize_str(&value.to_string())
20    }
21
22    /// Deserializes a canonical decimal string.
23    ///
24    /// # Errors
25    /// A number, a non-canonical decimal or an overflow.
26    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
27        let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
28        parse(&text).ok_or_else(|| D::Error::custom("expected a canonical decimal string"))
29    }
30
31    /// Parses a canonical decimal.
32    #[must_use]
33    pub fn parse(text: &str) -> Option<u64> {
34        let canonical = !text.is_empty()
35            && text.bytes().all(|b| b.is_ascii_digit())
36            && (text == "0" || !text.starts_with('0'));
37        if canonical { text.parse().ok() } else { None }
38    }
39}
40
41/// A signed object as it travels in JSON (specification §3.6): the canonical bytes `B` and the
42/// composite signature, both base64url. Receivers verify `sig` over `bytes` with the context of
43/// the object type they expect before decoding `bytes`.
44#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct SignedJson {
46    /// Canonical encoding `B` of the object (specification §3.1, §4).
47    #[serde(with = "crate::b64::bytes")]
48    pub bytes: Vec<u8>,
49    /// Encoded `Signature` (specification §3.4).
50    #[serde(with = "crate::b64::bytes")]
51    pub sig: Vec<u8>,
52}
53
54impl std::fmt::Debug for SignedJson {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.debug_struct("SignedJson")
57            .field("bytes_len", &self.bytes.len())
58            .field("sig_len", &self.sig.len())
59            .finish()
60    }
61}
62
63/// A field that distinguishes "absent" from "null" in update commands
64/// (`channel.update` with `"topic": null` clears the topic; no `topic` leaves it).
65///
66/// Use with `#[serde(default, skip_serializing_if = "Patch::is_keep")]`.
67#[derive(Debug, Clone, PartialEq, Eq, Default)]
68pub enum Patch<T> {
69    /// The field was absent: keep the current value.
70    #[default]
71    Keep,
72    /// The field was `null`: clear it.
73    Clear,
74    /// The field was present: set it.
75    Set(T),
76}
77
78impl<T> Patch<T> {
79    /// Whether the field was absent.
80    #[must_use]
81    pub const fn is_keep(&self) -> bool {
82        matches!(self, Self::Keep)
83    }
84}
85
86impl<T: Serialize> Serialize for Patch<T> {
87    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
88        match self {
89            Self::Keep | Self::Clear => s.serialize_none(),
90            Self::Set(value) => value.serialize(s),
91        }
92    }
93}
94
95impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
96    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
97        Option::<T>::deserialize(d)
98            .map(|value| value.map_or(Self::Clear, Self::Set))
99            .map_err(|e| D::Error::custom(e.to_string()))
100    }
101}
102
103/// `skip_serializing_if` for a `u32` that is absent when 0 (message `flags`, §8.14).
104#[must_use]
105#[allow(clippy::trivially_copy_pass_by_ref)]
106pub const fn is_zero_u32(value: &u32) -> bool {
107    *value == 0
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[derive(Debug, PartialEq, Serialize, Deserialize)]
115    struct Bits {
116        #[serde(with = "u64_decimal")]
117        allow: u64,
118    }
119
120    #[derive(Debug, PartialEq, Serialize, Deserialize)]
121    struct Update {
122        #[serde(default, skip_serializing_if = "Patch::is_keep")]
123        topic: Patch<String>,
124    }
125
126    #[test]
127    fn u64_is_a_canonical_decimal_string() {
128        let json = serde_json::to_string(&Bits { allow: u64::MAX }).unwrap();
129        assert_eq!(json, r#"{"allow":"18446744073709551615"}"#);
130        assert_eq!(serde_json::from_str::<Bits>(&json).unwrap().allow, u64::MAX);
131        for bad in [
132            r#"{"allow":1}"#,
133            r#"{"allow":"01"}"#,
134            r#"{"allow":"+1"}"#,
135            r#"{"allow":" 1"}"#,
136            r#"{"allow":""}"#,
137            r#"{"allow":"18446744073709551616"}"#,
138        ] {
139            assert!(serde_json::from_str::<Bits>(bad).is_err(), "{bad}");
140        }
141        assert_eq!(
142            serde_json::from_str::<Bits>(r#"{"allow":"0"}"#)
143                .unwrap()
144                .allow,
145            0
146        );
147    }
148
149    #[test]
150    fn patch_distinguishes_absent_null_and_value() {
151        assert_eq!(
152            serde_json::from_str::<Update>("{}").unwrap().topic,
153            Patch::Keep
154        );
155        assert_eq!(
156            serde_json::from_str::<Update>(r#"{"topic":null}"#)
157                .unwrap()
158                .topic,
159            Patch::Clear
160        );
161        assert_eq!(
162            serde_json::from_str::<Update>(r#"{"topic":"x"}"#)
163                .unwrap()
164                .topic,
165            Patch::Set("x".into())
166        );
167        assert_eq!(
168            serde_json::to_string(&Update { topic: Patch::Keep }).unwrap(),
169            "{}"
170        );
171    }
172}