Skip to main content

libutils_array/
iterators.rs

1//^
2//^ HEAD
3//^
4
5//> HEAD -> SUPER
6use super::Array;
7
8//> HEAD -> CORE
9use core::{
10    mem::{
11        MaybeUninit,
12        forget
13    },
14    slice::{
15        Iter,
16        IterMut
17    }
18};
19
20
21//^
22//^ ITERATORS
23//^
24
25//> ITERATORS -> ITERABLE
26pub struct Iterable<Type, const N: usize> {
27    index: usize,
28    length: usize,
29    data: MaybeUninit<[Type; N]>
30} impl<Type, const N: usize> Drop for Iterable<Type, N> {
31    fn drop(&mut self) {while let Some(value) = self.next() {drop(value)}}
32}
33
34//> ITERATORS -> ITERATIONS
35const impl<Type, const N: usize> Iterator for Iterable<Type, N> {
36    type Item = Type;
37    #[inline]
38    fn next(&mut self) -> Option<Self::Item> {
39        return if self.index >= self.length {None} else {
40            let value = unsafe {(self.data.as_ptr() as *const Type).add(self.index).read()};
41            self.index += 1;
42            Some(value)
43        }
44    }
45}
46
47//> ITERATORS -> FROM
48impl<Type, const N: usize> FromIterator<Type> for Array<Type, N> {
49    fn from_iter<T: IntoIterator<Item = Type>>(iter: T) -> Self {
50        let mut array = Self::new();
51        array.extend(iter);
52        return array;
53    }
54}
55
56//> ITERATORS -> INTO ITERATOR
57const impl<Type, const N: usize> IntoIterator for Array<Type, N> {
58    type Item = Type;
59    type IntoIter = Iterable<Type, N>;
60    fn into_iter(self) -> Self::IntoIter {
61        let iterator = Self::IntoIter {
62            index: 0,
63            length: self.length,
64            data: unsafe {MaybeUninit::new(self.data.as_ptr().read())}
65        };
66        forget(self);
67        return iterator;
68    }
69}
70
71//> ITERATORS -> BORROWED
72const impl<'valid, Type, const N: usize> IntoIterator for &'valid Array<Type, N> {
73    type Item = &'valid Type;
74    type IntoIter = Iter<'valid, Type>;
75    fn into_iter(self) -> Self::IntoIter {self.iter()}
76}
77
78//> ITERATORS -> BORROWED MUTABLY
79const impl<'valid, Type, const N: usize> IntoIterator for &'valid mut Array<Type, N> {
80    type Item = &'valid mut Type;
81    type IntoIter = IterMut<'valid, Type>;
82    fn into_iter(self) -> Self::IntoIter {self.iter_mut()}
83}