o3 0.62.0

shared-nothing primitives
Documentation
use crate::base::num::{self, sealed};
use crate::mem::Rejected;
use std::{convert, marker, mem, num::NonZero};

use crate::depot::{capacity, index::Stored, queue::links};

pub mod cycle;

/// The physical observation paired with the original branded key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Observation<const MAX: u32 = { u32::MAX }, B = (), R = (), C = capacity::Count> {
    Index { capacity: C },
    Free { actual: Generation<MAX> },
    Reserved { actual: Generation<MAX> },
    Retired { actual: Generation<MAX>, retired: R },
    Generation { actual: Generation<MAX> },
    Busy { actual: Generation<MAX>, borrow: B },
}

const _: () = assert!(mem::size_of::<Observation>() == 2 * mem::size_of::<u32>());

#[derive(Debug)]
#[repr(transparent)]
pub struct Handle<Tag = (), const MAX: u32 = { u32::MAX }, const COMPACT: bool = false> {
    parts: Parts<MAX>,
    marker: marker::PhantomData<*mut Tag>,
}

impl<Tag, const MAX: u32> Handle<Tag, MAX, false> {
    pub(crate) const fn new(index: u32, epoch: Generation<MAX>) -> Self {
        Self::from_parts(Parts::new(index, epoch))
    }

    #[doc(hidden)]
    pub const fn from_parts(parts: Parts<MAX>) -> Self {
        Self {
            parts,
            marker: marker::PhantomData,
        }
    }

    pub(in crate::depot) fn from_stored(raw: Stored<Self>) -> Self {
        // SAFETY: Stored retains a complete identity emitted by this Handle domain.
        let raw = unsafe { NonZero::<u64>::new_unchecked(raw.into_raw()) };
        Self::from_parts(Parts { raw })
    }

    pub const fn parts(self) -> Parts<MAX> {
        self.parts
    }
}

impl<Tag, const MAX: u32> From<Handle<Tag, MAX, false>> for Parts<MAX> {
    fn from(key: Handle<Tag, MAX, false>) -> Self {
        key.parts
    }
}

impl<Tag, const MAX: u32> Handle<Tag, MAX, true> {
    pub(in crate::depot) const fn from_index(index: links::Index, epoch: Generation<MAX>) -> Self {
        Self {
            parts: Parts::new(index.raw(), epoch),
            marker: marker::PhantomData,
        }
    }
}

impl<Tag, const MAX: u32> From<Handle<Tag, MAX, true>> for links::Index {
    fn from(handle: Handle<Tag, MAX, true>) -> Self {
        // SAFETY: the sole compact constructor excludes END.
        unsafe { Self::new_raw(handle.index()) }
    }
}

impl<Tag, const MAX: u32, const COMPACT: bool> Handle<Tag, MAX, COMPACT> {
    pub const fn index(self) -> u32 {
        self.parts.index()
    }

    pub const fn generation(self) -> Generation<MAX> {
        self.parts.generation()
    }
}

impl<Tag, const MAX: u32, const COMPACT: bool> Clone for Handle<Tag, MAX, COMPACT> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Tag, const MAX: u32, const COMPACT: bool> Copy for Handle<Tag, MAX, COMPACT> {}

impl<Tag, const MAX: u32, const COMPACT: bool> PartialEq for Handle<Tag, MAX, COMPACT> {
    fn eq(&self, other: &Self) -> bool {
        self.parts == other.parts
    }
}

impl<Tag, const MAX: u32, const COMPACT: bool> Eq for Handle<Tag, MAX, COMPACT> {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Parts<const MAX: u32 = { u32::MAX }> {
    raw: NonZero<u64>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Generation<const MAX: u32 = { u32::MAX }>(NonZero<u32>);

impl<const MAX: u32> Generation<MAX> {
    pub const MIN: Self = {
        assert!(MAX != 0, "generation limit must be nonzero");
        Self(NonZero::<u32>::MIN)
    };

    pub const fn get(self) -> u32 {
        self.0.get()
    }

    /// The retained generation as its nonzero wire value, without a second check.
    pub const fn nonzero(self) -> NonZero<u32> {
        self.0
    }

