1use std::marker::PhantomData;
2use std::slice;
3
4use try_from::TryFrom;
5
6pub struct Iter<'a, Key, Value: 'a> {
7 entries: slice::Iter<'a, Option<Value>>,
8 index: usize,
9 _pd: PhantomData<Key>,
10}
11
12impl<'a, Key, Value: 'a> Iter<'a, Key, Value> {
13 pub fn new(slice: &'a [Option<Value>]) -> Self {
14 Iter {
15 entries: slice.iter(),
16 index: 0,
17 _pd: PhantomData,
18 }
19 }
20}
21
22impl<'a, Key, Value> Iterator for Iter<'a, Key, Value>
23where
24 Key: TryFrom<usize>,
25{
26 type Item = (Key, &'a Value);
27
28 fn next(&mut self) -> Option<(Key, &'a Value)> {
29 while let Some(opt) = self.entries.next() {
30 let key = Key::try_from(self.index).ok().unwrap();
31 self.index += 1;
32
33 if let Some(value) = opt.as_ref() {
34 return Some((key, value));
35 }
36 }
37
38 None
39 }
40}
41
42pub struct IterMut<'a, Key, Value: 'a> {
43 entries: slice::IterMut<'a, Option<Value>>,
44 index: usize,
45 _pd: PhantomData<Key>,
46}
47
48impl<'a, Key, Value: 'a> IterMut<'a, Key, Value> {
49 pub fn new(slice: &'a mut [Option<Value>]) -> Self {
50 IterMut {
51 entries: slice.iter_mut(),
52 index: 0,
53 _pd: PhantomData,
54 }
55 }
56}
57
58impl<'a, Key, Value> Iterator for IterMut<'a, Key, Value>
59where
60 Key: TryFrom<usize>,
61{
62 type Item = (Key, &'a mut Value);
63
64 fn next(&mut self) -> Option<(Key, &'a mut Value)> {
65 while let Some(opt) = self.entries.next() {
66 let key = Key::try_from(self.index).ok().unwrap();
67 self.index += 1;
68
69 if let Some(value) = opt.as_mut() {
70 return Some((key, value));
71 }
72 }
73
74 None
75 }
76}
77
78pub struct Keys<'a, Key, Value: 'a> {
79 entries: slice::Iter<'a, Option<Value>>,
80 index: usize,
81 _pd: PhantomData<Key>,
82}
83
84impl<'a, Key, Value: 'a> Keys<'a, Key, Value> {
85 pub fn new(slice: &'a [Option<Value>]) -> Self {
86 Keys {
87 entries: slice.iter(),
88 index: 0,
89 _pd: PhantomData,
90 }
91 }
92}
93
94impl<'a, Key, Value> Iterator for Keys<'a, Key, Value>
95where
96 Key: TryFrom<usize>,
97{
98 type Item = Key;
99
100 fn next(&mut self) -> Option<Key> {
101 while let Some(opt) = self.entries.next() {
102 let key = Key::try_from(self.index).ok().unwrap();
103 self.index += 1;
104
105 if opt.is_some() {
106 return Some(key);
107 }
108 }
109
110 None
111 }
112}
113
114pub struct Values<'a, Value: 'a> {
115 entries: slice::Iter<'a, Option<Value>>,
116}
117
118impl<'a, Value: 'a> Values<'a, Value> {
119 pub fn new(slice: &'a [Option<Value>]) -> Self {
120 Values { entries: slice.iter() }
121 }
122}
123
124impl<'a, Value> Iterator for Values<'a, Value> {
125 type Item = &'a Value;
126
127 fn next(&mut self) -> Option<&'a Value> {
128 while let Some(opt) = self.entries.next() {
129 if let Some(value) = opt.as_ref() {
130 return Some(value);
131 }
132 }
133
134 None
135 }
136}