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
14/// Decodes a request-scoped view without copying the complete JSON body.
15pub trait JsonRequestDecode {
16    type View<'req>: JsonEncode;
17
18    fn decode_request<'req>(input: &'req [u8]) -> Result<Self::View<'req>>;
19}
20
21pub trait JsonScan: Sized {
22    fn scan_json<'a, I>(chunks: I) -> Result<Self>
23    where
24        I: IntoIterator<Item = &'a [u8]>;
25}
26
27pub trait JsonEncode: Sized {
28    fn json_len(&self) -> usize;
29
30    fn write_into<W: Write>(&self, w: &mut W) -> std::result::Result<(), W::Error>;
31
32    fn write_json(&self, out: &mut Vec<u8>) {
33        let expected = self.json_len();
34        let mut w = Writer::new(out, expected);
35        match self.write_into(&mut w) {
36            Ok(()) => {}
37            Err(error) => match error {},
38        }
39    }
40
41    fn encode_json(&self) -> Vec<u8> {
42        let mut out = Vec::with_capacity(self.json_len());
43        self.write_json(&mut out);
44        out
45    }
46}
47
48pub trait JsonPreserve {
49    fn raw_json(&self) -> Option<&Shared>;
50}
51
52impl<T> JsonEncode for &T
53where
54    T: JsonEncode,
55{
56    fn json_len(&self) -> usize {
57        (*self).json_len()
58    }
59
60    fn write_into<W: Write>(&self, w: &mut W) -> std::result::Result<(), W::Error> {
61        (*self).write_into(w)
62    }
63
64    fn write_json(&self, out: &mut Vec<u8>) {
65        (*self).write_json(out)
66    }
67}
68
69impl<T> JsonPreserve for &T
70where
71    T: JsonPreserve + ?Sized,
72{
73    fn raw_json(&self) -> Option<&Shared> {
74        (*self).raw_json()
75    }
76}