o3 0.62.0

shared-nothing primitives
Documentation
//! Single-value ownership in exclusively borrowed, uninitialized storage.

use std::{borrow, ops, pin};

use crate::base::marker::ThreadBound;

pub mod raw;

/// Owns one initialized value while exclusively borrowing its backing storage.
/// Forgetting it leaks the value; the backing never owns a second destructor.
#[derive(Debug)]
#[repr(transparent)]
pub struct Occupied<'a, T> {
    value: &'a mut T,
    bound: ThreadBound,
}

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

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

    /// Moves out the initialized value, releasing its borrowed backing.
    pub fn into_inner(self) -> T {
        self.take().0
    }

    /// Moves out the value while retaining its exact vacant backing.
    pub fn take(self) -> (T, raw::Vacant<'a, T>) {
        raw::Vacant::take(self)
    }

    /// Returns the same backing without reading or dropping the stored value.
    /// The original exclusive loan transfers after disarming its sole destructor.
    pub fn into_uninit(self) -> raw::Vacant<'a, T> {
        raw::Vacant::release(self)
    }

    /// Pins this initialized value until the callback returns, then drops it in place.
    /// The consumed owner retains destruction even if the callback forgets its pin.
    pub fn with_pin<R>(mut self, run: impl for<'p> FnOnce(pin::Pin<&'p mut T>) -> R) -> R {
        run(raw::pinned(&mut self))
    }
}

impl<'a, T, U> Occupied<'a, (T, U)> {
    /// Transfers each field's destruction right at its original address.
    pub fn split(self) -> (Occupied<'a, T>, Occupied<'a, U>) {
        let bound = self.bound;
        let (first, second) = raw::detach(self);
        (Occupied::new(first, bound), Occupied::new(second, bound))
    }
}

impl<T> borrow::Borrow<T> for Occupied<'_, T> {
    fn borrow(&self) -> &T {
        self.value
    }
}

impl<T> borrow::BorrowMut<T> for Occupied<'_, T> {
    fn borrow_mut(&mut self) -> &mut T {
        self.value
    }
}

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

    fn deref(&self) -> &T {
        self.value
    }
}

impl<T> Drop for Occupied<'_, T> {
    /// Consumes this affine owner's value once; its borrowed backing has no destructor.
    fn drop(&mut self) {
        raw::clear(self);
    }
}

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