ladata/list/array/
methods.rs1#[cfg(feature = "unsafe_init")]
7use core::mem::{self, MaybeUninit};
8
9use crate::all::{Array, Direct, Storage};
10
11#[allow(unused)]
12#[cfg(feature = "alloc")]
13use {
14 crate::mem::Boxed,
15 alloc::{boxed::Box, vec::Vec},
16};
17
18impl<T, S: Storage, const LEN: usize> Array<T, S, LEN> {
20 pub fn new(array: [T; LEN]) -> Self {
22 Self {
23 array: array.into(),
24 }
25 }
26}
27
28impl<T: Clone, const LEN: usize> Array<T, (), LEN> {
30 pub fn with(element: T) -> Self {
40 #[cfg(feature = "unsafe_init")]
41 let data = Direct::new({
42 let mut arr: [MaybeUninit<T>; LEN] = unsafe { MaybeUninit::uninit().assume_init() };
43
44 for i in &mut arr[..] {
45 let _ = i.write(element.clone());
46 }
47
48 unsafe { mem::transmute_copy::<_, [T; LEN]>(&arr) }
55 });
56
57 #[cfg(not(feature = "unsafe_init"))]
58 let data = Direct::new(core::array::from_fn(|_| element.clone()));
59
60 Self { array: data }
61 }
62}
63
64#[cfg(feature = "alloc")]
66#[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
67impl<T: Clone, const LEN: usize> Array<T, Boxed, LEN> {
68 pub fn with(element: T) -> Self {
78 #[cfg(not(feature = "unsafe_init"))]
79 let data = {
80 let mut v = Vec::<T>::with_capacity(LEN);
81
82 for _ in 0..LEN {
83 v.push(element.clone());
84 }
85
86 let Ok(array) = v.into_boxed_slice().try_into() else {
87 panic!("Can't turn the boxed slice into a boxed array");
88 };
89 array
90 };
91
92 #[cfg(feature = "unsafe_init")]
93 let data = {
94 let mut v = Vec::<T>::with_capacity(LEN);
95
96 for _ in 0..LEN {
97 v.push(element.clone());
98 }
99
100 let slice = v.into_boxed_slice();
101 let raw_slice = Box::into_raw(slice);
102 unsafe { Box::from_raw(raw_slice as *mut [T; LEN]) }
104 };
105
106 Self { array: data }
107 }
108}
109
110impl<T: PartialEq, S: Storage, const CAP: usize> Array<T, S, CAP> {
112 pub fn contains(&self, element: &T) -> bool {
124 self.iter().any(|n| n == element)
125 }
126}
127
128impl<T, S: Storage, const LEN: usize> Array<T, S, LEN> {
130 #[inline]
132 pub const fn len(&self) -> usize {
133 LEN
134 }
135
136 #[inline]
138 pub const fn is_empty(&self) -> bool {
139 LEN == 0
140 }
141
142 pub fn as_slice(&self) -> &[T] {
144 self.array.as_slice()
145 }
146
147 pub fn as_mut_slice(&mut self) -> &mut [T] {
149 self.array.as_mut_slice()
150 }
151}
152
153#[cfg(feature = "alloc")]
155#[cfg_attr(feature = "nightly", doc(cfg(feature = "alloc")))]
156impl<T, const LEN: usize> Array<T, Boxed, LEN> {
157 pub fn into_array(self) -> Box<[T; LEN]> {
159 self.array
160 }
161}
162impl<T, const LEN: usize> Array<T, (), LEN> {
164 pub fn into_array(self) -> [T; LEN] {
166 self.array.0
167 }
168}