use std::{cell::Cell, convert::Infallible, marker::PhantomData};
use crate::depot::queue::resident::{Key, Lanes, handoff::Cancel};
pub trait GrantIndex: Sized {
fn from_lane(lane: usize) -> Option<Self>;
}
impl GrantIndex for Infallible {
fn from_lane(_: usize) -> Option<Self> {
None
}
}
impl GrantIndex for usize {
fn from_lane(lane: usize) -> Option<Self> {
Some(lane)
}
}
type Binding<'a, W, G, P, L> = (&'a Lanes<W, G, P, L>, Key);
#[repr(transparent)]
pub struct Lease<'target, W, G, P: GrantIndex, L> {
pub(super) active: Option<Binding<'target, W, G, P, L>>,
target: PhantomData<Cell<Binding<'target, W, G, P, L>>>,
}
impl<W, G, P: GrantIndex, L> Lease<'_, W, G, P, L> {
pub const fn new() -> Self {
Self {
active: None,
target: PhantomData,
}
}
}
impl<W, G, P: GrantIndex, L> Default for Lease<'_, W, G, P, L> {
fn default() -> Self {
Self::new()
}
}
impl<W, G, P: GrantIndex, L> Drop for Lease<'_, W, G, P, L> {
fn drop(&mut self) {
if let Some((target, key)) = self.active
&& let Cancel::Grant(entry) = target.remove(key)
{
drop(unsafe { entry.take_grant() });
}
}
}