use std::{borrow::BorrowMut, ops::ControlFlow};
use o3::buffer::{
resident::bound::AtMost,
storage::NonEmpty,
write::{self, Sink as _},
};
use crate::payload::{owned, response};
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(transparent)]
pub struct Body<'a> {
bytes: &'a [u8],
}
impl<'a> Body<'a> {
pub const fn new(bytes: &'a [u8]) -> Self {
Self { bytes }
}
pub const fn as_slice(&self) -> &'a [u8] {
self.bytes
}
pub const fn len(self) -> usize {
self.bytes.len()
}
pub const fn is_empty(self) -> bool {
self.bytes.is_empty()
}
}
impl<'body_d: 'd, 'd, Ranges: Copy + 'd> response::Body<'d, Ranges> for Body<'body_d> {
type Bound = AtMost<0>;
type Storage = NonEmpty<&'body_d [u8]>;
type Prepared = Option<Self::Storage>;
const INLINE: bool = true;
fn len(&self) -> usize {
self.bytes.len()
}
fn as_slice(&self) -> Option<&[u8]> {
Some(self.bytes)
}
fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
Ok(NonEmpty::try_new(self.bytes).ok())
}
fn try_inline<L: BorrowMut<usize>>(
self,
out: &mut write::raw::Slice<'_, L>,
) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
let body = <Self as response::Body<'d, Ranges>>::try_prepare(self)?;
if let Some(bytes) = &body
&& out.write_slice(bytes.as_ref()).is_ok()
{
return Ok(ControlFlow::Break(bytes.len().get()));
}
Ok(ControlFlow::Continue(body))
}
}
impl AsRef<[u8]> for Body<'_> {
fn as_ref(&self) -> &[u8] {
self.bytes
}
}