Skip to main content

sark_http/payload/response/bounded/
plan.rs

1use o3::{
2    buffer::{
3        storage,
4        write::{Sink, Slice, 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)).map(storage::Owned::<()>::freeze)
45    }
46
47    pub fn encode<L: std::borrow::BorrowMut<usize>>(
48        self,
49        out: &mut Slice<'_, L>,
50    ) -> Result<usize, storage::BuildError<consume::Error>> {
51        let Self { body, max_len } = self;
52        let mut split = response::try_encode(out, max_len, body)?;
53        let len = split.body().len();
54        split.try_commit().map_err(storage::BuildError::Build)?;
55        Ok(len)
56    }
57}
58
59impl<B: TryBody> Body for Plan<B> {
60    fn max_len(&self) -> usize {
61        self.max_len
62    }
63}
64
65impl<B: Encode> Encode for Plan<B> {
66    fn encode<W>(self, out: &mut W) -> Result<(), consume::Error>
67    where
68        W: Sink<Error = consume::Error>,
69    {
70        self.body.encode(out)
71    }
72}