o3 0.60.0

shared-nothing primitives
Documentation
//! Private linear lease shared by resident completion registries.

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);

/// Two-word ownership of one slot in an exactly borrowed target.
/// The invariant reference retains the original registration lifetime and !Sync.
#[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)
        {
            // SAFETY: this lease owns the parked grant. Move it before Drop can reenter.
            drop(unsafe { entry.take_grant() });
        }
    }
}