Skip to main content

sark_http/payload/response/bounded/
plan.rs

1use o3::{
2    buffer::{
3        storage,
4        write::{Sink, consume},
5    },
6    mem::Rejected,
7};
8
9use crate::payload::response::{
10    self, Encode,
11    bounded::{Body, TryBody},
12};
13
14pub struct Plan<B> {
15    body: B,
16    max_len: usize,
17}
18
19impl<B> Plan<B>
20where
21    B: Body,
22{
23    pub fn new(body: B) -> Self {
24        let max_len = body.max_len();
25        Self { body, max_len }
26    }
27}
28
29impl<B: TryBody> Plan<B> {
30    /// Admits the upper bound once while retaining the original encoder owner.
31    pub fn try_new(body: B) -> Result<Self, Rejected<B, B::Error>> {
32        match body.try_max_len() {
33            Ok(max_len) => Ok(Self { body, max_len }),
34            Err(error) => Err(Rejected::new(body, error)),
35        }
36    }
37
38    pub fn max_len(&self) -> usize {
39        self.max_len
40    }
41
42    pub fn into_shared(self) -> Result<storage::Shared, storage::BuildError<consume::Error>> {
43        let Self { body, max_len } = self;
44        storage::Owned::try_build(max_len, |out| body.encode(out))
45            .map(storage::Owned::<(), 0>::freeze)
46    }
47
48    pub fn encode(self, out: &mut [u8]) -> Result<&mut [u8], storage::BuildError<consume::Error>> {
49        let Self { body, max_len } = self;
50        Ok(response::try_encode(out, max_len, body)?.into_mut())
51    }
52}
53
54impl<B: TryBody> Body for Plan<B> {
55    fn max_len(&self) -> usize {
56        self.max_len
57    }
58}
59
60impl<B: Encode> Encode for Plan<B> {
61    fn encode<W>(self, out: &mut W) -> Result<(), consume::Error>
62    where
63        W: Sink<Error = consume::Error>,
64    {
65        self.body.encode(out)
66    }
67}