o3 0.62.0

shared-nothing primitives
Documentation
use std::ptr;

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

/// Exclusive access to an initialized value whose storage retains destruction.
/// Ending this loan leaves the value and its destruction owned by the storage.
#[derive(Debug)]
#[repr(transparent)]
pub struct Occupied<'a, T> {
    pub(super) source: &'a mut Option<T>,
    pub(super) bound: ThreadBound,
}

impl<'a, T> Occupied<'a, T> {
    pub fn clear(self) {
        // SAFETY: this exclusive loan retains Some. Retire its value in place,
        // then clear the stale representation without another destructor.
        unsafe {
            ptr::drop_in_place(self.source.as_mut_slice().as_mut_ptr());
            drop(self.into_uninit());
        }
    }

    pub fn get(&self) -> &T {
        unsafe { mem::raw::initialized(self.source) }
    }

    pub fn get_mut(&mut self) -> &mut T {
        // SAFETY: this short loan projects the retained Some's sole value.
        unsafe { mem::raw::initialized_mut(self.source) }
    }

    /// Transfers the retained initialized loan without ending storage ownership.
    pub fn into_mut(self) -> &'a mut T {
        // SAFETY: consuming this capability transfers its original exclusive loan.
        // Storage keeps the same initialized value and destruction obligation.
        unsafe { mem::raw::initialized_mut(self.source) }
    }

    pub fn take(self) -> (T, mem::raw::Vacant<'a, T>) {
        // SAFETY: this consumed capability moves the selected value once, then
        // clears its owner's stale representation without dropping it. No value
        // pointer is accessed after clearing and no user code runs between them.
        let value = unsafe { self.source.as_mut_slice().as_mut_ptr().read() };
        (value, unsafe { self.into_uninit() })
    }

    /// # Safety
    /// The old value or all its owned parts were moved or destroyed exactly once.
    /// No value loan or pending destructor remains; never read the old value again.
    pub unsafe fn into_uninit(self) -> mem::raw::Vacant<'a, T> {
        unsafe { ptr::write(self.source, None) };
        mem::raw::Vacant {
            source: self.source,
            bound: self.bound,
        }
    }
}

impl<T> crate::mem::Return for Occupied<'_, T> {
    type Item = ();

    fn return_item(self, _: ()) {
        self.clear();
    }
}