use alloc::vec::Vec;
use core::iter::FromIterator;
use crate::MelinoeCell;
#[derive(Debug, Default)]
pub struct BrandedVec<'brand, T> {
pub(crate) cells: Vec<MelinoeCell<'brand, T>>,
}
impl<'brand, T> BrandedVec<'brand, T> {
#[inline]
#[must_use]
pub fn new() -> Self {
Self { cells: Vec::new() }
}
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
cells: Vec::with_capacity(capacity),
}
}
#[inline]
#[must_use]
pub fn from_fn<F>(len: usize, mut generate: F) -> Self
where
F: FnMut(usize) -> T,
{
let mut values = Self::with_capacity(len);
values.extend((0..len).map(&mut generate));
values
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.cells.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.cells.is_empty()
}
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.cells.capacity()
}
#[inline]
#[must_use]
pub fn as_cells(&self) -> &[MelinoeCell<'brand, T>] {
&self.cells
}
#[inline]
#[must_use]
pub fn as_mut_cells(&mut self) -> &mut [MelinoeCell<'brand, T>] {
&mut self.cells
}
}
impl<'brand, T> Extend<T> for BrandedVec<'brand, T> {
#[inline]
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
self.cells.extend(iter.into_iter().map(MelinoeCell::new));
}
}
impl<'brand, T> FromIterator<T> for BrandedVec<'brand, T> {
#[inline]
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = T>,
{
let mut values = Self::new();
values.extend(iter);
values
}
}
impl<'brand, T> From<Vec<T>> for BrandedVec<'brand, T> {
#[inline]
fn from(values: Vec<T>) -> Self {
unsafe {
let mut values = core::mem::ManuallyDrop::new(values);
let ptr = values.as_mut_ptr().cast::<MelinoeCell<'brand, T>>();
Self {
cells: Vec::from_raw_parts(ptr, values.len(), values.capacity()),
}
}
}
}
impl<'brand, T> IntoIterator for BrandedVec<'brand, T> {
type Item = T;
type IntoIter = alloc::vec::IntoIter<T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.into_vec().into_iter()
}
}