o3 0.62.0

shared-nothing primitives
Documentation
use std::{cell, marker, mem, ops, pin, ptr};

use crate::{
    alloc::tail,
    depot::{
        arena::pool::{
            self,
            recycle::{self, release},
            shared::{Initialized, Resident},
        },
        capacity,
    },
    mem::rc,
};

pub(in crate::depot::arena::pool) use mutable::Mutable;
pub(in crate::depot::arena::pool) use policy::Policy;

mod mutable;
mod policy;

pub struct Vacant<'a, T, C = (), P: Policy<T, C> = ()> {
    entry: ptr::NonNull<Entry<T, C>>,
    owner: &'a recycle::Header<T, C>,
    policy: marker::PhantomData<P>,
}

#[repr(transparent)]
pub struct Unique<'a, T, C = (), P: Policy<T, C> = (), M = ()> {
    entry: ptr::NonNull<Entry<T, C>>,
    owner: pool::Domain<'a, T, C, P, M>,
}

#[derive(Debug)]
#[repr(transparent)]
pub struct Shared<'a, T> {
    entry: crate::mem::raw::Owner<Counted<T>>,
    owner: marker::PhantomData<fn(&'a T) -> &'a T>,
}

impl<'a, T, C, P: Policy<T, C>> Vacant<'a, T, C, P> {
    pub(crate) fn new(owner: &'a recycle::Header<T, C>) -> Option<Self> {
        let free = &owner.free;
        let entry = ptr::NonNull::new(free.get())?;
        free.set(unsafe { entry.as_ref().state.get().cast() });
        Some(Self {
            entry,
            owner,
            policy: marker::PhantomData,
        })
    }

    pub fn reserve(self) -> Unique<'a, T, C, P> {
        let this = mem::ManuallyDrop::new(self);
        unsafe {
            this.entry
                .as_ref()
                .state
                .set(ptr::from_ref(this.owner).cast_mut())
        };
        Unique {
            entry: this.entry,
            owner: marker::PhantomData,
        }
    }
}

impl<T, C, P: Policy<T, C>> Drop for Vacant<'_, T, C, P> {
    fn drop(&mut self) {
        unsafe { Entry::recycle(self.entry, &self.owner.free) };
    }
}

impl<'a, T, C, P: Policy<T, C>, M> Unique<'a, T, C, P, M> {
    pub fn get(&self) -> pin::Pin<&T> {
        // SAFETY: the owned entry is structurally pinned for the retained borrow.
        unsafe { pin::Pin::new_unchecked(&self.entry.as_ref().value) }
    }
}

impl<T, C, P: Mutable<T, C>> Unique<'_, T, C, P> {
    pub fn get_mut(&mut self) -> pin::Pin<&mut T> {
        // SAFETY: the owned entry is structurally pinned for the retained mutable borrow.
        unsafe { pin::Pin::new_unchecked(&mut self.entry.as_mut().value) }
    }
}

impl<'a, T> Unique<'a, T> {
    /// Transfers this reservation without recycling its slot.
    pub fn into_raw(self) -> ptr::NonNull<Entry<T>> {
        mem::ManuallyDrop::new(self).entry
    }

    /// # Safety
    /// The original Store's allocation and initialized slot stay live for 'a.
    /// This is its sole unrecycled default-policy reservation, with no value loan.
    pub unsafe fn from_raw(entry: ptr::NonNull<Entry<T>>) -> Self {
        Self {
            entry,
            owner: marker::PhantomData,
        }
    }
}

impl<'a, T> Unique<'a, Resident<T>, (), Initialized> {
    pub fn freeze(self) -> Shared<'a, T> {
        // SAFETY: begin/into_unique retain an initialized value with an empty reference domain.
        unsafe { crate::mem::raw::Edge::activate(self.get().get_ref()) };
        let this = mem::ManuallyDrop::new(self);
        Shared {
            // SAFETY: activation transfers one counted edge to the same transparent slot view.
            entry: unsafe { crate::mem::raw::Owner::from_raw(this.entry.cast()) },
            owner: marker::PhantomData,
        }
    }

    pub fn freeze_pair(self) -> (Shared<'a, T>, Shared<'a, T>) {
        // SAFETY: this unique view owns the empty domain and publishes exactly two edges.
        unsafe { crate::mem::raw::Edge::start_pair(self.get().get_ref()) };
        let this = mem::ManuallyDrop::new(self);
        (
            Shared {
                // SAFETY: activation transfers one counted edge to the same transparent slot view.
                entry: unsafe { crate::mem::raw::Owner::from_raw(this.entry.cast()) },
                owner: marker::PhantomData,
            },
            Shared {
                // SAFETY: activation transfers one counted edge to the same transparent slot view.
                entry: unsafe { crate::mem::raw::Owner::from_raw(this.entry.cast()) },
                owner: marker::PhantomData,
            },
        )
    }
}

