Skip to main content

sark_json/
traits.rs

1use o3::buffer::Shared;
2
3use crate::Result;
4use crate::encode::{Write, Writer};
5
6pub trait JsonDecode: Sized {
7    fn decode_json(input: Shared) -> Result<Self>;
8
9    fn decode_json_borrowed(input: &[u8]) -> Result<Self> {
10        Self::decode_json(Shared::copy_from_slice(input))
11    }
12}
13
14pub trait JsonScan: Sized {
15    fn scan_json<'a, I>(chunks: I) -> Result<Self>
16    where
17        I: IntoIterator<Item = &'a [u8]>;
18}
19
20pub trait JsonEncode: Sized {
21    fn json_len(&self) -> usize;
22
23    fn write_into<W: Write>(&self, w: &mut W);
24
25    fn write_json(&self, out: &mut Vec<u8>) {
26        let expected = self.json_len();
27        let mut w = Writer::new(out, expected);
28        self.write_into(&mut w);
29        assert_eq!(w.finish(), expected, "JsonEncode length mismatch");
30    }
31
32    fn encode_json(&self) -> Vec<u8> {
33        let mut out = Vec::with_capacity(self.json_len());
34        self.write_json(&mut out);
35        out
36    }
37}
38
39pub trait JsonPreserve {
40    fn raw_json(&self) -> Option<&Shared>;
41}
42
43impl<T> JsonEncode for &T
44where
45    T: JsonEncode,
46{
47    fn json_len(&self) -> usize {
48        (*self).json_len()
49    }
50
51    fn write_into<W: Write>(&self, w: &mut W) {
52        (*self).write_into(w)
53    }
54
55    fn write_json(&self, out: &mut Vec<u8>) {
56        (*self).write_json(out)
57    }
58}
59
60impl<T> JsonPreserve for &T
61where
62    T: JsonPreserve + ?Sized,
63{
64    fn raw_json(&self) -> Option<&Shared> {
65        (*self).raw_json()
66    }
67}