#[cfg(feature = "unsafe_init")]
use core::mem::{self, MaybeUninit};
use crate::all::{Array, Direct, Storage};
#[allow(unused)]
#[cfg(feature = "alloc")]
use {
crate::mem::Boxed,
alloc::{boxed::Box, vec::Vec},
};
impl<T, S: Storage, const LEN: usize> Array<T, S, LEN> {
pub fn new(array: [T; LEN]) -> Self {
Self {
array: array.into(),
}
}
}
impl<T: Clone, const LEN: usize> Array<T, (), LEN> {
pub fn with(element: T) -> Self {
#[cfg(feature = "unsafe_init")]
let data = Direct::new({
let mut arr: [MaybeUninit<T>; LEN] = unsafe { MaybeUninit::uninit().assume_init() };
for i in &mut arr[..] {
let _ = i.write(element.clone());
}
unsafe { mem::transmute_copy::<_, [T; LEN]>(&arr) }
});
#[cfg(not(feature = "unsafe_init"))]
let data = Direct::new(core::array::from_fn(|_| element.clone()));
Self { array: data }
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
impl<T: Clone, const LEN: usize> Array<T, Boxed, LEN> {
pub fn with(element: T) -> Self {
#[cfg(not(feature = "unsafe_init"))]
let data = {
let mut v = Vec::<T>::with_capacity(LEN);
for _ in 0..LEN {
v.push(element.clone());
}
let Ok(array) = v.into_boxed_slice().try_into() else {
panic!("Can't turn the boxed slice into a boxed array");
};
array
};
#[cfg(feature = "unsafe_init")]
let data = {
let mut v = Vec::<T>::with_capacity(LEN);
for _ in 0..LEN {
v.push(element.clone());
}
let slice = v.into_boxed_slice();
let raw_slice = Box::into_raw(slice);
unsafe { Box::from_raw(raw_slice as *mut [T; LEN]) }
};
Self { array: data }
}
}
impl<T: PartialEq, S: Storage, const CAP: usize> Array<T, S, CAP> {
pub fn contains(&self, element: &T) -> bool {
self.iter().any(|n| n == element)
}
}
impl<T, S: Storage, const LEN: usize> Array<T, S, LEN> {
#[inline]
pub const fn len(&self) -> usize {
LEN
}
#[inline]
pub const fn is_empty(&self) -> bool {
LEN == 0
}
pub fn as_slice(&self) -> &[T] {
self.array.as_slice()
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.array.as_mut_slice()
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
impl<T, const LEN: usize> Array<T, Boxed, LEN> {
pub fn into_array(self) -> Box<[T; LEN]> {
self.array
}
}
impl<T, const LEN: usize> Array<T, (), LEN> {
pub fn into_array(self) -> [T; LEN] {
self.array.0
}
}