use resident::Admission as _;
use crate::buffer::{
self,
hold::{Error, Retained},
resident, storage,
storage::{provided, regions::ResidentBacking},
};
pub unsafe trait Retain<'d>: buffer::Source {
fn resident<'a>(_: &Self::View<'a>) -> usize
where
Self: 'a,
{
0
}
fn try_copy<'a>(
plan: &Self::View<'a>,
budget: &resident::Budget<'d>,
) -> Result<storage::Owned<resident::Budget<'d>>, Error>
where
Self: 'a,
{
storage::Owned::try_from_slice(budget, buffer::Read::as_slice(plan))
.map_err(Error::Resident)
}
fn try_retain<'a>(
plan: &Self::View<'a>,
budget: &resident::Budget<'d>,
) -> Result<Retained<'d>, Error>
where
Self: 'a,
{
Self::try_copy(plan, budget).map(Into::into)
}
fn try_retain_with<'a>(
_: &Self::View<'a>,
_: &resident::Budget<'d>,
_: usize,
) -> Result<Option<Retained<'d>>, Error>
where
Self: 'a,
{
Ok(None)
}
}
unsafe impl<'d, L: provided::Layout> Retain<'d> for storage::Shared<provided::Owner<'d, L>>
where
resident::Kind<'d>: From<provided::Account<'d, L>>,
{
fn resident<'a>(plan: &Self::View<'a>) -> usize
where
Self: 'a,
{
plan.resident()
}
fn try_retain<'a>(
plan: &Self::View<'a>,
budget: &resident::Budget<'d>,
) -> Result<Retained<'d>, Error>
where
Self: 'a,
{
let std::ops::ControlFlow::Continue(owner) = provided::Prefix::from_view(*plan)
.try_account_with(*budget, ())
.map_err(Error::Account)?;
Ok(owner)
}
fn try_retain_with<'a>(
plan: &Self::View<'a>,
budget: &resident::Budget<'d>,
limit: usize,
) -> Result<Option<Retained<'d>>, Error>
where
Self: 'a,
{
Ok(provided::Prefix::from_view(*plan)
.try_account_with(*budget, resident::Cap(limit))
.map_err(Error::Account)?
.continue_value())
}
}
unsafe impl<'d, O> Retain<'d> for storage::Shared<Option<O>>
where
Option<O>: buffer::raw::Retain + buffer::Residency + ResidentBacking<'d> + Unpin,
{
fn resident<'a>(plan: &Self::View<'a>) -> usize
where
Self: 'a,
{
plan.resident()
}
fn try_retain<'a>(
plan: &Self::View<'a>,
_: &resident::Budget<'d>,
) -> Result<Retained<'d>, Error>
where
Self: 'a,
{
if plan.is_empty() {
return Ok(Retained::EMPTY);
}
let inner = plan.try_clone().map_err(resident::AllocError::Retain)?;
Ok(inner.into())
}
fn try_retain_with<'a>(
plan: &Self::View<'a>,
budget: &resident::Budget<'d>,
limit: usize,
) -> Result<Option<Retained<'d>>, Error>
where
Self: 'a,
{
let resident = plan.as_slice().len().max(Self::resident(plan));
let additional = plan.source.owner().additional(*budget, resident);
if resident::Cap(limit).check(*budget, additional).is_break() {
return Ok(None);
}
Self::try_retain(plan, budget).map(Some)
}
}