impl<T, C, P: Policy<T, C>, M> Drop for Unique<'_, T, C, P, M> {
    fn drop(&mut self) {
        P::retire(Terminal {
            entry: self.entry,
            owner: marker::PhantomData,
        });
    }
}

impl<'a, T> Shared<'a, T> {
    /// # Safety
    /// The exact initialized entry must stay live for every use of the result.
    pub unsafe fn value_ptr(entry: ptr::NonNull<Entry<Resident<T>>>) -> ptr::NonNull<T> {
        // SAFETY: both value wrappers preserve T's address at this exact field offset.
        unsafe {
            entry
                .byte_add(mem::offset_of!(Entry<Resident<T>>, value.value))
                .cast()
        }
    }

    /// Transfers this counted edge without changing its reference count.
    pub fn into_raw(self) -> ptr::NonNull<Entry<Resident<T>>> {
        self.entry.into_raw().cast()
    }

    /// # Safety
    /// This is one unreleased edge from into_raw in the same live Store.
    /// The initialized allocation and count must remain valid for 'a.
    pub unsafe fn from_raw(entry: ptr::NonNull<Entry<Resident<T>>>) -> Self {
        Self {
            // SAFETY: the exact transferred edge and initialized target stay live.
            entry: unsafe { crate::mem::raw::Owner::from_raw(entry.cast()) },
            owner: marker::PhantomData,
        }
    }

    pub fn is_same(&self, other: &Self) -> bool {
        self.entry.as_ptr() == other.entry.as_ptr()
    }

    pub fn try_clone(&self) -> Result<Self, rc::Error> {
        Ok(Self {
            entry: self.entry.try_clone()?,
            owner: marker::PhantomData,
        })
    }

    /// Consumes this edge and returns the initialized slot only on the last release.
    pub fn into_unique(self) -> Option<Unique<'a, Resident<T>, (), Initialized>> {
        let entry = self.entry.into_raw();
        // SAFETY: the consumed Shared retains one live edge in this exact allocation.
        match unsafe { crate::mem::raw::Edge::release(entry.as_ref()) } {
            rc::Release::Shared => None,
            rc::Release::Last => Some(Unique {
                entry: entry.cast(),
                owner: marker::PhantomData,
            }),
        }
    }

    /// Returns the same counted edge when the initialized slot is shared.
    pub fn try_unique(self) -> Result<Unique<'a, Resident<T>, (), Initialized>, Self> {
        if !crate::mem::raw::Edge::is_unique(self.entry.get()) {
            return Err(self);
        }
        let entry = self.entry.into_raw();
        // SAFETY: this consumed edge is unique and no user code runs before retirement.
        unsafe { crate::mem::raw::Edge::retire(entry.as_ref()) };
        Ok(Unique {
            entry: entry.cast(),
            owner: marker::PhantomData,
        })
    }
}

impl<'owner, T> Unique<'owner, Resident<T>> {
    pub fn begin(mut self, value: T) -> Unique<'owner, Resident<T>, (), Initialized> {
        let resident = self.get_mut();
        unsafe { resident.value.get().write(mem::MaybeUninit::new(value)) };
        let this = mem::ManuallyDrop::new(self);
        Unique {
            entry: this.entry,
            owner: marker::PhantomData,
        }
    }

    pub fn commit(self, value: T) -> Shared<'owner, T> {
        self.begin(value).freeze()
    }
}

impl<T> ops::Deref for Unique<'_, Resident<T>, (), Initialized> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { (*self.get().value.get()).assume_init_ref() }
    }
}

impl<T> ops::DerefMut for Unique<'_, Resident<T>, (), Initialized> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { (*self.get().value.get()).assume_init_mut() }
    }
}

