simd_json_derive/
impls.rs

1mod array;
2#[cfg(feature = "impl-chrono")]
3mod chrono;
4mod collections;
5mod deref;
6mod primitives;
7mod simdjson;
8mod string;
9mod tpl;
10use crate::{de, io, Deserialize, DummyGenerator, Serialize, Tape, Write};
11use value_trait::generator::BaseGenerator;
12
13impl<T> Serialize for Option<T>
14where
15    T: Serialize,
16{
17    #[inline]
18    fn json_write<W>(&self, writer: &mut W) -> io::Result<()>
19    where
20        W: Write,
21    {
22        if let Some(e) = self {
23            e.json_write(writer)
24        } else {
25            writer.write_all(b"null")
26        }
27    }
28}
29
30impl<'input, T> Deserialize<'input> for Option<T>
31where
32    T: Deserialize<'input>,
33{
34    #[inline]
35    fn from_tape(tape: &mut Tape<'input>) -> de::Result<Self>
36    where
37        Self: Sized + 'input,
38    {
39        if let Some(simd_json::Node::Static(simd_json::StaticNode::Null)) = tape.peek() {
40            tape.next();
41            Ok(None)
42        } else {
43            Ok(Some(T::from_tape(tape)?))
44        }
45    }
46}
47
48impl<TOk, TErr> Serialize for std::result::Result<TOk, TErr>
49where
50    TOk: Serialize,
51    TErr: Serialize,
52{
53    #[inline]
54    fn json_write<W>(&self, writer: &mut W) -> io::Result<()>
55    where
56        W: Write,
57    {
58        match self {
59            Ok(e) => {
60                writer.write_all(b"{\"Ok\":")?;
61                e.json_write(writer)?;
62                writer.write_all(b"}")
63            }
64            Err(e) => {
65                writer.write_all(b"{\"Err\":")?;
66                e.json_write(writer)?;
67                writer.write_all(b"}")
68            }
69        }
70    }
71}
72
73impl<'input, TOk, TErr> Deserialize<'input> for std::result::Result<TOk, TErr>
74where
75    TOk: Deserialize<'input>,
76    TErr: Deserialize<'input>,
77{
78    #[inline]
79    fn from_tape(tape: &mut Tape<'input>) -> de::Result<Self>
80    where
81        Self: Sized + 'input,
82    {
83        if let Some(simd_json::Node::Object { len: 1, .. }) = tape.next() {
84            match tape.next() {
85                Some(simd_json::Node::String("Ok")) => Ok(Ok(TOk::from_tape(tape)?)),
86                Some(simd_json::Node::String("Err")) => Ok(Err(TErr::from_tape(tape)?)),
87                Some(simd_json::Node::String("ok")) => Ok(Ok(TOk::from_tape(tape)?)),
88                Some(simd_json::Node::String("err")) => Ok(Err(TErr::from_tape(tape)?)),
89                _ => Err(de::Error::custom("result not `Ok` or `Err`")),
90            }
91        } else {
92            Err(de::Error::InvalidStructRepresentation)
93        }
94    }
95}