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