fixed_map/set/storage/
option.rs1use core::iter;
2use core::mem;
3use core::option;
4
5use crate::set::SetStorage;
6use crate::Key;
7
8type Iter<'a, T> = iter::Chain<
9 iter::Map<<<T as Key>::SetStorage as SetStorage<T>>::Iter<'a>, fn(T) -> Option<T>>,
10 option::IntoIter<Option<T>>,
11>;
12type IntoIter<T> = iter::Chain<
13 iter::Map<<<T as Key>::SetStorage as SetStorage<T>>::IntoIter, fn(T) -> Option<T>>,
14 option::IntoIter<Option<T>>,
15>;
16
17pub struct OptionSetStorage<T>
50where
51 T: Key,
52{
53 some: T::SetStorage,
54 none: bool,
55}
56
57impl<T> Clone for OptionSetStorage<T>
58where
59 T: Key,
60 T::SetStorage: Clone,
61{
62 #[inline]
63 fn clone(&self) -> Self {
64 Self {
65 some: self.some.clone(),
66 none: self.none,
67 }
68 }
69}
70
71impl<T> Copy for OptionSetStorage<T>
72where
73 T: Key,
74 T::SetStorage: Copy,
75{
76}
77
78impl<T> PartialEq for OptionSetStorage<T>
79where
80 T: Key,
81 T::SetStorage: PartialEq,
82{
83 #[inline]
84 fn eq(&self, other: &Self) -> bool {
85 self.none == other.none && self.some == other.some
86 }
87}
88
89impl<T> Eq for OptionSetStorage<T>
90where
91 T: Key,
92 T::SetStorage: Eq,
93{
94}
95
96impl<T> SetStorage<Option<T>> for OptionSetStorage<T>
97where
98 T: Key,
99{
100 type Iter<'this>
101 = Iter<'this, T>
102 where
103 T: 'this;
104 type IntoIter = IntoIter<T>;
105
106 #[inline]
107 fn empty() -> Self {
108 Self {
109 some: T::SetStorage::empty(),
110 none: false,
111 }
112 }
113
114 #[inline]
115 fn len(&self) -> usize {
116 self.some.len() + usize::from(self.none)
117 }
118
119 #[inline]
120 fn is_empty(&self) -> bool {
121 self.some.is_empty() && self.none
122 }
123
124 #[inline]
125 fn insert(&mut self, value: Option<T>) -> bool {
126 match value {
127 Some(value) => self.some.insert(value),
128 None => mem::replace(&mut self.none, true),
129 }
130 }
131
132 #[inline]
133 fn contains(&self, value: Option<T>) -> bool {
134 match value {
135 Some(key) => self.some.contains(key),
136 None => self.none,
137 }
138 }
139
140 #[inline]
141 fn remove(&mut self, key: Option<T>) -> bool {
142 match key {
143 Some(key) => self.some.remove(key),
144 None => mem::replace(&mut self.none, false),
145 }
146 }
147
148 #[inline]
149 fn retain<F>(&mut self, mut func: F)
150 where
151 F: FnMut(Option<T>) -> bool,
152 {
153 self.some.retain(|value| func(Some(value)));
154
155 if self.none {
156 self.none = func(None);
157 }
158 }
159
160 #[inline]
161 fn clear(&mut self) {
162 self.some.clear();
163 self.none = false;
164 }
165
166 #[inline]
167 fn iter(&self) -> Self::Iter<'_> {
168 let map: fn(_) -> _ = Some;
169 self.some
170 .iter()
171 .map(map)
172 .chain(self.none.then_some(None::<T>))
173 }
174
175 #[inline]
176 fn into_iter(self) -> Self::IntoIter {
177 let map: fn(_) -> _ = Some;
178 self.some
179 .into_iter()
180 .map(map)
181 .chain(self.none.then_some(None::<T>))
182 }
183}