1use std::collections::{BTreeMap, BTreeSet, btree_map, btree_set};
11use std::fmt;
12use std::{iter, mem, slice};
13
14pub const FEW: usize = 16;
17
18fn shrink<T>(vector: &mut Vec<T>) {
22 if vector.capacity() >= 2 * vector.len().max(1) {
23 vector.shrink_to_fit();
24 }
25}
26
27#[derive(Clone)]
29pub struct SmallSet<T>(SetRepr<T>);
30
31#[derive(Clone)]
32enum SetRepr<T> {
33 Few(Vec<T>),
35 Many(BTreeSet<T>),
36}
37
38impl<T> SmallSet<T> {
39 #[must_use]
41 pub const fn new() -> Self {
42 Self(SetRepr::Few(Vec::new()))
43 }
44
45 #[must_use]
47 pub fn len(&self) -> usize {
48 match &self.0 {
49 SetRepr::Few(few) => few.len(),
50 SetRepr::Many(many) => many.len(),
51 }
52 }
53
54 #[must_use]
56 pub fn is_empty(&self) -> bool {
57 self.len() == 0
58 }
59
60 #[must_use]
62 pub fn iter(&self) -> SetIter<'_, T> {
63 match &self.0 {
64 SetRepr::Few(few) => SetIter(SetIterRepr::Few(few.iter())),
65 SetRepr::Many(many) => SetIter(SetIterRepr::Many(many.iter())),
66 }
67 }
68
69 #[must_use]
71 pub fn first(&self) -> Option<&T>
72 where
73 T: Ord,
74 {
75 match &self.0 {
76 SetRepr::Few(few) => few.first(),
77 SetRepr::Many(many) => many.first(),
78 }
79 }
80}
81
82impl<T: Ord> SmallSet<T> {
83 #[must_use]
85 pub fn contains(&self, value: &T) -> bool {
86 match &self.0 {
87 SetRepr::Few(few) => few.binary_search(value).is_ok(),
88 SetRepr::Many(many) => many.contains(value),
89 }
90 }
91
92 pub fn insert(&mut self, value: T) -> bool {
94 match &mut self.0 {
95 SetRepr::Few(few) => match few.binary_search(&value) {
96 Ok(_) => false,
97 Err(_) if few.len() == FEW => {
98 let mut many: BTreeSet<T> = mem::take(few).into_iter().collect();
99 many.insert(value);
100 self.0 = SetRepr::Many(many);
101 true
102 }
103 Err(index) => {
104 few.reserve_exact(1);
105 few.insert(index, value);
106 true
107 }
108 },
109 SetRepr::Many(many) => many.insert(value),
110 }
111 }
112
113 pub fn remove(&mut self, value: &T) -> bool {
115 match &mut self.0 {
116 SetRepr::Few(few) => match few.binary_search(value) {
117 Ok(index) => {
118 few.remove(index);
119 shrink(few);
120 true
121 }
122 Err(_) => false,
123 },
124 SetRepr::Many(many) => {
125 let removed = many.remove(value);
126 if many.len() <= FEW / 2 {
127 let few: Vec<T> = mem::take(many).into_iter().collect();
128 self.0 = SetRepr::Few(few);
129 }
130 removed
131 }
132 }
133 }
134}
135
136impl<T> Default for SmallSet<T> {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142impl<T: fmt::Debug> fmt::Debug for SmallSet<T> {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 f.debug_set().entries(self.iter()).finish()
145 }
146}
147
148impl<T: PartialEq> PartialEq for SmallSet<T> {
149 fn eq(&self, other: &Self) -> bool {
150 self.len() == other.len() && self.iter().eq(other.iter())
151 }
152}
153
154impl<T: Eq> Eq for SmallSet<T> {}
155
156impl<T: Ord> FromIterator<T> for SmallSet<T> {
157 fn from_iter<I: IntoIterator<Item = T>>(elements: I) -> Self {
158 let mut set = Self::new();
159 set.extend(elements);
160 set
161 }
162}
163
164impl<T: Ord, const N: usize> From<[T; N]> for SmallSet<T> {
165 fn from(elements: [T; N]) -> Self {
166 elements.into_iter().collect()
167 }
168}
169
170impl<T: Ord> Extend<T> for SmallSet<T> {
171 fn extend<I: IntoIterator<Item = T>>(&mut self, elements: I) {
172 for element in elements {
173 self.insert(element);
174 }
175 }
176}
177
178impl<'a, T> IntoIterator for &'a SmallSet<T> {
179 type Item = &'a T;
180 type IntoIter = SetIter<'a, T>;
181
182 fn into_iter(self) -> Self::IntoIter {
183 self.iter()
184 }
185}
186
187#[derive(Clone, Debug)]
189pub struct SetIter<'a, T>(SetIterRepr<'a, T>);
190
191#[derive(Clone, Debug)]
192enum SetIterRepr<'a, T> {
193 Few(slice::Iter<'a, T>),
194 Many(btree_set::Iter<'a, T>),
195}
196
197impl<'a, T> Iterator for SetIter<'a, T> {
198 type Item = &'a T;
199
200 fn next(&mut self) -> Option<Self::Item> {
201 match &mut self.0 {
202 SetIterRepr::Few(few) => few.next(),
203 SetIterRepr::Many(many) => many.next(),
204 }
205 }
206
207 fn size_hint(&self) -> (usize, Option<usize>) {
208 match &self.0 {
209 SetIterRepr::Few(few) => few.size_hint(),
210 SetIterRepr::Many(many) => many.size_hint(),
211 }
212 }
213}
214
215impl<T> DoubleEndedIterator for SetIter<'_, T> {
216 fn next_back(&mut self) -> Option<Self::Item> {
217 match &mut self.0 {
218 SetIterRepr::Few(few) => few.next_back(),
219 SetIterRepr::Many(many) => many.next_back(),
220 }
221 }
222}
223
224impl<T> ExactSizeIterator for SetIter<'_, T> {}
225
226impl<T> iter::FusedIterator for SetIter<'_, T> {}
227
228#[derive(Clone)]
230pub struct SmallMap<K, V>(MapRepr<K, V>);
231
232#[derive(Clone)]
233enum MapRepr<K, V> {
234 Few(Vec<(K, V)>),
236 Many(BTreeMap<K, V>),
237}
238
239impl<K, V> SmallMap<K, V> {
240 #[must_use]
242 pub const fn new() -> Self {
243 Self(MapRepr::Few(Vec::new()))
244 }
245
246 #[must_use]
248 pub fn len(&self) -> usize {
249 match &self.0 {
250 MapRepr::Few(few) => few.len(),
251 MapRepr::Many(many) => many.len(),
252 }
253 }
254
255 #[must_use]
257 pub fn is_empty(&self) -> bool {
258 self.len() == 0
259 }
260
261 #[must_use]
263 pub fn iter(&self) -> MapIter<'_, K, V> {
264 match &self.0 {
265 MapRepr::Few(few) => MapIter(MapIterRepr::Few(few.iter())),
266 MapRepr::Many(many) => MapIter(MapIterRepr::Many(many.iter())),
267 }
268 }
269
270 pub fn keys(&self) -> impl DoubleEndedIterator<Item = &K> + ExactSizeIterator {
272 self.iter().map(|(key, _)| key)
273 }
274
275 pub fn values(&self) -> impl DoubleEndedIterator<Item = &V> + ExactSizeIterator {
277 self.iter().map(|(_, value)| value)
278 }
279}
280
281impl<K: Ord, V> SmallMap<K, V> {
282 #[must_use]
284 pub fn get(&self, key: &K) -> Option<&V> {
285 match &self.0 {
286 MapRepr::Few(few) => few
287 .binary_search_by(|(held, _)| held.cmp(key))
288 .ok()
289 .map(|index| &few[index].1),
290 MapRepr::Many(many) => many.get(key),
291 }
292 }
293
294 #[must_use]
296 pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
297 match &mut self.0 {
298 MapRepr::Few(few) => few
299 .binary_search_by(|(held, _)| held.cmp(key))
300 .ok()
301 .map(|index| &mut few[index].1),
302 MapRepr::Many(many) => many.get_mut(key),
303 }
304 }
305
306 #[must_use]
308 pub fn contains_key(&self, key: &K) -> bool {
309 self.get(key).is_some()
310 }
311
312 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
314 match &mut self.0 {
315 MapRepr::Few(few) => match few.binary_search_by(|(held, _)| held.cmp(&key)) {
316 Ok(index) => Some(mem::replace(&mut few[index].1, value)),
317 Err(_) if few.len() == FEW => {
318 let mut many: BTreeMap<K, V> = mem::take(few).into_iter().collect();
319 many.insert(key, value);
320 self.0 = MapRepr::Many(many);
321 None
322 }
323 Err(index) => {
324 few.reserve_exact(1);
325 few.insert(index, (key, value));
326 None
327 }
328 },
329 MapRepr::Many(many) => many.insert(key, value),
330 }
331 }
332
333 pub fn get_or_insert_with(&mut self, key: K, default: impl FnOnce() -> V) -> &mut V {
335 let position = match &self.0 {
338 MapRepr::Few(few) => {
339 let position = few.binary_search_by(|(held, _)| held.cmp(&key));
340 (position.is_ok() || few.len() < FEW).then_some(position)
341 }
342 MapRepr::Many(_) => None,
343 };
344 if position.is_none()
345 && let MapRepr::Few(few) = &mut self.0
346 {
347 self.0 = MapRepr::Many(mem::take(few).into_iter().collect());
348 }
349 match (&mut self.0, position) {
350 (MapRepr::Few(few), Some(Ok(index))) => &mut few[index].1,
351 (MapRepr::Few(few), Some(Err(index))) => {
352 few.reserve_exact(1);
353 few.insert(index, (key, default()));
354 &mut few[index].1
355 }
356 (MapRepr::Many(many), _) => many.entry(key).or_insert_with(default),
357 (MapRepr::Few(_), None) => unreachable!("a full vector became a tree"),
358 }
359 }
360
361 pub fn remove(&mut self, key: &K) -> Option<V> {
363 match &mut self.0 {
364 MapRepr::Few(few) => {
365 let index = few.binary_search_by(|(held, _)| held.cmp(key)).ok()?;
366 let (_, value) = few.remove(index);
367 shrink(few);
368 Some(value)
369 }
370 MapRepr::Many(many) => {
371 let removed = many.remove(key);
372 if many.len() <= FEW / 2 {
373 let few: Vec<(K, V)> = mem::take(many).into_iter().collect();
374 self.0 = MapRepr::Few(few);
375 }
376 removed
377 }
378 }
379 }
380}
381
382impl<K, V> Default for SmallMap<K, V> {
383 fn default() -> Self {
384 Self::new()
385 }
386}
387
388impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for SmallMap<K, V> {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 f.debug_map().entries(self.iter()).finish()
391 }
392}
393
394impl<K: PartialEq, V: PartialEq> PartialEq for SmallMap<K, V> {
395 fn eq(&self, other: &Self) -> bool {
396 self.len() == other.len() && self.iter().eq(other.iter())
397 }
398}
399
400impl<K: Eq, V: Eq> Eq for SmallMap<K, V> {}
401
402impl<'a, K, V> IntoIterator for &'a SmallMap<K, V> {
403 type Item = (&'a K, &'a V);
404 type IntoIter = MapIter<'a, K, V>;
405
406 fn into_iter(self) -> Self::IntoIter {
407 self.iter()
408 }
409}
410
411#[derive(Clone, Debug)]
413pub struct MapIter<'a, K, V>(MapIterRepr<'a, K, V>);
414
415#[derive(Clone, Debug)]
416enum MapIterRepr<'a, K, V> {
417 Few(slice::Iter<'a, (K, V)>),
418 Many(btree_map::Iter<'a, K, V>),
419}
420
421impl<'a, K, V> Iterator for MapIter<'a, K, V> {
422 type Item = (&'a K, &'a V);
423
424 fn next(&mut self) -> Option<Self::Item> {
425 match &mut self.0 {
426 MapIterRepr::Few(few) => few.next().map(|(key, value)| (key, value)),
427 MapIterRepr::Many(many) => many.next(),
428 }
429 }
430
431 fn size_hint(&self) -> (usize, Option<usize>) {
432 match &self.0 {
433 MapIterRepr::Few(few) => few.size_hint(),
434 MapIterRepr::Many(many) => many.size_hint(),
435 }
436 }
437}
438
439impl<K, V> DoubleEndedIterator for MapIter<'_, K, V> {
440 fn next_back(&mut self) -> Option<Self::Item> {
441 match &mut self.0 {
442 MapIterRepr::Few(few) => few.next_back().map(|(key, value)| (key, value)),
443 MapIterRepr::Many(many) => many.next_back(),
444 }
445 }
446}
447
448impl<K, V> ExactSizeIterator for MapIter<'_, K, V> {}
449
450impl<K, V> iter::FusedIterator for MapIter<'_, K, V> {}