Skip to main content

sark_http/payload/fixed/
body.rs

1use std::{borrow::BorrowMut, ops::ControlFlow};
2
3use o3::buffer::{bytes::scope, write::Slice};
4
5use crate::{
6    owner::{handoff, handoff::stage},
7    payload::{owned, response},
8};
9
10#[derive(Clone, Copy, Eq, PartialEq)]
11#[repr(transparent)]
12pub struct Body<'a> {
13    bytes: &'a [u8],
14}
15
16impl<'a> Body<'a> {
17    pub const fn new(bytes: &'a [u8]) -> Self {
18        Self { bytes }
19    }
20
21    pub const fn as_slice(&self) -> &'a [u8] {
22        self.bytes
23    }
24
25    pub const fn len(self) -> usize {
26        self.bytes.len()
27    }
28
29    pub const fn is_empty(self) -> bool {
30        self.bytes.is_empty()
31    }
32}
33
34impl<'body_d, 'd> response::Body<'d> for Body<'body_d>
35where
36    'body_d: 'd,
37{
38    type Bound = o3::buffer::resident::bound::AtMost<0>;
39    type Selected<S, B> = handoff::Selection<'d, S, B>;
40
41    const INLINE: bool = true;
42
43    fn len(&self) -> usize {
44        self.bytes.len()
45    }
46
47    fn as_slice(&self) -> Option<&[u8]> {
48        Some(self.bytes)
49    }
50
51    fn try_resolve<'req, H: scope::Source, O: stage::Body<'req, 'd>>(
52        self,
53        slot: &handoff::Slot<'req, 'd, H, O>,
54    ) -> Result<Self::Selected<H::Selection, O>, owned::Error> {
55        Ok(slot.fixed(self))
56    }
57
58    fn try_resolve_into<'req, H: scope::Source, O: stage::Body<'req, 'd>, L: BorrowMut<usize>>(
59        self,
60        slot: &handoff::Slot<'req, 'd, H, O>,
61        out: &mut Slice<'_, L>,
62    ) -> Result<ControlFlow<usize, handoff::Selection<'d, H::Selection, O>>, owned::Error> {
63        if !self.is_empty()
64            && let Some(written) = handoff::copy::into(out, self.bytes)
65        {
66            return Ok(ControlFlow::Break(written));
67        }
68        Ok(ControlFlow::Continue(slot.fixed(self)))
69    }
70}
71
72impl AsRef<[u8]> for Body<'_> {
73    fn as_ref(&self) -> &[u8] {
74        self.bytes
75    }
76}