Skip to main content

sark_json/
traits.rs

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