zaun_community_protocol/
json.rs1use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
4
5pub mod u64_decimal {
11 use super::{Deserialize, Deserializer, Serializer};
12 use serde::de::Error as _;
13
14 pub fn serialize<S: Serializer>(value: &u64, s: S) -> Result<S::Ok, S::Error> {
19 s.serialize_str(&value.to_string())
20 }
21
22 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 #[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#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct SignedJson {
46 #[serde(with = "crate::b64::bytes")]
48 pub bytes: Vec<u8>,
49 #[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
68pub enum Patch<T> {
69 #[default]
71 Keep,
72 Clear,
74 Set(T),
76}
77
78impl<T> Patch<T> {
79 #[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#[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}