1use std::fmt;
10
11use serde::de::{
12 self, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess,
13 Unexpected, VariantAccess, Visitor,
14};
15
16pub fn from_slice<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, serde_json::Error> {
18 let mut json = serde_json::Deserializer::from_slice(bytes);
19 let value = T::deserialize(Objects(&mut json))?;
20 json.end()?;
21 Ok(value)
22}
23
24pub fn from_value<T: DeserializeOwned>(value: serde_json::Value) -> Result<T, serde_json::Error> {
26 T::deserialize(Objects(value))
27}
28
29pub struct Objects<D>(pub D);
31
32macro_rules! forward {
35 ($($method:ident),* $(,)?) => {
36 $(
37 fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, D::Error> {
38 self.0.$method(Wrap::value(visitor))
39 }
40 )*
41 };
42}
43
44impl<'de, D: Deserializer<'de>> Deserializer<'de> for Objects<D> {
45 type Error = D::Error;
46
47 forward! {
48 deserialize_any, deserialize_bool, deserialize_i8, deserialize_i16, deserialize_i32,
49 deserialize_i64, deserialize_i128, deserialize_u8, deserialize_u16, deserialize_u32,
50 deserialize_u64, deserialize_u128, deserialize_f32, deserialize_f64, deserialize_char,
51 deserialize_str, deserialize_string, deserialize_bytes, deserialize_byte_buf,
52 deserialize_option, deserialize_unit, deserialize_seq, deserialize_map,
53 deserialize_identifier, deserialize_ignored_any,
54 }
55
56 fn deserialize_unit_struct<V: Visitor<'de>>(
57 self,
58 name: &'static str,
59 visitor: V,
60 ) -> Result<V::Value, D::Error> {
61 self.0.deserialize_unit_struct(name, Wrap::value(visitor))
62 }
63
64 fn deserialize_newtype_struct<V: Visitor<'de>>(
65 self,
66 name: &'static str,
67 visitor: V,
68 ) -> Result<V::Value, D::Error> {
69 self.0
70 .deserialize_newtype_struct(name, Wrap::value(visitor))
71 }
72
73 fn deserialize_tuple<V: Visitor<'de>>(
74 self,
75 len: usize,
76 visitor: V,
77 ) -> Result<V::Value, D::Error> {
78 self.0.deserialize_tuple(len, Wrap::value(visitor))
79 }
80
81 fn deserialize_tuple_struct<V: Visitor<'de>>(
82 self,
83 name: &'static str,
84 len: usize,
85 visitor: V,
86 ) -> Result<V::Value, D::Error> {
87 self.0
88 .deserialize_tuple_struct(name, len, Wrap::value(visitor))
89 }
90
91 fn deserialize_struct<V: Visitor<'de>>(
92 self,
93 name: &'static str,
94 fields: &'static [&'static str],
95 visitor: V,
96 ) -> Result<V::Value, D::Error> {
97 self.0
98 .deserialize_struct(name, fields, Wrap::structure(visitor))
99 }
100
101 fn deserialize_enum<V: Visitor<'de>>(
102 self,
103 name: &'static str,
104 variants: &'static [&'static str],
105 visitor: V,
106 ) -> Result<V::Value, D::Error> {
107 self.0
108 .deserialize_enum(name, variants, Wrap::value(visitor))
109 }
110
111 fn is_human_readable(&self) -> bool {
112 self.0.is_human_readable()
113 }
114}
115
116struct Wrap<V> {
119 visitor: V,
120 structure: bool,
121}
122
123impl<V> Wrap<V> {
124 fn value(visitor: V) -> Self {
125 Self {
126 visitor,
127 structure: false,
128 }
129 }
130
131 fn structure(visitor: V) -> Self {
132 Self {
133 visitor,
134 structure: true,
135 }
136 }
137}
138
139macro_rules! visit {
140 ($($method:ident($ty:ty)),* $(,)?) => {
141 $(
142 fn $method<E: de::Error>(self, value: $ty) -> Result<V::Value, E> {
143 self.visitor.$method(value)
144 }
145 )*
146 };
147}
148
149impl<'de, V: Visitor<'de>> Visitor<'de> for Wrap<V> {
150 type Value = V::Value;
151
152 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 self.visitor.expecting(f)
154 }
155
156 visit! {
157 visit_bool(bool), visit_i8(i8), visit_i16(i16), visit_i32(i32), visit_i64(i64),
158 visit_i128(i128), visit_u8(u8), visit_u16(u16), visit_u32(u32), visit_u64(u64),
159 visit_u128(u128), visit_f32(f32), visit_f64(f64), visit_char(char), visit_str(&str),
160 visit_borrowed_str(&'de str), visit_string(String), visit_bytes(&[u8]),
161 visit_borrowed_bytes(&'de [u8]), visit_byte_buf(Vec<u8>),
162 }
163
164 fn visit_none<E: de::Error>(self) -> Result<V::Value, E> {
165 self.visitor.visit_none()
166 }
167
168 fn visit_unit<E: de::Error>(self) -> Result<V::Value, E> {
169 self.visitor.visit_unit()
170 }
171
172 fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<V::Value, D::Error> {
173 self.visitor.visit_some(Objects(deserializer))
174 }
175
176 fn visit_newtype_struct<D: Deserializer<'de>>(
177 self,
178 deserializer: D,
179 ) -> Result<V::Value, D::Error> {
180 self.visitor.visit_newtype_struct(Objects(deserializer))
181 }
182
183 fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<V::Value, A::Error> {
184 if self.structure {
185 return Err(de::Error::invalid_type(Unexpected::Seq, &self));
186 }
187 self.visitor.visit_seq(Seq(seq))
188 }
189
190 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<V::Value, A::Error> {
191 self.visitor.visit_map(Map(map))
192 }
193
194 fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<V::Value, A::Error> {
195 self.visitor.visit_enum(Enum(data))
196 }
197}
198
199struct Seed<S>(S);
201
202impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for Seed<S> {
203 type Value = S::Value;
204
205 fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<S::Value, D::Error> {
206 self.0.deserialize(Objects(deserializer))
207 }
208}
209
210struct Seq<A>(A);
211
212impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for Seq<A> {
213 type Error = A::Error;
214
215 fn next_element_seed<T: DeserializeSeed<'de>>(
216 &mut self,
217 seed: T,
218 ) -> Result<Option<T::Value>, A::Error> {
219 self.0.next_element_seed(Seed(seed))
220 }
221
222 fn size_hint(&self) -> Option<usize> {
223 self.0.size_hint()
224 }
225}
226
227struct Map<A>(A);
228
229impl<'de, A: MapAccess<'de>> MapAccess<'de> for Map<A> {
230 type Error = A::Error;
231
232 fn next_key_seed<K: DeserializeSeed<'de>>(
233 &mut self,
234 seed: K,
235 ) -> Result<Option<K::Value>, A::Error> {
236 self.0.next_key_seed(Seed(seed))
237 }
238
239 fn next_value_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<T::Value, A::Error> {
240 self.0.next_value_seed(Seed(seed))
241 }
242
243 fn size_hint(&self) -> Option<usize> {
244 self.0.size_hint()
245 }
246}
247
248struct Enum<A>(A);
249
250impl<'de, A: EnumAccess<'de>> EnumAccess<'de> for Enum<A> {
251 type Error = A::Error;
252 type Variant = Variant<A::Variant>;
253
254 fn variant_seed<T: DeserializeSeed<'de>>(
255 self,
256 seed: T,
257 ) -> Result<(T::Value, Self::Variant), A::Error> {
258 self.0
259 .variant_seed(Seed(seed))
260 .map(|(value, variant)| (value, Variant(variant)))
261 }
262}
263
264struct Variant<A>(A);
265
266impl<'de, A: VariantAccess<'de>> VariantAccess<'de> for Variant<A> {
267 type Error = A::Error;
268
269 fn unit_variant(self) -> Result<(), A::Error> {
270 self.0.unit_variant()
271 }
272
273 fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, A::Error> {
274 self.0.newtype_variant_seed(Seed(seed))
275 }
276
277 fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, A::Error> {
278 self.0.tuple_variant(len, Wrap::value(visitor))
279 }
280
281 fn struct_variant<V: Visitor<'de>>(
282 self,
283 fields: &'static [&'static str],
284 visitor: V,
285 ) -> Result<V::Value, A::Error> {
286 self.0.struct_variant(fields, Wrap::structure(visitor))
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use std::collections::BTreeMap;
293
294 use serde::Deserialize;
295 use serde_json::json;
296
297 use super::*;
298
299 #[derive(Debug, PartialEq, Deserialize)]
300 struct Point {
301 x: f64,
302 #[serde(default)]
303 label: Option<String>,
304 }
305
306 #[derive(Debug, PartialEq, Deserialize)]
307 enum Shape {
308 #[serde(rename = "point")]
309 Point(Point),
310 #[serde(rename = "path")]
311 Path(Vec<Point>),
312 }
313
314 #[derive(Debug, PartialEq, Deserialize)]
315 struct Body {
316 #[serde(default)]
317 point: Option<Point>,
318 #[serde(default)]
319 points: Vec<Point>,
320 #[serde(default)]
321 named: BTreeMap<String, Point>,
322 #[serde(default)]
323 shape: Option<Shape>,
324 #[serde(default)]
325 field: crate::field::Field<Point>,
326 #[serde(default)]
327 boxed: Option<Box<Point>>,
328 #[serde(default)]
329 document: Option<serde_json::Value>,
330 #[serde(default)]
331 tags: Vec<String>,
332 }
333
334 fn both(json: &str) -> [Result<Body, serde_json::Error>; 2] {
335 [
336 from_slice(json.as_bytes()),
337 from_value(serde_json::from_str(json).unwrap()),
338 ]
339 }
340
341 #[test]
342 fn plain_serde_json_reads_a_structure_from_an_array() {
343 assert!(serde_json::from_str::<Body>(r#"{"point":[1]}"#).is_ok());
345 assert!(serde_json::from_str::<Body>("[]").is_ok());
346 }
347
348 #[test]
349 fn a_structure_is_only_an_object_at_every_depth() {
350 for json in [
351 "[]",
352 r#"[null, []]"#,
353 r#"{"point":[]}"#,
354 r#"{"point":[1]}"#,
355 r#"{"point":[1, "a"]}"#,
356 r#"{"points":[{"x":1},[2]]}"#,
357 r#"{"named":{"a":[1]}}"#,
358 r#"{"shape":{"point":[1]}}"#,
359 r#"{"shape":{"path":[[1]]}}"#,
360 r#"{"field":[1]}"#,
361 r#"{"boxed":[1]}"#,
362 ] {
363 for result in both(json) {
364 let error = result.expect_err(json).to_string();
365 assert!(error.contains("invalid type: sequence"), "{json}: {error}");
366 }
367 }
368 }
369
370 #[test]
371 fn everything_else_reads_as_before() {
372 let json = r#"{"point":{"x":1},"points":[{"x":2,"label":"b"}],"named":{"a":{"x":3}},
373 "shape":{"path":[{"x":4}]},"field":null,"boxed":{"x":5},
374 "document":[1,{"x":[2]}],"tags":["t"]}"#;
375 for body in both(json) {
376 let body = body.unwrap();
377 assert_eq!(
378 body.point,
379 Some(Point {
380 x: 1.0,
381 label: None
382 })
383 );
384 assert_eq!(body.points[0].label.as_deref(), Some("b"));
385 assert_eq!(body.named["a"].x, 3.0);
386 assert_eq!(
387 body.shape,
388 Some(Shape::Path(vec![Point {
389 x: 4.0,
390 label: None
391 }]))
392 );
393 assert!(body.field.is_null());
394 assert_eq!(body.boxed.map(|point| point.x), Some(5.0));
395 assert_eq!(body.document, Some(json!([1, {"x": [2]}])));
397 assert_eq!(body.tags, ["t"]);
398 }
399 for body in both(r#"{"point":null,"shape":null}"#) {
400 let body = body.unwrap();
401 assert_eq!((body.point, body.shape), (None, None));
402 }
403 assert!(from_slice::<Body>(b"{} {}").is_err());
405 }
406}