use core::fmt::{self, Debug};
use core::num::NonZeroUsize;
use core::pin::Pin;
extern crate alloc;
use alloc::{boxed::Box, vec::Vec};
use super::{Slot, Storage};
pub struct HeapStorage<T> {
data: Box<[Slot<T>]>,
}
impl<T> HeapStorage<T> {
pub fn with_capacity(cap: NonZeroUsize) -> Self {
unsafe { Self::with_capacity_unchecked(cap.get()) }
}
pub unsafe fn with_capacity_unchecked(cap: usize) -> Self {
let mut data = Vec::new();
data.reserve_exact(cap);
unsafe { data.set_len(cap); }
Self { data: data.into_boxed_slice() }
}
}
unsafe impl<T> Storage for HeapStorage<T> {
type Item = T;
fn cap(&self) -> usize {
self.data.len()
}
fn get(&self) -> &[Slot<Self::Item>] {
&self.data
}
fn get_mut(&mut self) -> &mut [Slot<Self::Item>] {
&mut self.data
}
fn get_pin(self: Pin<&mut Self>) -> Pin<&mut [Slot<Self::Item>]> {
unsafe { self.map_unchecked_mut(|this| &mut *this.data) }
}
}
impl<T> Clone for HeapStorage<T> {
fn clone(&self) -> Self {
unsafe { Self::with_capacity_unchecked(self.cap()) }
}
}
impl<T> Debug for HeapStorage<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "HeapStorage")
}
}