use super::traits::{Storage, StorageMut};
use std::borrow::Cow;
pub struct CowStorage<'a, T: Clone> {
data: Cow<'a, [T]>,
}
impl<'a, T: Clone> CowStorage<'a, T> {
#[inline]
pub const fn borrowed(slice: &'a [T]) -> Self {
Self {
data: Cow::Borrowed(slice),
}
}
#[inline]
pub const fn owned(data: Vec<T>) -> Self {
Self {
data: Cow::Owned(data),
}
}
#[inline]
pub const fn is_borrowed(&self) -> bool {
matches!(self.data, Cow::Borrowed(_))
}
#[inline]
pub const fn is_owned(&self) -> bool {
matches!(self.data, Cow::Owned(_))
}
#[inline]
pub const fn as_borrowed(&self) -> Option<&'a [T]> {
match &self.data {
Cow::Borrowed(slice) => Some(slice),
Cow::Owned(_) => None,
}
}
#[inline]
pub const fn as_owned(&self) -> Option<&Vec<T>> {
match &self.data {
Cow::Borrowed(_) => None,
Cow::Owned(data) => Some(data),
}
}
#[inline]
pub fn into_owned(self) -> Vec<T> {
self.data.into_owned()
}
}
impl<'a, T: Clone> Storage<T> for CowStorage<'a, T> {
#[inline]
fn as_slice(&self) -> &[T] {
self.data.as_ref()
}
}
impl<'a, T: Clone> StorageMut<T> for CowStorage<'a, T> {
#[inline]
fn as_mut_slice(&mut self) -> &mut [T] {
self.data.to_mut()
}
}