simd_json_derive/
lib.rs

1//! Derive for simd-json deserialisation
2#![deny(
3    warnings,
4    clippy::unwrap_used,
5    clippy::unnecessary_unwrap,
6    clippy::pedantic,
7    missing_docs
8)]
9use simd_json::Node;
10pub use simd_json_derive_int::*;
11use std::io::{self, Write};
12use std::iter::Peekable;
13use std::vec::IntoIter;
14use value_trait::generator::BaseGenerator;
15mod impls;
16/// Generic derive result
17pub type Result = io::Result<()>;
18
19/// Tape to deserialize
20pub type Tape<'input> = Peekable<IntoIter<Node<'input>>>;
21
22/// Deserializer trait
23pub mod de;
24
25pub use de::Deserialize;
26
27/// Skip method, skips n elements works with nested structures
28pub fn __skip(n: usize, tape: &mut Tape) {
29    for _ in 0..n {
30        match tape.next() {
31            Some(Node::Object { count, .. } | Node::Array { count, .. }) => {
32                for _ in 0..count {
33                    if tape.next().is_none() {
34                        return;
35                    }
36                }
37            }
38            Some(_) => {}
39            None => return,
40        }
41    }
42}
43/// Serialisation logic for simd-json derive
44pub trait Serialize {
45    /// Writes the json to a writer
46    ///
47    /// # Errors
48    /// If the serialisation failed
49    fn json_write<W>(&self, writer: &mut W) -> Result
50    where
51        W: Write;
52
53    #[inline]
54    /// Writes the json to a `Vec`
55    ///
56    /// # Errors
57    /// If the serialisation failed
58    fn json_vec(&self) -> io::Result<Vec<u8>> {
59        let mut v = Vec::with_capacity(512);
60        self.json_write(&mut v)?;
61        Ok(v)
62    }
63
64    #[inline]
65    /// Writes the json to a `String`
66    ///
67    /// # Errors
68    /// If the serialisation failed
69    fn json_string(&self) -> io::Result<String> {
70        self.json_vec()
71            .map(|v| unsafe { String::from_utf8_unchecked(v) })
72    }
73}
74
75/// Helper traint to serialize keys of json struct
76pub trait SerializeAsKey {
77    /// Writes the json to a writer
78    ///
79    /// # Errors
80    /// If the serialisation failed
81    fn json_write<W>(&self, writer: &mut W) -> Result
82    where
83        W: Write;
84}
85impl<T: AsRef<str>> SerializeAsKey for T {
86    #[inline]
87    fn json_write<W>(&self, writer: &mut W) -> Result
88    where
89        W: Write,
90    {
91        let s: &str = self.as_ref();
92        s.json_write(writer)
93    }
94}
95
96struct DummyGenerator<W: Write>(W);
97impl<W: Write> BaseGenerator for DummyGenerator<W> {
98    type T = W;
99    #[inline]
100    fn get_writer(&mut self) -> &mut <Self as BaseGenerator>::T {
101        &mut self.0
102    }
103    #[inline]
104    fn write_min(&mut self, _: &[u8], _: u8) -> io::Result<()> {
105        unimplemented!("write min is not supported")
106    }
107}