sark_http/payload/fixed/
body.rs1use std::{borrow::BorrowMut, ops::ControlFlow};
2
3use o3::buffer::{
4 resident::bound::AtMost,
5 storage::NonEmpty,
6 write::{self, Sink as _},
7};
8
9use crate::payload::{owned, response};
10
11#[derive(Clone, Copy, Eq, PartialEq)]
12#[repr(transparent)]
13pub struct Body<'a> {
14 bytes: &'a [u8],
15}
16
17impl<'a> Body<'a> {
18 pub const fn new(bytes: &'a [u8]) -> Self {
19 Self { bytes }
20 }
21
22 pub const fn as_slice(&self) -> &'a [u8] {
23 self.bytes
24 }
25
26 pub const fn len(self) -> usize {
27 self.bytes.len()
28 }
29
30 pub const fn is_empty(self) -> bool {
31 self.bytes.is_empty()
32 }
33}
34
35impl<'body_d: 'd, 'd, Ranges: Copy + 'd> response::Body<'d, Ranges> for Body<'body_d> {
36 type Bound = AtMost<0>;
37 type Storage = NonEmpty<&'body_d [u8]>;
38 type Prepared = Option<Self::Storage>;
39
40 const INLINE: bool = true;
41
42 fn len(&self) -> usize {
43 self.bytes.len()
44 }
45 fn as_slice(&self) -> Option<&[u8]> {
46 Some(self.bytes)
47 }
48
49 fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
50 Ok(NonEmpty::try_new(self.bytes).ok())
51 }
52
53 fn try_inline<L: BorrowMut<usize>>(
54 self,
55 out: &mut write::raw::Slice<'_, L>,
56 ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
57 let body = <Self as response::Body<'d, Ranges>>::try_prepare(self)?;
58 if let Some(bytes) = &body
59 && out.write_slice(bytes.as_ref()).is_ok()
60 {
61 return Ok(ControlFlow::Break(bytes.len().get()));
62 }
63 Ok(ControlFlow::Continue(body))
64 }
65}
66
67impl AsRef<[u8]> for Body<'_> {
68 fn as_ref(&self) -> &[u8] {
69 self.bytes
70 }
71}