o3 0.61.0

shared-nothing primitives
Documentation
use crate::depot::arena::linked::slots;

/// Portable tagged index for Empty, Single, and Multi states.
#[derive(Debug)]
#[repr(transparent)]
pub struct Key(usize);

/// A decoded key whose retained owner is known to be nonempty.
pub(in crate::buffer::segments) enum Occupied {
    Single(slots::Index),
    Multi(slots::Index),
}

impl Key {
    const MULTI: usize = 1usize << (usize::BITS - 1);

    pub const EMPTY: Self = Self(0);

    pub const fn is_empty(&self) -> bool {
        self.0 == 0
    }

    pub(in crate::buffer::segments) const fn state(&self) -> Option<Occupied> {
        if self.0 == 0 {
            return None;
        }
        // SAFETY: the empty key was excluded above.
        Some(unsafe { self.occupied() })
    }

    /// # Safety
    /// This key retains a live single node or multi descriptor, never Empty.
    pub(in crate::buffer::segments) const unsafe fn occupied(&self) -> Occupied {
        let index = slots::Index::new(((self.0 & !Self::MULTI) - 1) as u32);
        if self.0 & Self::MULTI == 0 {
            Occupied::Single(index)
        } else {
            Occupied::Multi(index)
        }
    }

    pub(in crate::buffer::segments) fn single(index: slots::Index) -> Self {
        let value = index.raw() as usize + 1;
        Self(value)
    }

    pub(in crate::buffer::segments) fn multi(index: slots::Index) -> Self {
        let value = index.raw() as usize + 1;
        Self(Self::MULTI | value)
    }

    /// # Safety
    /// This key is in the multi state.
    pub(in crate::buffer::segments) const unsafe fn multi_index(&self) -> slots::Index {
        slots::Index::new(((self.0 & !Self::MULTI) - 1) as u32)
    }
}