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            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| {
254            unsafe {first.as_ref()}.unwrap() == unsafe {second.as_ref()}.unwrap()
255        }
256    )}
257    pub const fn dedup_with(
258        &mut self,
259        mut decider: impl [const] FnMut(&mut Type, &mut Type) -> bool + [const] Destruct
260    ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
261        const |element| element as *mut Type, 
262        const |first, second| decider(
263            unsafe {first.as_mut()}.unwrap(), 
264            unsafe {second.as_mut()}.unwrap()
265        )
266    )}
267    pub const fn dedup_by_key<
268        'valid, 
269        Key: 'valid + [const] PartialEq<Key> + [const] Destruct
270    >(
271        &'valid mut self,
272        transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct
273    ) -> () where Type: [const] Destruct {self.dedup_by_key_with(
274        transformation, 
275        const |first, second| first == second
276    )}
277    pub const fn dedup_by_key_with<'valid, Key: 'valid + [const] Destruct>(
278        &'valid mut self, 
279        mut transformation: impl [const] FnMut(&mut Type) -> Key + [const] Destruct,
280        mut decider: impl [const] FnMut(&mut Key, &mut Key) -> bool + [const] Destruct
281    ) -> () where Type: [const] Destruct {
282        if self.length == 0 {return}
283        let mut offset = 0;
284        let mut previous = transformation(unsafe {self.data[0].assume_init_mut()});
285        for index in (1..self.length).const_into_iter() {
286            let current = unsafe {self.data[index].assume_init_mut()};
287            let mut key = transformation(current);
288            if decider(&mut previous, &mut key) {
289                unsafe {(current as *mut Type).drop_in_place()};
290                drop(key);
291                offset += 1;
292            } else {
293                previous = key;
294                if offset != 0 {
295                    let value = unsafe {(current as *mut Type).read()};
296                    self.data[index - offset].write(value);
297                }
298            }
299        }
300        self.length -= offset;
301    }
302    pub const fn drain(
303        &mut self, 
304        range: impl [const] RangeBounds<usize> + [const] Destruct
305    ) -> Self {
306        let start = match range.start_bound() {
307            Bound::Excluded(_) => unsafe {unreachable_unchecked()},
308            Bound::Included(bound) => {
309                assert!(*bound < self.length);
310                *bound
311            },
312            Bound::Unbounded => 0
313        };
314        let end = match range.end_bound() {
315            Bound::Excluded(bound) => {
316                assert!(*bound <= self.length);
317                *bound
318            },
319            Bound::Included(bound) => {
320                assert!(*bound < self.length);
321                *bound + 1
322            },
323            Bound::Unbounded => self.length
324        };
325        let mut additional = MaybeUninit::<[Type; N]>::uninit().transpose();
326        let array = match end - start {
327            0 => Array {
328                length: 0,
329                data: additional
330            },
331            1 => {
332                additional[0].write(self.remove(start));
333                Array {
334                    length: 1,
335                    data: additional
336                }
337            },
338            amount => {
339                for index in (start..end).const_into_iter() {
340                    additional[index - start].write(unsafe {
341                        self.data[index].assume_init_read()
342                    });
343                }
344                for index in (end..self.length).const_into_iter() {
345                    self.data[index - end + start].write(unsafe {
346                        self.data[index].assume_init_read()
347                    });
348                }
349                self.length -= end - start;
350                Array {
351                    length: amount,
352                    data: additional
353                }
354            }
355        };
356        return array;
357    }
358}
359
360//> ARRAY -> DROP
361const impl<Type: [const] Destruct, const N: usize> Drop for Array<Type, N> {
362    fn drop(&mut self) {self.clear()}
363}
364
365//> ARRAY -> DEBUG
366impl<Type: Debug, const N: usize> Debug for Array<Type, N> {
367    fn fmt(&self, formatter: &mut Formatter<'_>) -> Format {
368        return self.as_ref().fmt(formatter);
369    }
370}
371
372//> ARRAY -> EXTEND
373impl<Type, const N: usize> Extend<Type> for Array<Type, N> {
374    fn extend<T: IntoIterator<Item = Type>>(&mut self, iter: T) {
375        iter.into_iter().for_each(|item| self.push(item));
376    }
377}
378
379//> ARRAY -> CLONE
380const impl<Type: [const] Clone, const N: usize> Clone for Array<Type, N> {
381    fn clone(&self) -> Self {return Array {
382        length: self.length,
383        data: arrayfn(const |index| if index >= self.length {MaybeUninit::uninit()} else {
384            MaybeUninit::new(unsafe {self.data[index].assume_init_ref().clone()})
385        })
386    }}
387}
388
389//> ARRAY -> DEFAULT
390const impl<Type, const N: usize> Default for Array<Type, N> {
391    fn default() -> Self {return Self {
392        data: MaybeUninit::uninit().transpose(),
393        length: 0
394    }}
395}