use std::{convert::Infallible, marker::PhantomData};
use o3::buffer::{bytes::scope, hold, segments::Source, storage};
use crate::{
owner::handoff::{Origin, Selection, stage},
payload::fixed,
request::{Id, body},
};
#[doc(hidden)]
pub struct Slot<'req, 'd, H = (), B = body::Retained<'req, 'd>> {
pub(in crate::owner::handoff) origin: Origin<'req, 'd, B>,
pub(in crate::owner::handoff) head: H,
}
impl<'req, 'd> Slot<'req, 'd> {
pub const fn new(body: body::Ref<'req, 'd>) -> Self {
Self {
origin: match body.try_retained() {
Ok(body) => Origin::Retained(body),
Err(_) => Origin::Empty(PhantomData),
},
head: (),
}
}
pub const fn retained(body: body::Retained<'req, 'd>) -> Self {
Self {
origin: Origin::Retained(body),
head: (),
}
}
pub const fn empty() -> Self {
Self {
origin: Origin::Empty(PhantomData),
head: (),
}
}
pub const fn task(id: Id<'d>) -> Self {
Self {
origin: Origin::Task(id),
head: (),
}
}
}
impl<'req, 'd, OldHead, B> Slot<'req, 'd, OldHead, B> {
pub fn with_head<H: scope::Source>(self, head: H) -> Slot<'req, 'd, H, B> {
Slot {
origin: self.origin,
head,
}
}
}
impl<'req, 'd, H: scope::Source, B: stage::Body<'req, 'd>> Slot<'req, 'd, H, B> {
pub(crate) const fn clear(&self) -> Selection<'d, H::Selection, B> {
Selection::Empty
}
pub(crate) fn shared(&self, body: storage::Shared) -> Selection<'d, H::Selection, B> {
if body.is_empty() {
self.clear()
} else {
Selection::Retained(body)
}
}
pub(crate) fn segmented(
&self,
body: Source<'d>,
) -> Selection<'d, H::Selection, B> {
if body.is_empty() {
self.clear()
} else {
Selection::Segmented(body)
}
}
pub(crate) fn fixed(&self, body: fixed::Body<'d>) -> Selection<'d, H::Selection, B> {
if body.is_empty() {
self.clear()
} else {
Selection::Fixed(body)
}
}
pub(crate) fn request(
&self,
id: Id<'d>,
body: Source<'d>,
) -> Selection<'d, H::Selection, B> {
if body.is_empty() {
return self.clear();
}
match self.origin {
Origin::Task(expected) if expected == id => Selection::Linked(body),
_ => Selection::Segmented(body),
}
}
}
impl<'req, 'd> Slot<'req, 'd, (), Infallible> {
pub const fn ready(id: Option<Id<'d>>) -> Self {
Self {
origin: match id {
Some(id) => Origin::Task(id),
None => Origin::Empty(PhantomData),
},
head: (),
}
}
}
impl<'req, 'd: 'req, H, B: stage::Body<'req, 'd>> Slot<'req, 'd, H, B> {
pub fn linked_shared(&self, body: &storage::Shared) -> hold::Charge {
body.backing().map_or_else(hold::Charge::default, |owner| {
if let Origin::Retained(request) = self.origin
&& request.borrow().contains(owner)
{
hold::Charge::from_owner(owner.len(), owner.resident())
} else {
hold::Charge::default()
}
})
}
pub fn linked_segments(
&self,
body: &Source<'d>,
) -> hold::Charge {
let Origin::Retained(request) = self.origin else {
return hold::Charge::default();
};
match request.borrow() {
body::Retained::Segments(request) => body.linked_source(request),
body::Retained::Resident(request) => match request.backing() {
Some(request) => body.linked_backing(&request),
None => hold::Charge::default(),
}
}
}
}