1use std::fmt;
12
13use serde::de::{self, MapAccess, SeqAccess, Visitor};
14use serde::Deserialize;
15
16#[derive(Debug, Clone, PartialEq)]
18pub enum Entry {
19 Null,
22 Bool(bool),
24 Number(f64),
27 Str(String),
29 Seq(Vec<Entry>),
31 Map(Vec<(String, Entry)>),
34}
35
36impl Entry {
37 pub fn canonical_text(&self) -> String {
41 let mut out = String::new();
42 self.write_canonical(&mut out);
43 out
44 }
45
46 fn write_canonical(&self, out: &mut String) {
47 match self {
48 Self::Null => {}
49 Self::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
50 Self::Number(value) => {
51 out.push_str(&value.to_string());
54 }
55 Self::Str(text) => out.push_str(text),
56 Self::Seq(items) => {
57 out.push('[');
58 for (index, item) in items.iter().enumerate() {
59 if index > 0 {
60 out.push(',');
61 }
62 item.write_json(out);
63 }
64 out.push(']');
65 }
66 Self::Map(pairs) => {
67 out.push('{');
68 for (index, (key, value)) in pairs.iter().enumerate() {
69 if index > 0 {
70 out.push(',');
71 }
72 write_json_string(key, out);
73 out.push(':');
74 value.write_json(out);
75 }
76 out.push('}');
77 }
78 }
79 }
80
81 fn write_json(&self, out: &mut String) {
85 match self {
86 Self::Null => out.push_str("null"),
87 Self::Str(text) => write_json_string(text, out),
88 other => other.write_canonical(out),
89 }
90 }
91}
92
93impl fmt::Display for Entry {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str(&self.canonical_text())
96 }
97}
98
99fn write_json_string(text: &str, out: &mut String) {
100 out.push('"');
101 for ch in text.chars() {
102 match ch {
103 '"' => out.push_str("\\\""),
104 '\\' => out.push_str("\\\\"),
105 '\n' => out.push_str("\\n"),
106 '\r' => out.push_str("\\r"),
107 '\t' => out.push_str("\\t"),
108 c if (c as u32) < 0x20 => {
109 out.push_str(&format!("\\u{:04x}", c as u32));
110 }
111 c => out.push(c),
112 }
113 }
114 out.push('"');
115}
116
117#[derive(Debug, Clone, PartialEq)]
122enum MapKey {
123 Name(String),
124 Bool(bool),
125 Int(i64),
126 UInt(u64),
127 Float(f64),
128}
129
130impl MapKey {
131 fn into_name(self) -> Result<String, String> {
132 match self {
133 Self::Name(name) => Ok(name),
134 Self::Bool(value) => Ok(value.to_string()),
135 Self::Int(value) => Ok(value.to_string()),
136 Self::UInt(value) => Ok(value.to_string()),
137 Self::Float(value) if value.is_finite() => Ok(value.to_string()),
138 Self::Float(value) => Err(format!("non-finite number used as a mapping key: {value}")),
139 }
140 }
141}
142
143impl<'de> Deserialize<'de> for MapKey {
144 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
145 where
146 D: serde::Deserializer<'de>,
147 {
148 struct KeyVisitor;
149 impl Visitor<'_> for KeyVisitor {
150 type Value = MapKey;
151
152 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 f.write_str("a mapping key (string, boolean, or number)")
154 }
155
156 fn visit_str<E>(self, value: &str) -> Result<MapKey, E> {
157 Ok(MapKey::Name(value.to_owned()))
158 }
159
160 fn visit_string<E>(self, value: String) -> Result<MapKey, E> {
161 Ok(MapKey::Name(value))
162 }
163
164 fn visit_bool<E>(self, value: bool) -> Result<MapKey, E> {
165 Ok(MapKey::Bool(value))
166 }
167
168 fn visit_i64<E>(self, value: i64) -> Result<MapKey, E> {
169 Ok(MapKey::Int(value))
170 }
171
172 fn visit_u64<E>(self, value: u64) -> Result<MapKey, E> {
173 Ok(MapKey::UInt(value))
174 }
175
176 fn visit_f64<E>(self, value: f64) -> Result<MapKey, E> {
177 Ok(MapKey::Float(value))
178 }
179 }
180 deserializer.deserialize_any(KeyVisitor)
181 }
182}
183
184impl<'de> Deserialize<'de> for Entry {
185 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
186 where
187 D: serde::Deserializer<'de>,
188 {
189 struct EntryVisitor;
190 impl<'de> Visitor<'de> for EntryVisitor {
191 type Value = Entry;
192
193 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.write_str("any YAML/JSON value (string, object, array, number, boolean, or null)")
195 }
196
197 fn visit_unit<E>(self) -> Result<Entry, E> {
198 Ok(Entry::Null)
199 }
200
201 fn visit_none<E>(self) -> Result<Entry, E> {
202 Ok(Entry::Null)
203 }
204
205 fn visit_some<D>(self, deserializer: D) -> Result<Entry, D::Error>
206 where
207 D: serde::Deserializer<'de>,
208 {
209 Entry::deserialize(deserializer)
210 }
211
212 fn visit_bool<E>(self, value: bool) -> Result<Entry, E> {
213 Ok(Entry::Bool(value))
214 }
215
216 fn visit_i64<E>(self, value: i64) -> Result<Entry, E> {
217 Ok(Entry::Number(value as f64))
218 }
219
220 fn visit_u64<E>(self, value: u64) -> Result<Entry, E> {
221 Ok(Entry::Number(value as f64))
222 }
223
224 fn visit_f64<E>(self, value: f64) -> Result<Entry, E>
225 where
226 E: de::Error,
227 {
228 if value.is_finite() {
229 Ok(Entry::Number(value))
230 } else {
231 Err(de::Error::custom(format!(
232 "non-finite numbers are not representable: {value}"
233 )))
234 }
235 }
236
237 fn visit_str<E>(self, value: &str) -> Result<Entry, E> {
238 Ok(Entry::Str(value.to_owned()))
239 }
240
241 fn visit_string<E>(self, value: String) -> Result<Entry, E> {
242 Ok(Entry::Str(value))
243 }
244
245 fn visit_seq<A>(self, mut seq: A) -> Result<Entry, A::Error>
246 where
247 A: SeqAccess<'de>,
248 {
249 let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0));
250 while let Some(item) = seq.next_element()? {
251 items.push(item);
252 }
253 Ok(Entry::Seq(items))
254 }
255
256 fn visit_map<A>(self, mut map: A) -> Result<Entry, A::Error>
257 where
258 A: MapAccess<'de>,
259 {
260 let mut pairs = Vec::with_capacity(map.size_hint().unwrap_or(0));
261 while let Some((key, value)) = map.next_entry::<MapKey, Entry>()? {
262 let name = key.into_name().map_err(de::Error::custom)?;
263 pairs.push((name, value));
266 }
267 Ok(Entry::Map(pairs))
268 }
269 }
270 deserializer.deserialize_any(EntryVisitor)
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn canonical_text_of_structured_entry_is_compact_json() {
280 let entry = Entry::Map(vec![
281 (
282 "b".to_owned(),
283 Entry::Seq(vec![Entry::Number(1.0), Entry::Str("x".into())]),
284 ),
285 ("a".to_owned(), Entry::Bool(true)),
286 ]);
287 assert_eq!(entry.canonical_text(), r#"{"b":[1,"x"],"a":true}"#);
288 }
289
290 #[test]
291 fn strings_render_verbatim_at_top_level() {
292 assert_eq!(
293 Entry::Str("plain text".into()).canonical_text(),
294 "plain text"
295 );
296 assert_eq!(Entry::Null.canonical_text(), "");
297 }
298
299 #[test]
300 fn nested_nulls_render_as_json_null_not_empty() {
301 let entry = Entry::Map(vec![(
305 "a".to_owned(),
306 Entry::Seq(vec![Entry::Null, Entry::Bool(true)]),
307 )]);
308 assert_eq!(entry.canonical_text(), r#"{"a":[null,true]}"#);
309 let reparsed: Entry = serde_json::from_str(&entry.canonical_text())
310 .unwrap_or_else(|error| panic!("valid JSON: {error}"));
311 assert_eq!(reparsed, entry);
312 }
313}