use crate::{base::marker::ThreadBound, mem};
#[derive(Debug)]
#[repr(C)]
pub struct Storage<T, M = ()> {
pub(in crate::mem) value: Option<T>,
metadata: M,
bound: ThreadBound,
}
impl<T, M> Storage<T, M> {
pub unsafe fn project(&self) -> &T {
unsafe { mem::raw::initialized(&self.value) }
}
pub unsafe fn project_mut(&mut self) -> &mut T {
unsafe { mem::raw::initialized_mut(&mut self.value) }
}
pub unsafe fn occupy(&mut self) -> mem::raw::Occupied<'_, T> {
mem::raw::Occupied {
source: &mut self.value,
bound: ThreadBound::NEW,
}
}
pub unsafe fn vacancy(&mut self) -> mem::raw::Vacant<'_, T> {
mem::raw::Vacant {
source: &mut self.value,
bound: ThreadBound::NEW,
}
}
pub const fn new(metadata: M) -> Self {
Self {
value: None,
metadata,
bound: ThreadBound::NEW,
}
}
pub const fn filled(value: T, metadata: M) -> Self {
Self {
value: Some(value),
metadata,
bound: ThreadBound::NEW,
}
}
pub fn insert(&mut self, value: T) -> mem::raw::Occupied<'_, T> {
self.value = Some(value);
unsafe { self.occupy() }
}
pub const fn metadata(&self) -> &M {
&self.metadata
}
pub fn metadata_mut(&mut self) -> &mut M {
&mut self.metadata
}
pub const fn get(&self) -> Option<&T> {
self.value.as_ref()
}
pub fn get_mut(&mut self) -> Option<&mut T> {
self.value.as_mut()
}
pub fn occupied(&mut self) -> Option<mem::raw::Occupied<'_, T>> {
self.value.as_ref()?;
Some(unsafe { self.occupy() })
}
pub fn vacant(&mut self) -> Option<mem::raw::Vacant<'_, T>> {
if self.value.is_some() {
return None;
}
Some(unsafe { self.vacancy() })
}
}