impl<T> ops::Deref for Shared<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { Self::value_ptr(self.entry.as_ptr().cast()).as_ref() }
    }
}

impl<'owner, T, C> Unique<'owner, T, C, release::Notify<'owner>>
where
    T: recycle::Recycle + 'owner,
    C: release::Context<'owner, T>,
{
    pub fn commit(self) -> Unique<'owner, T, C, release::Notify<'owner>, release::Frozen> {
        let this = mem::ManuallyDrop::new(self);
        Unique {
            entry: this.entry,
            owner: marker::PhantomData,
        }
    }
}

/// Physical pool slot; its value is the first field for native pointer round trips.
#[derive(Debug)]
#[repr(C)]
pub struct Entry<T, C = ()> {
    pub(in crate::depot::arena::pool) value: T,
    pub(in crate::depot::arena::pool) state: cell::Cell<*mut recycle::Header<T, C>>,
}

/// Counted view of the same initialized shared-value slot.
#[derive(Debug)]
#[repr(transparent)]
pub struct Counted<T> {
    entry: Entry<Resident<T>>,
}

// SAFETY: this view retains an initialized value and its original pool owner
// until the final counted edge transfers the slot to its retirement policy.
unsafe impl<T> crate::mem::raw::Target for Counted<T> {
    unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        <Initialized as Policy<Resident<T>, ()>>::retire(Terminal {
            entry: pointer.cast(),
            owner: marker::PhantomData,
        });
    }
}

pub struct Terminal<'a, T, C = ()> {
    pub(in crate::depot::arena::pool) entry: ptr::NonNull<Entry<T, C>>,
    pub(in crate::depot::arena::pool) owner: marker::PhantomData<&'a recycle::Header<T, C>>,
}

impl<'a, T, C> Terminal<'a, T, C> {
    pub fn get_mut(&mut self) -> pin::Pin<&mut T> {
        // SAFETY: the terminal entry is structurally pinned for the retained mutable borrow.
        unsafe { pin::Pin::new_unchecked(&mut self.entry.as_mut().value) }
    }

    pub(crate) fn recycle(self) -> &'a recycle::Header<T, C> {
        // SAFETY: this terminal entry retains its initialized owner's original loan.
        let owner = unsafe { &*self.entry.as_ref().state.get() };
        unsafe { Entry::recycle(self.entry, &owner.free) };
        owner
    }
}

impl<T, C> Entry<T, C> {
    pub(crate) fn try_new(
        capacity: capacity::Count,
        context: C,
        mut init: impl FnMut(u32) -> T,
    ) -> Result<tail::raw::Block<recycle::Header<T, C>, Self, capacity::Count>, crate::alloc::Error>
    {
        let mut block = tail::Plan::try_new(capacity)?
            .try_allocate()?
            .init(recycle::Header {
                free: cell::Cell::new(ptr::null_mut()),
                context: mem::ManuallyDrop::new(context),
            });
        let indices = 0..capacity.raw();
        let (header, entries) = block.parts_mut();
        let mut free: *mut Self = ptr::null_mut();
        for (index, slot) in indices.zip(entries) {
            let entry: *mut Self = slot.as_mut_ptr();
            // SAFETY: this exclusive final slot admits both fields and initializes T once.
            unsafe {
                ptr::addr_of_mut!((*entry).value).write(init(index));
                ptr::addr_of_mut!((*entry).state).write(cell::Cell::new(free.cast()));
            }
            free = entry;
        }
        // SAFETY: each initialized slot belongs to this retained pinned owner.
        header.free.set(free);
        // SAFETY: every admitted slot was initialized once in index order.
        Ok(unsafe { block.assume_init() })
    }

    pub(in crate::depot::arena::pool) unsafe fn recycle(
        entry: ptr::NonNull<Self>,
        free: &cell::Cell<*mut Self>,
    ) {
        unsafe {
            entry
                .as_ref()
                .state
                .set(free.replace(entry.as_ptr()).cast())
        };
    }
}

// SAFETY: the transparent view preserves the initialized entry's exact reference domain.
unsafe impl<T> crate::mem::raw::Edge for Counted<T> {
    fn count(&self) -> &crate::mem::raw::Count {
        crate::mem::raw::Edge::count(&self.entry.value)
    }
}