| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 1 | use std::collections::HashSet; |
| 2 | use std::hash::Hash; |
| 3 | use std::slice; |
| 4 | |
| David Tolnay | 45f3f89 | 2020-08-29 19:19:56 -0700 | [diff] [blame] | 5 | pub struct OrderedSet<T> { |
| 6 | set: HashSet<T>, |
| 7 | vec: Vec<T>, |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 8 | } |
| 9 | |
| David Tolnay | 45f3f89 | 2020-08-29 19:19:56 -0700 | [diff] [blame] | 10 | impl<'a, T> OrderedSet<&'a T> |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 11 | where |
| 12 | T: Hash + Eq, |
| 13 | { |
| 14 | pub fn new() -> Self { |
| 15 | OrderedSet { |
| 16 | set: HashSet::new(), |
| 17 | vec: Vec::new(), |
| 18 | } |
| 19 | } |
| 20 | |
| David Tolnay | ab91445 | 2020-05-04 00:21:37 -0700 | [diff] [blame] | 21 | pub fn insert(&mut self, value: &'a T) -> bool { |
| 22 | let new = self.set.insert(value); |
| 23 | if new { |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 24 | self.vec.push(value); |
| 25 | } |
| David Tolnay | ab91445 | 2020-05-04 00:21:37 -0700 | [diff] [blame] | 26 | new |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | pub fn contains(&self, value: &T) -> bool { |
| 30 | self.set.contains(value) |
| 31 | } |
| 32 | } |
| 33 | |
| David Tolnay | 45f3f89 | 2020-08-29 19:19:56 -0700 | [diff] [blame] | 34 | impl<'s, 'a, T> IntoIterator for &'s OrderedSet<&'a T> { |
| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame] | 35 | type Item = &'a T; |
| 36 | type IntoIter = Iter<'s, 'a, T>; |
| 37 | fn into_iter(self) -> Self::IntoIter { |
| 38 | Iter(self.vec.iter()) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub struct Iter<'s, 'a, T>(slice::Iter<'s, &'a T>); |
| 43 | |
| 44 | impl<'s, 'a, T> Iterator for Iter<'s, 'a, T> { |
| 45 | type Item = &'a T; |
| 46 | fn next(&mut self) -> Option<Self::Item> { |
| 47 | self.0.next().copied() |
| 48 | } |
| 49 | } |