Skip to main content

stack_array/
lib.rs

1//^
2//^ HEAD
3//^
4
5//> HEAD -> NO_STD
6#![no_std]
7
8//> HEAD -> DOCS
9#![doc = include_str!("README.md")]
10
11//> HEAD -> LINTS
12#![allow(incomplete_features)]
13
14//> HEAD -> FEATURES
15#![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
36//> HEAD -> CRATES
37extern crate alloc;
38
39//> HEAD -> MODULES
40mod comparisons;
41mod conversions;
42mod errors;
43mod iterators;
44mod references;
45
46//> HEAD -> CORE
47use 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
69//> HEAD -> CONSTRANGEITER
70use constrangeiter::ConstIntoIterator;
71
72//> HEAD -> ERRORS
73pub use errors::{
74    CapacityExceeded,
75    UnmatchedCapacity
76};
77
78
79//^
80//^ ARRAY
81//^
82
83//> ARRAY -> STRUCT
84pub struct Array<Type, const N: usize> {
85    length: usize,
86    data: [MaybeUninit<Type>; N]
87}
88
89//> ARRAY -> IMPLEMENTATION
90impl<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            match (closure(&mut item), offset == 0) {
241                (true, true) => forget(item),
242                (true, false) => {self.data[index - offset].write(item);},
243                (false, _) => {
244                    drop(item);
245                    offset += 1;
246                }
247            }
248        }
249        self.length -= offset;
250    }
251    pub const fn dedup(
252        &mut self
253    ) -> () where Type: [const] PartialEq<Type> + [const] Destruct {self.dedup_by_key_with(
254        const |element| element as *const Type,
255        const |first, second| {
256            unsafe {first.as_ref()}.unwrap() == unsafe {second.as_ref()}.unwrap()
257        }
258    )}
259    pub const fn dedup_with(
260        &mut self,
261        mut decider: impl [const] FnMut(&mut Type, &mut Type) -> bool + [const] Destruct
262    ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
263        const |element| element as *mut Type, 
264        const |first, second| decider(
265            unsafe {first.as_mut()}.unwrap(), 
266            unsafe {second.as_mut()}.unwrap()
267        )
268    )}
269    pub const fn dedup_by_key<
270        'valid, 
271        Key: 'valid + [const] PartialEq<Key> + [const] Destruct
272    >(
273        &'valid mut self,
274        transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct
275    ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
276        transformation, 
277        const |first, second| first == second
278    )}
279    pub const fn dedup_by_key_with<'valid, Key: 'valid + [const] Destruct>(
280        &'valid mut self, 
281        mut transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct,
282        mut decider: impl [const] FnMut(&mut Key, &mut Key) -> bool + [const] Destruct
283    ) -> () where Type: [const] Destruct {
284        if self.length == 0 {return}
285        let mut offset = 0;
286        let mut previous = transformation(unsafe {self.data[0].assume_init_mut()});
287        for index in (1..self.length).const_into_iter() {
288            let current = unsafe {self.data[index].assume_init_mut()};
289            let mut key = transformation(current);
290            if decider(&mut previous, &mut key) {
291                unsafe {(current as *mut Type).drop_in_place()};
292                drop(key);
293                offset += 1;
294            } else {
295                previous = key;
296                if offset != 0 {
297                    let value = unsafe {(current as *mut Type).read()};
298                    self.data[index - offset].write(value);
299                }
300            }
301        }
302        self.length -= offset;
303    }
304    pub const fn drain(
305        &mut self, 
306        range: impl [const] RangeBounds<usize> + [const] Destruct
307    ) -> Self {
308        let start = match range.start_bound() {
309            Bound::Excluded(_) => unsafe {unreachable_unchecked()},
310            Bound::Included(bound) => {
311                assert!(*bound < self.length);
312                *bound
313            },
314            Bound::Unbounded => 0
315        };
316        let end = match range.end_bound() {
317            Bound::Excluded(bound) => {
318                assert!(*bound <= self.length);
319                *bound
320            },
321            Bound::Included(bound) => {
322                assert!(*bound < self.length);
323                *bound + 1
324            },
325            Bound::Unbounded => self.length
326        };
327        let mut additional = MaybeUninit::<[Type; N]>::uninit().transpose();
328        let array = match end - start {
329            0 => Array {
330                length: 0,
331                data: additional
332            },
333            1 => {
334                additional[0].write(self.remove(start));
335                Array {
336                    length: 1,
337                    data: additional
338                }
339            },
340            amount => {
341                for index in (start..end).const_into_iter() {
342                    additional[index - start].write(unsafe {
343                        self.data[index].assume_init_read()
344                    });
345                }
346                for index in (end..self.length).const_into_iter() {
347                    self.data[index - end + start].write(unsafe {
348                        self.data[index].assume_init_read()
349                    });
350                }
351                self.length -= end - start;
352                Array {
353                    length: amount,
354                    data: additional
355                }
356            }
357        };
358        return array;
359    }
360}
361
362//> ARRAY -> DROP
363const impl<Type: [const] Destruct, const N: usize> Drop for Array<Type, N> {
364    fn drop(&mut self) {self.clear()}
365}
366
367//> ARRAY -> DEBUG
368impl<Type: Debug, const N: usize> Debug for Array<Type, N> {
369    fn fmt(&self, formatter: &mut Formatter<'_>) -> Format {
370        return self.as_ref().fmt(formatter);
371    }
372}
373
374//> ARRAY -> EXTEND
375impl<Type, const N: usize> Extend<Type> for Array<Type, N> {
376    fn extend<T: IntoIterator<Item = Type>>(&mut self, iter: T) {
377        iter.into_iter().for_each(|item| self.push(item));
378    }
379}
380
381//> ARRAY -> CLONE
382const impl<Type: [const] Clone, const N: usize> Clone for Array<Type, N> {
383    fn clone(&self) -> Self {return Array {
384        length: self.length,
385        data: arrayfn(const |index| if index >= self.length {MaybeUninit::uninit()} else {
386            MaybeUninit::new(unsafe {self.data[index].assume_init_ref().clone()})
387        })
388    }}
389}
390
391//> ARRAY -> DEFAULT
392const impl<Type, const N: usize> Default for Array<Type, N> {
393    fn default() -> Self {return Self {
394        data: MaybeUninit::uninit().transpose(),
395        length: 0
396    }}
397}