Skip to main content

sark_http/payload/response/exact/
plan.rs

1use o3::{
2    buffer::{storage, write::consume},
3    mem::Rejected,
4};
5
6use crate::payload::response::{
7    self,
8    exact::{Body, Overflow, TryBody},
9};
10
11pub struct Plan<B> {
12    body: B,
13    len: usize,
14}
15
16impl<B> Plan<B>
17where
18    B: Body,
19{
20    pub fn new(body: B) -> Self {
21        let len = body.encoded_len();
22        Self { body, len }
23    }
24}
25
26impl<B: TryBody> Plan<B> {
27    /// Admits the complete length once while retaining the exact body owner.
28    pub fn try_new(body: B) -> Result<Self, Rejected<B, Overflow>> {
29        match body.try_len() {
30            Ok(len) => Ok(Self { body, len }),
31            Err(error) => Err(Rejected::new(body, error)),
32        }
33    }
34
35    pub fn len(&self) -> usize {
36        self.len
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.len == 0
41    }
42
43    pub fn into_shared(self) -> Result<storage::Shared, storage::BuildError<consume::Error>> {
44        let Self { body, len } = self;
45        storage::Exact::try_build(len, |out| body.encode(out)).map(storage::Exact::into_shared)
46    }
47
48    pub fn encode(self, out: &mut [u8]) -> Result<(), storage::BuildError<consume::Error>> {
49        let Self {
50            body,
51            len: expected,
52        } = self;
53        response::try_encode(out, expected, body)?
54            .try_complete()
55            .map_err(storage::BuildError::Length)
56    }
57}