    #[must_use]
    pub const fn checked_add(self, value: u32) -> Option<Self> {
        match self.0.checked_add(value) {
            Some(next) if next.get() <= MAX => Some(Self(next)),
            _ => None,
        }
    }
}

impl<const MAX: u32> Default for Generation<MAX> {
    fn default() -> Self {
        const { Self::MIN }
    }
}

impl<const MAX: u32> num::Step for Generation<MAX> {
    const INITIAL: Self = Self::MIN;

    fn next(self) -> Option<Self> {
        self.checked_add(1)
    }
}

impl<const MAX: u32> Parts<MAX> {
    pub const fn new(index: u32, epoch: Generation<MAX>) -> Self {
        let raw = ((epoch.get() as u64) << 32) | index as u64;
        // SAFETY: the retained generation is nonzero, so the shifted epoch keeps the word nonzero.
        Self {
            raw: unsafe { NonZero::<u64>::new_unchecked(raw) },
        }
    }

    #[must_use]
    pub const fn from_raw(raw: NonZero<u64>) -> Option<Self> {
        let epoch = (raw.get() >> 32) as u32;
        if epoch == 0 || epoch > MAX {
            return None;
        }
        let _ = Generation::<MAX>::MIN;
        Some(Self { raw })
    }

    pub const fn into_raw(self) -> NonZero<u64> {
        self.raw
    }

    /// Widens the generation domain while retaining the packed identity.
    pub const fn widen<const TO: u32>(self) -> Parts<TO> {
        const { assert!(MAX <= TO, "bounds") };
        Parts { raw: self.raw }
    }

    pub const fn index(self) -> u32 {
        self.raw.get() as u32
    }

    pub const fn generation(self) -> Generation<MAX> {
        let _ = Generation::<MAX>::MIN;
        Generation(
            // SAFETY: the packed word retains a nonzero generation in its high half.
            unsafe { NonZero::<u32>::new_unchecked((self.raw.get() >> 32) as u32) },
        )
    }
}

const _: () = {
    assert!(mem::size_of::<Generation>() == mem::size_of::<u32>());
    assert!(mem::size_of::<Option<Generation>>() == mem::size_of::<Generation>());
    assert!(mem::size_of::<Parts>() == mem::size_of::<u64>());
    assert!(mem::size_of::<Option<Parts>>() == mem::size_of::<Parts>());
    assert!(mem::size_of::<Handle>() == mem::size_of::<Parts>());
    assert!(mem::size_of::<Option<Handle>>() == mem::size_of::<Handle>());
};

impl<const MAX: u32, B, R, C: Copy> Observation<MAX, B, R, C> {
    pub fn as_ref(&self) -> Observation<MAX, &B, &R, C> {
        match self {
            Self::Index { capacity } => Observation::Index {
                capacity: *capacity,
            },
            Self::Free { actual } => Observation::Free { actual: *actual },
            Self::Reserved { actual } => Observation::Reserved { actual: *actual },
            Self::Retired { actual, retired } => Observation::Retired {
                actual: *actual,
                retired,
            },
            Self::Generation { actual } => Observation::Generation { actual: *actual },
            Self::Busy { actual, borrow } => Observation::Busy {
                actual: *actual,
                borrow,
            },
        }
    }
}
const _: () = {
    assert!(size_of::<Rejected<Handle, Observation>>() == 2 * size_of::<u64>());
    assert!(
        size_of::<Option<Rejected<Handle, Observation>>>()
            == size_of::<Rejected<Handle, Observation>>()
    );
    assert!(
        size_of::<(
            Handle,
            Observation<{ u32::MAX }, convert::Infallible, (), convert::Infallible>
        )>() == 2 * size_of::<u64>()
    );
};

impl<const MAX: u32> sealed::Sealed for Generation<MAX> {}

const _: () = assert!(
    size_of::<
        Option<(
            Handle,
            Observation<{ u32::MAX }, convert::Infallible, (), convert::Infallible>
        )>,
    >() == size_of::<(
        Handle,
        Observation<{ u32::MAX }, convert::Infallible, (), convert::Infallible>
    )>()
);