o3 0.62.0

shared-nothing primitives
Documentation
use std::{marker, mem, num, ptr, slice};

use crate::{
    buffer::{
        self, resident, storage,
        storage::alloc,
        write::{self, consume},
    },
    mem::rc,
};

/// One allocation whose complete data region is initialized.
#[derive(Debug)]
#[repr(transparent)]
pub(in crate::buffer) struct Init<P: buffer::raw::Policy = ()> {
    allocation: buffer::raw::Heap<P>,
}

/// One complete allocation, with its plain or resident policy encoded in bit zero.
#[derive(Debug)]
#[repr(transparent)]
pub(in crate::buffer) struct Complete<'d> {
    pointer: ptr::NonNull<storage::raw::Prefix<num::NonZero<u32>>>,
    ownership: marker::PhantomData<Init<resident::Budget<'d>>>,
}

impl<P: buffer::raw::Policy> Init<P> {
    /// # Safety
    /// The retained sources must exactly fill the new, disjoint allocation.
    pub(in crate::buffer) unsafe fn try_copy(
        capacity: num::NonZero<u32>,
        sources: impl buffer::raw::Transfer,
        seed: P,
    ) -> Result<Self, alloc::Error<P::Failure>> {
        let mut heap = buffer::raw::Heap::try_new(seed, capacity)?;
        // SAFETY: the admitted source bytes initialize this exact destination.
        unsafe { sources.copy_to(heap.as_mut_ptr().cast()) };
        Ok(Self { allocation: heap })
    }

    pub(in crate::buffer) fn try_full(
        owner: storage::Owned<P>,
    ) -> Result<Option<Self>, consume::Error> {
        consume::Error::check(owner.capacity(), owner.len())?;
        Ok(owner.allocation.map(|heap| Self { allocation: heap }))
    }

    pub(in crate::buffer) fn capacity(&self) -> num::NonZero<u32> {
        self.allocation.capacity()
    }

    pub(in crate::buffer) fn as_slice(&self) -> &[u8] {
        // SAFETY: construction proves the complete allocation is initialized,
        // and this owner keeps the header and data live for the borrow.
        unsafe {
            slice::from_raw_parts(
                self.allocation.as_ptr().cast(),
                self.capacity().get() as usize,
            )
        }
    }

    pub(in crate::buffer) fn into_owned(self) -> storage::Owned<P> {
        storage::Owned {
            len: self.capacity().get(),
            allocation: Some(self.allocation),
        }
    }

    pub(in crate::buffer) fn into_buf(
        self,
    ) -> storage::Shared<crate::mem::raw::Owner<buffer::raw::Header<P>>> {
        let len = self.capacity();
        // SAFETY: Init transfers its fully initialized extent with its original owner.
        unsafe { buffer::raw::Header::into_range(self.allocation.into_shared(), 0, len.get()) }
    }
}

impl Init<()> {
    pub(in crate::buffer) fn bind<'d>(self) -> storage::raw::Complete<'d> {
        Complete {
            pointer: self.allocation.into_shared().into_raw().cast(),
            ownership: marker::PhantomData,
        }
    }
}

impl<'d> Init<resident::Budget<'d>> {
    pub(in crate::buffer) fn bind(self) -> storage::raw::Complete<'d> {
        Complete {
            pointer: self
                .allocation
                .into_shared()
                .into_raw()
                .cast()
                .map_addr(|address| address | 1),
            ownership: marker::PhantomData,
        }
    }
}

const _: () = assert!(size_of::<Init>() == size_of::<usize>());

