Skip to main content

sark_json/
response.rs

1use o3::buffer::{CapacityError, ExactBuildError, Owned, Shared, SliceWriter};
2use sark_core::http::EncodedBody;
3
4use crate::JsonEncode;
5
6pub struct JsonBody<T>(T);
7
8impl<T> JsonBody<T> {
9    pub fn new(value: T) -> Self {
10        Self(value)
11    }
12}
13
14impl<T> EncodedBody for JsonBody<T>
15where
16    T: JsonEncode,
17{
18    type Error = ExactBuildError<CapacityError>;
19
20    fn encoded_len(&self) -> usize {
21        self.0.json_len()
22    }
23
24    fn encode_into(&self, out: &mut [u8]) -> Result<(), Self::Error> {
25        let expected = out.len();
26        let mut writer = SliceWriter::new(out);
27        self.0
28            .write_into(&mut writer)
29            .map_err(ExactBuildError::Build)?;
30        let actual = writer.finish();
31        if actual != expected {
32            return Err(ExactBuildError::LengthMismatch { expected, actual });
33        }
34        Ok(())
35    }
36
37    fn into_shared(self, encoded_len: usize) -> Result<Shared, Self::Error> {
38        Owned::try_build_exact(encoded_len, |out| self.0.write_into(out)).map(Owned::freeze)
39    }
40}