o3 0.62.0

shared-nothing primitives
Documentation
use std::marker;

use crate::{
    base::marker::ThreadBound,
    mem::{self, lease},
};

/// A single-threaded counter from which refundable reservations are drawn.
#[repr(transparent)]
pub struct Ledger<Tag = ()> {
    pub(in crate::mem) remaining: mem::raw::Account,
    tag: marker::PhantomData<fn(Tag) -> Tag>,
}

/// Returns one unit to the exact ledger which created its lease.
#[repr(transparent)]
pub struct Return<'source, Tag = ()> {
    source: &'source mem::raw::Account,
    tag: marker::PhantomData<fn(Tag) -> Tag>,
}

/// An exclusive consumable reservation.
#[must_use = "unused quota is returned when the lease is dropped"]
#[repr(C)]
pub struct Lease<'source, Tag = ()> {
    source: &'source mem::raw::Account,
    remaining: usize,
    tag: marker::PhantomData<fn(Tag) -> Tag>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Exhausted;

/// The result of conditionally admitting one item under quota.
#[must_use = "admission reports whether work was acquired or quota was exhausted"]
pub enum Admission<T> {
    Item(T),
    Empty,
    Exhausted,
}

/// An exclusive loan admitting one quota debit after acquisition succeeds.
#[must_use = "commit only after acquiring an item"]
#[repr(transparent)]
pub struct Take<'a> {
    remaining: &'a mut usize,
    thread: ThreadBound,
}

impl Take<'_> {
    /// Commits the nonzero debit retained by this exclusive loan.
    pub fn commit(self) {
        *self.remaining -= 1;
    }
}

impl<Tag> Ledger<Tag> {
    pub const fn new(left: usize) -> Self {
        Self {
            remaining: mem::raw::Account::new(left),
            tag: marker::PhantomData,
        }
    }

    pub fn remaining(&self) -> usize {
        self.remaining.get()
    }

    /// Replaces the available quota after every reservation has ended.
    pub fn reset(&mut self, left: usize) {
        self.remaining = mem::raw::Account::new(left);
    }

    pub fn take(&self) -> Result<(), Exhausted> {
        self.remaining.reserve(1)
    }

    /// Reserves one refundable unit whose owner may consume its parts.
    pub fn open(&self) -> Option<mem::Lease<Return<'_, Tag>, lease::Open>> {
        self.take().ok()?;
        Some(mem::Lease::open(
            Return {
                source: &self.remaining,
                tag: marker::PhantomData,
            },
            (),
        ))
    }
}

impl<'source, Tag> Lease<'source, Tag> {
    /// Reserves an exclusive lease tied to `source`.
    ///
    /// A child lease is similarly tied to the borrow of its shared parent.
    pub fn reserve_up<SourceTag>(source: &'source Ledger<SourceTag>, limit: usize) -> Self {
        Self {
            source: &source.remaining,
            remaining: source.remaining.reserve_up(limit),
            tag: marker::PhantomData,
        }
    }

    pub fn reserve_all<SourceTag>(source: &'source Ledger<SourceTag>) -> Self {
        Self::reserve_up(source, usize::MAX)
    }

    pub const fn remaining(&self) -> usize {
        self.remaining
    }

    pub fn take(&mut self) -> Option<Take<'_>> {
        if self.remaining == 0 {
            return None;
        }
        Some(Take {
            remaining: &mut self.remaining,
            thread: ThreadBound::NEW,
        })
    }
}

impl<Tag> Drop for Lease<'_, Tag> {
    fn drop(&mut self) {
        self.source.refund_spare(self.remaining);
    }
}

impl<Tag> mem::Return for Return<'_, Tag> {
    type Item = ();

    fn return_item(self, (): Self::Item) {
        self.source.refund(1);
    }
}

const _: () = {
    use std::mem::{align_of, size_of};

    assert!(size_of::<Ledger>() == size_of::<usize>());
    assert!(align_of::<Ledger>() == align_of::<usize>());
    assert!(size_of::<Return<'static>>() == size_of::<usize>());
    assert!(size_of::<mem::Lease<Return<'static>>>() == size_of::<usize>());
    assert!(size_of::<Option<mem::Lease<Return<'static>>>>() == size_of::<usize>());
    assert!(size_of::<mem::Lease<Return<'static>, lease::Open>>() == size_of::<usize>());
    assert!(size_of::<Option<mem::Lease<Return<'static>, lease::Open>>>() == size_of::<usize>());
    assert!(size_of::<mem::raw::Shared<'_>>() == 2 * size_of::<usize>());
    assert!(size_of::<mem::raw::Shared<'_, (), lease::Open>>() == 2 * size_of::<usize>());
    assert!(size_of::<Lease<'static>>() == 2 * size_of::<usize>());
    assert!(size_of::<Admission<usize>>() == 2 * size_of::<usize>());
    let _: [(); size_of::<Option<Take<'_>>>()] = [(); size_of::<usize>()];
};