use std::{borrow::BorrowMut, ops::ControlFlow};
use o3::buffer::{bytes::scope, write::Slice};
use crate::{
owner::{handoff, handoff::stage},
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> response::Body<'d> for Body<'body_d>
where
'body_d: 'd,
{
type Bound = o3::buffer::resident::bound::AtMost<0>;
type Selected<S, B> = handoff::Selection<'d, S, B>;
const INLINE: bool = true;
fn len(&self) -> usize {
self.bytes.len()
}
fn as_slice(&self) -> Option<&[u8]> {
Some(self.bytes)
}
fn try_resolve<'req, H: scope::Source, O: stage::Body<'req, 'd>>(
self,
slot: &handoff::Slot<'req, 'd, H, O>,
) -> Result<Self::Selected<H::Selection, O>, owned::Error> {
Ok(slot.fixed(self))
}
fn try_resolve_into<'req, H: scope::Source, O: stage::Body<'req, 'd>, L: BorrowMut<usize>>(
self,
slot: &handoff::Slot<'req, 'd, H, O>,
out: &mut Slice<'_, L>,
) -> Result<ControlFlow<usize, handoff::Selection<'d, H::Selection, O>>, owned::Error> {
if !self.is_empty()
&& let Some(written) = handoff::copy::into(out, self.bytes)
{
return Ok(ControlFlow::Break(written));
}
Ok(ControlFlow::Continue(slot.fixed(self)))
}
}
impl AsRef<[u8]> for Body<'_> {
fn as_ref(&self) -> &[u8] {
self.bytes
}
}