libutils_array/
iterators.rs1use super::Array;
7
8use core::{
10 mem::MaybeUninit,
11 slice::{
12 Iter,
13 IterMut
14 },
15 iter::{
16 ExactSizeIterator,
17 DoubleEndedIterator,
18 FusedIterator,
19 TrustedLen
20 },
21 marker::Destruct
22};
23
24
25pub struct Iterable<Type, const N: usize> {
31 index: usize,
32 reduced: usize,
33 length: usize,
34 data: MaybeUninit<[Type; N]>
35}
36
37const impl<Type: [const] Destruct, const N: usize> Drop for Iterable<Type, N> {
39 fn drop(&mut self) {while let Some(value) = self.next() {drop(value)}}
40}
41
42const impl<Type, const N: usize> Iterator for Iterable<Type, N> {
44 type Item = Type;
45 fn next(&mut self) -> Option<Self::Item> {
46 return if self.length - self.reduced - self.index == 0 {None} else {
47 let value = unsafe {self.data.as_ptr().cast::<Type>().add(self.index).read()};
48 self.index += 1;
49 Some(value)
50 }
51 }
52 fn size_hint(&self) -> (usize, Option<usize>) {return (self.length - self.index, Some(self.length - self.index))}
53}
54
55impl<Type, const N: usize> ExactSizeIterator for Iterable<Type, N> {}
57
58const impl<Type, const N: usize> DoubleEndedIterator for Iterable<Type, N> {
60 fn next_back(&mut self) -> Option<Self::Item> {
61 return if self.length - self.reduced - self.index == 0 {None} else {
62 let value = unsafe {self.data.as_ptr().cast::<Type>().add(self.length - 1 - self.reduced).read()};
63 self.reduced += 1;
64 Some(value)
65 }
66 }
67}
68
69impl<Type, const N: usize> FusedIterator for Iterable<Type, N> {}
71
72unsafe impl<Type, const N: usize> TrustedLen for Iterable<Type, N> {}
74
75
76impl<Type, const N: usize> FromIterator<Type> for Array<Type, N> {
82 fn from_iter<T: IntoIterator<Item = Type>>(iter: T) -> Self {
83 let mut array = Self::new();
84 array.extend(iter);
85 return array;
86 }
87}
88
89const impl<Type, const N: usize> IntoIterator for Array<Type, N> {
91 type Item = Type;
92 type IntoIter = Iterable<Type, N>;
93 fn into_iter(self) -> Self::IntoIter {
94 let (length, data) = self.into();
95 let iterator = Self::IntoIter {
96 index: 0,
97 reduced: 0,
98 length: length,
99 data: data
100 };
101 return iterator;
102 }
103}
104
105const impl<'valid, Type, const N: usize> IntoIterator for &'valid Array<Type, N> {
107 type Item = &'valid Type;
108 type IntoIter = Iter<'valid, Type>;
109 fn into_iter(self) -> Self::IntoIter {self.iter()}
110}
111
112const impl<'valid, Type, const N: usize> IntoIterator for &'valid mut Array<Type, N> {
114 type Item = &'valid mut Type;
115 type IntoIter = IterMut<'valid, Type>;
116 fn into_iter(self) -> Self::IntoIter {self.iter_mut()}
117}