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 #[inline]
48 fn next(&mut self) -> Option<Self::Item> {
49 return if self.length - self.reduced - self.index == 0 {None} else {
50 let value = unsafe {(self.data.as_ptr() as *const Type).add(self.index).read()};
51 self.index += 1;
52 Some(value)
53 }
54 }
55 #[inline]
56 fn size_hint(&self) -> (usize, Option<usize>) {return (self.length - self.index, Some(self.length - self.index))}
57}
58
59impl<Type, const N: usize> ExactSizeIterator for Iterable<Type, N> {}
61
62const impl<Type, const N: usize> DoubleEndedIterator for Iterable<Type, N> {
64 #[inline]
65 fn next_back(&mut self) -> Option<Self::Item> {
66 return if self.length - self.reduced - self.index == 0 {None} else {
67 let value = unsafe {(self.data.as_ptr() as *const Type).add(self.length - 1 - self.reduced).read()};
68 self.reduced += 1;
69 Some(value)
70 }
71 }
72}
73
74impl<Type, const N: usize> FusedIterator for Iterable<Type, N> {}
76
77unsafe impl<Type, const N: usize> TrustedLen for Iterable<Type, N> {}
79
80
81impl<Type, const N: usize> FromIterator<Type> for Array<Type, N> {
87 fn from_iter<T: IntoIterator<Item = Type>>(iter: T) -> Self {
88 let mut array = Self::new();
89 array.extend(iter);
90 return array;
91 }
92}
93
94const impl<Type, const N: usize> IntoIterator for Array<Type, N> {
96 type Item = Type;
97 type IntoIter = Iterable<Type, N>;
98 fn into_iter(self) -> Self::IntoIter {
99 let iterator = Self::IntoIter {
100 index: 0,
101 reduced: 0,
102 length: self.length,
103 data: unsafe {MaybeUninit::new(self.data.as_ptr().read())}
104 };
105 forget(self);
106 return iterator;
107 }
108}
109
110const impl<'valid, Type, const N: usize> IntoIterator for &'valid Array<Type, N> {
112 type Item = &'valid Type;
113 type IntoIter = Iter<'valid, Type>;
114 fn into_iter(self) -> Self::IntoIter {self.iter()}
115}
116
117const impl<'valid, Type, const N: usize> IntoIterator for &'valid mut Array<Type, N> {
119 type Item = &'valid mut Type;
120 type IntoIter = IterMut<'valid, Type>;
121 fn into_iter(self) -> Self::IntoIter {self.iter_mut()}
122}