1#![no_std]
7
8#![doc = include_str!("README.md")]
10
11#![allow(incomplete_features)]
13
14#![feature(const_cmp)]
16#![feature(const_destruct)]
17#![feature(const_drop_in_place)]
18#![feature(const_array)]
19#![feature(const_try)]
20#![feature(transmute_neo)]
21#![feature(const_index)]
22#![feature(const_range)]
23#![feature(maybe_uninit_uninit_array_transpose)]
24#![feature(const_closures)]
25#![feature(const_trait_impl)]
26#![feature(const_heap)]
27#![feature(trusted_len)]
28#![feature(const_clone)]
29#![feature(new_range)]
30#![feature(const_slice_make_iter)]
31#![feature(generic_const_exprs)]
32#![feature(const_iter)]
33#![feature(const_convert)]
34#![feature(const_default)]
35
36extern crate alloc;
38
39mod comparisons;
41mod conversions;
42mod errors;
43mod iterators;
44mod references;
45
46use core::{
48 fmt::{
49 Debug,
50 Formatter,
51 Result as Format
52 },
53 marker::Destruct,
54 mem::{
55 MaybeUninit,
56 forget,
57 transmute_neo as transmute
58 },
59 ops::{
60 Bound,
61 Drop,
62 RangeBounds
63 },
64 array::from_fn as arrayfn,
65 ptr::copy,
66 hint::unreachable_unchecked
67};
68
69use constrangeiter::ConstIntoIterator;
71
72pub use errors::{
74 CapacityExceeded,
75 UnmatchedCapacity
76};
77
78
79pub struct Array<Type, const N: usize> {
85 length: usize,
86 data: [MaybeUninit<Type>; N]
87}
88
89impl<Type, const N: usize> Array<Type, N> {
91 pub const fn len(&self) -> usize {return self.length}
92 pub const fn new() -> Self {return Self::default()}
93 pub const fn is_full(&self) -> bool {return self.length == N}
94 pub const fn repeat<const TIMES: usize>(self) -> Array<
95 Type,
96 {TIMES * N}
97 > where Type: [const] Clone + [const] Destruct, [(); TIMES * N]: {
98 let (length, mut data) = self.into();
99 let mut additional = MaybeUninit::<[Type; TIMES * N]>::uninit().transpose();
100 if TIMES == 0 {for index in (0..length).const_into_iter() {
101 unsafe {data[index].assume_init_drop();};
102 }} else {
103 for index in (0..length).const_into_iter() {
104 additional[index].write(unsafe {data[index].assume_init_read()});
105 }
106 for iteration in (1..TIMES).const_into_iter() {
107 for index in (0..length).const_into_iter() {
108 additional[index + length * iteration].write(unsafe {
109 data[index].assume_init_ref().clone()
110 });
111 }
112 }
113 }
114 return Array::from((length * TIMES, additional));
115 }
116 pub const fn resize<const M: usize>(
117 self
118 ) -> Array<Type, M> where Type: [const] Destruct {
119 let (length, mut data) = self.into();
120 let mut additional = MaybeUninit::<[Type; M]>::uninit().transpose();
121 return if M >= length {
122 for index in (0..length).const_into_iter() {
123 additional[index].write(unsafe {data[index].assume_init_read()});
124 }
125 Array::from((length, additional))
126 } else {
127 for index in (0..M).const_into_iter() {
128 additional[index].write(unsafe {data[index].assume_init_read()});
129 }
130 for index in (M..length).const_into_iter() {
131 unsafe {data[index].assume_init_drop()};
132 }
133 Array::from((M, additional))
134 }
135 }
136 pub const fn divide<const AT: usize>(self) -> (
137 Array<Type, AT>,
138 Array<Type, {N - AT}>
139 ) where [(); N - AT]: {
140 let (length, data) = self.into();
141 let (first, second) = unsafe {transmute(data)};
142 return (Array {
143 length: length.min(AT),
144 data: first
145 }, Array {
146 length: length.saturating_sub(AT),
147 data: second
148 })
149 }
150 pub const fn join<const M: usize>(self, other: Array<Type, M>) -> Array<Type, {N + M}> {
151 let (length, data) = self.into();
152 let (slength, sdata) = other.into();
153 let mut together = unsafe {transmute::<_, [MaybeUninit<Type>; N + M]>((data, sdata))};
154 let pointer = together.as_mut_ptr();
155 unsafe {copy(
156 pointer.add(N),
157 pointer.add(length),
158 slength
159 )}
160 return Array {
161 length: length + slength,
162 data: together
163 }
164 }
165 #[track_caller]
166 pub const fn push(&mut self, value: Type) -> () {
167 self.push_mut(value);
168 }
169 #[track_caller]
170 pub const fn push_mut<'valid>(&'valid mut self, value: Type) -> &'valid mut Type {
171 let reference = self.data[self.length].write(value);
172 self.length += 1;
173 return reference;
174 }
175 pub const fn pop(&mut self) -> Option<Type> {return if self.length == 0 {None} else {
176 self.length -= 1;
177 Some(unsafe {self.data[self.length].assume_init_read()})
178 }}
179 pub const fn pop_if(
180 &mut self,
181 decider: impl [const] FnOnce(&mut Type) -> bool + [const] Destruct
182 ) -> Option<Type> {return if decider(self.last_mut()?) {self.pop()} else {None}}
183 pub const fn clear(&mut self) -> () where Type: [const] Destruct {self.truncate(0)}
184 pub const fn truncate(&mut self, length: usize) -> () where Type: [const] Destruct {
185 for index in (length..self.length).const_into_iter() {
186 unsafe {self.data.get_unchecked_mut(index).assume_init_drop()};
187 }
188 self.length = length;
189 }
190 #[track_caller]
191 pub const fn insert(&mut self, index: usize, value: Type) -> () {
192 self.insert_mut(index, value);
193 }
194 #[track_caller]
195 pub const fn insert_mut<'valid>(
196 &'valid mut self,
197 index: usize,
198 value: Type
199 ) -> &'valid mut Type {
200 assert!(index <= self.length, "tried to insert out of bounds");
201 assert!(self.length != N, "array capacity exceeded");
202 let pointer = unsafe {self.data.as_mut_ptr().add(index)};
203 unsafe {copy(
204 pointer,
205 pointer.add(1),
206 self.length - index
207 )};
208 let reference = unsafe {self.data.get_unchecked_mut(index).write(value)};
209 self.length += 1;
210 return reference;
211 }
212 #[track_caller]
213 pub const fn remove(&mut self, index: usize) -> Type {
214 assert!(index < self.length, "tried to remove out of bounds");
215 let value = unsafe {self.data.get_unchecked(index).assume_init_read()};
216 let pointer = unsafe {self.data.as_mut_ptr().add(index)};
217 unsafe {copy(
218 pointer.add(1),
219 pointer,
220 self.length - index - 1
221 )};
222 self.length -= 1;
223 return value;
224 }
225 #[track_caller]
226 pub const fn swap_remove(&mut self, index: usize) -> Type {
227 assert!(index <= self.length - 1, "tried to remove out of bounds");
228 let value = unsafe {self.data[index].assume_init_read()};
229 self.data.swap(index, self.length - 1);
230 self.length -= 1;
231 return value;
232 }
233 pub const fn retain(
234 &mut self,
235 mut closure: impl [const] FnMut(&mut Type) -> bool + [const] Destruct
236 ) -> () where Type: [const] Destruct {
237 let mut offset = 0;
238 for index in (0..self.length).const_into_iter() {
239 let mut item = unsafe {self.data[index].assume_init_read()};
240 if closure(&mut item) {
241 if offset == 0 {forget(item)} else {self.data[index - offset].write(item);}
242 } else {
243 drop(item);
244 offset += 1;
245 }
246 }
247 self.length -= offset;
248 }
249 pub const fn dedup(
250 &mut self
251 ) -> () where Type: [const] PartialEq<Type> + [const] Destruct {self.dedup_by_key_with(
252 const |element| element as *const Type,
253 const |first, second| unsafe {first.as_ref_unchecked() == second.as_ref_unchecked()}
254 )}
255 pub const fn dedup_with(
256 &mut self,
257 mut decider: impl [const] FnMut(&mut Type, &mut Type) -> bool + [const] Destruct
258 ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
259 const |element| element as *mut Type,
260 const |first, second| decider(
261 unsafe {first.as_mut()}.unwrap(),
262 unsafe {second.as_mut()}.unwrap()
263 )
264 )}
265 pub const fn dedup_by_key<
266 'valid,
267 Key: 'valid + [const] PartialEq<Key> + [const] Destruct
268 >(
269 &'valid mut self,
270 transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct
271 ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
272 transformation,
273 const |first, second| first == second
274 )}
275 pub const fn dedup_by_key_with<'valid, Key: 'valid + [const] Destruct>(
276 &'valid mut self,
277 mut transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct,
278 mut decider: impl [const] FnMut(&mut Key, &mut Key) -> bool + [const] Destruct
279 ) -> () where Type: [const] Destruct {
280 if self.length == 0 {return}
281 let mut offset = 0;
282 let mut previous = transformation(unsafe {self.data[0].assume_init_mut()});
283 for index in (1..self.length).const_into_iter() {
284 let current = unsafe {self.data[index].assume_init_mut()};
285 let mut key = transformation(current);
286 if decider(&mut previous, &mut key) {
287 drop(key);
288 unsafe {(current as *mut Type).drop_in_place()};
289 offset += 1;
290 } else {
291 previous = key;
292 if offset != 0 {
293 let value = unsafe {(current as *mut Type).read()};
294 self.data[index - offset].write(value);
295 }
296 }
297 }
298 self.length -= offset;
299 }
300 pub const fn drain(
301 &mut self,
302 range: impl [const] RangeBounds<usize> + [const] Destruct
303 ) -> Self {
304 let start = match range.start_bound() {
305 Bound::Excluded(_) => unsafe {unreachable_unchecked()},
306 Bound::Included(bound) => {
307 assert!(*bound < self.length);
308 *bound
309 },
310 Bound::Unbounded => 0
311 };
312 let end = match range.end_bound() {
313 Bound::Excluded(bound) => {
314 assert!(*bound <= self.length);
315 *bound
316 },
317 Bound::Included(bound) => {
318 assert!(*bound < self.length);
319 *bound + 1
320 },
321 Bound::Unbounded => self.length
322 };
323 let mut additional = MaybeUninit::<[Type; N]>::uninit().transpose();
324 let array = match end - start {
325 0 => Array {
326 length: 0,
327 data: additional
328 },
329 1 => {
330 additional[0].write(self.remove(start));
331 Array {
332 length: 1,
333 data: additional
334 }
335 },
336 amount => {
337 for index in (start..end).const_into_iter() {
338 additional[index - start].write(unsafe {
339 self.data[index].assume_init_read()
340 });
341 }
342 for index in (end..self.length).const_into_iter() {
343 self.data[index - end + start].write(unsafe {
344 self.data[index].assume_init_read()
345 });
346 }
347 self.length -= end - start;
348 Array {
349 length: amount,
350 data: additional
351 }
352 }
353 };
354 return array;
355 }
356}
357
358const impl<Type: [const] Destruct, const N: usize> Drop for Array<Type, N> {
360 fn drop(&mut self) {self.clear()}
361}
362
363impl<Type: Debug, const N: usize> Debug for Array<Type, N> {
365 fn fmt(&self, formatter: &mut Formatter<'_>) -> Format {
366 return self.as_ref().fmt(formatter);
367 }
368}
369
370impl<Type, const N: usize> Extend<Type> for Array<Type, N> {
372 fn extend<T: IntoIterator<Item = Type>>(&mut self, iter: T) {
373 iter.into_iter().for_each(|item| self.push(item));
374 }
375}
376
377const impl<Type: [const] Clone, const N: usize> Clone for Array<Type, N> {
379 fn clone(&self) -> Self {return Array {
380 length: self.length,
381 data: arrayfn(const |index| if index >= self.length {MaybeUninit::uninit()} else {
382 MaybeUninit::new(unsafe {self.data[index].assume_init_ref()}.clone())
383 })
384 }}
385}
386
387const impl<Type, const N: usize> Default for Array<Type, N> {
389 fn default() -> Self {return Self {
390 data: MaybeUninit::uninit().transpose(),
391 length: 0
392 }}
393}