o3 0.62.0

shared-nothing primitives
Documentation
use std::{
    mem::{ManuallyDrop, MaybeUninit},
    pin, ptr,
};

use crate::{base::marker::ThreadBound, mem::slot::Occupied};

pub(super) fn detach<T>(owner: Occupied<'_, T>) -> &mut T {
    // SAFETY: the sole destructor is disarmed before its exclusive borrow moves out.
    unsafe { ptr::read(&ManuallyDrop::new(owner).value) }
}

pub(super) fn pinned<'p, T>(owner: &'p mut Occupied<'_, T>) -> pin::Pin<&'p mut T> {
    // SAFETY: with_pin borrows its consumed owner here and drops it in place on return.
    unsafe { pin::Pin::new_unchecked(&mut *owner.value) }
}

pub(super) fn clear<T>(owner: &mut Occupied<'_, T>) {
    // SAFETY: only Occupied::drop consumes this destructor at its original address.
    unsafe { ptr::drop_in_place(owner.value) };
}

/// Exclusive initialization authority; the backing has no value destructor.
#[derive(Debug)]
#[repr(transparent)]
pub struct Vacant<'a, T> {
    value: &'a mut MaybeUninit<T>,
    bound: ThreadBound,
}

impl<'a, T> Vacant<'a, T> {
    pub fn new(value: &'a mut MaybeUninit<T>) -> Self {
        Self {
            value,
            bound: ThreadBound::NEW,
        }
    }

    pub(super) fn release(owner: Occupied<'a, T>) -> Self {
        let place = ptr::from_mut(detach(owner)).cast::<MaybeUninit<T>>();
        Self::new(unsafe { &mut *place })
    }

    pub(super) fn take(owner: Occupied<'a, T>) -> (T, Self) {
        let vacant = Self::release(owner);
        (unsafe { vacant.value.assume_init_read() }, vacant)
    }

    pub fn get_mut(&mut self) -> &mut MaybeUninit<T> {
        self.value
    }

    /// # Safety
    /// This slot contains one valid, exclusively owned T with no prior pinning obligation.
    pub unsafe fn assume_init(self) -> Occupied<'a, T> {
        Occupied::new(unsafe { self.value.assume_init_mut() }, self.bound)
    }

    pub fn insert(self, value: T) -> Occupied<'a, T> {
        Occupied::new(self.value.write(value), self.bound)
    }
}

const _: () = {
    assert!(size_of::<Vacant<'_, ()>>() == size_of::<usize>());
    assert!(size_of::<Option<Vacant<'_, ()>>>() == size_of::<usize>());
};