impl<'d> Complete<'d> {
    pub(in crate::buffer) fn as_slice<'a>(&'a self) -> &'a [u8] {
        let pointer = self.pointer();
        let bytes = if self.pointer.addr().get() & 1 == 0 {
            // SAFETY: the plain Init constructor transfers its entire initialized allocation.
            unsafe { buffer::raw::Header::<()>::slice(pointer.cast()) }
        } else {
            // SAFETY: bit zero encodes the transferred resident Init and its exact lifetime.
            unsafe { buffer::raw::Header::<resident::Budget<'d>>::slice(pointer.cast()) }
        };
        // SAFETY: this owner borrow keeps the complete initialized region live.
        unsafe { bytes.as_ref() }
    }

    pub(in crate::buffer) fn into_buf(self) -> storage::Shared<resident::State<'d>> {
        let this = mem::ManuallyDrop::new(self);
        let pointer = this.pointer();
        // SAFETY: the tag identifies the exact retained header. Its entire allocation
        // is initialized. Each arm consumes the single edge into its final owner.
        let (bytes, owner) = unsafe {
            if this.pointer.addr().get() & 1 == 0 {
                let header = pointer.cast::<buffer::raw::Header<()>>();
                (
                    buffer::raw::Header::slice(header),
                    resident::Kind::Owned(storage::raw::Tag::allocation(
                        crate::mem::raw::Owner::from_raw(header),
                    )),
                )
            } else {
                let header = pointer.cast::<buffer::raw::Header<resident::Budget<'d>>>();
                (
                    buffer::raw::Header::slice(header),
                    resident::Kind::Resident(crate::mem::raw::Owner::from_raw(header)),
                )
            }
        };
        storage::Shared {
            owner: resident::State(owner),
            bytes: storage::raw::Extent(bytes),
        }
    }

    pub(in crate::buffer) fn bytes(&self) -> usize {
        self.prefix().word().get() as usize
    }

    fn pointer(&self) -> ptr::NonNull<storage::raw::Prefix<num::NonZero<u32>>> {
        // SAFETY: both constructors own aligned nonzero headers; only bit zero is encoded.
        self.pointer
            .map_addr(|address| unsafe { num::NonZero::new_unchecked(address.get() & !1) })
    }

    fn prefix(&self) -> &storage::raw::Prefix<num::NonZero<u32>> {
        // SAFETY: both complete allocation policies begin with a live Prefix.
        unsafe { self.pointer().as_ref() }
    }
}

impl Complete<'_> {
    pub(in crate::buffer) fn try_clone(&self) -> Result<Self, rc::Error> {
        use crate::mem::raw::Edge as _;

        // SAFETY: this complete owner retains the same initialized allocation during retention.
        unsafe { self.prefix().try_retain() }?;
        Ok(Self {
            pointer: self.pointer,
            ownership: marker::PhantomData,
        })
    }
}

impl<'d> Drop for Complete<'d> {
    fn drop(&mut self) {
        use crate::mem::raw::Edge as _;

        // SAFETY: Drop consumes this complete allocation's exact edge once.
        if unsafe { self.prefix().release() } != rc::Release::Last {
            return;
        }
        let pointer = self.pointer();
        if self.pointer.addr().get() & 1 == 0 {
            // SAFETY: the last plain allocation edge grants exclusive destruction.
            unsafe { buffer::raw::Header::<()>::destroy(pointer.cast()) };
        } else {
            // SAFETY: the last resident allocation edge retains its exact policy lifetime.
            unsafe { buffer::raw::Header::<resident::Budget<'d>>::destroy(pointer.cast()) };
        }
    }
}

const _: () = {
    assert!(align_of::<buffer::raw::Header<()>>() > 1);
    assert!(align_of::<buffer::raw::Header<resident::Budget<'static>>>() > 1);
    assert!(size_of::<Complete<'static>>() == size_of::<ptr::NonNull<()>>());
    assert!(size_of::<Option<Complete<'static>>>() == size_of::<ptr::NonNull<()>>());
};

impl<P: buffer::raw::Policy> write::Init for storage::Owned<P> {
    fn try_init<I: buffer::raw::Initializer>(&mut self, source: I) -> Result<(), Self::Error> {
        // SAFETY: Exclusive pairs the disjoint length and spare on this exact allocation.
        unsafe { write::raw::try_initialize(buffer::raw::Exclusive::spare_parts(self), source) }
    }
}

impl Init {
    /// # Safety
    /// The retained sources contain exactly this positive initialized byte count.
    pub(in crate::buffer) unsafe fn try_bytes(
        len: num::NonZero<usize>,
        sources: impl buffer::raw::Transfer,
    ) -> Result<Self, storage::AllocError> {
        let capacity = num::NonZero::<u32>::try_from(len).map_err(|_range| {
            storage::AllocError::Capacity(consume::Error::new(len, u32::MAX as usize))
        })?;
        // SAFETY: the same length is admitted into the allocation domain.
        Ok(unsafe { Self::try_copy(capacity, sources, ()) }?)
    }
}

impl TryFrom<storage::NonEmpty<&[u8]>> for Init {
    type Error = storage::AllocError;

    fn try_from(source: storage::NonEmpty<&[u8]>) -> Result<Self, Self::Error> {
        // SAFETY: this retained slice supplies its own admitted positive length.
        unsafe { Self::try_bytes(source.len(), source.into_storage()) }
    }
}