blob: 688d1c0e25f41a2845338c17bd3b7ae8c59b56cc [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use std::collections::HashSet;
2use std::hash::Hash;
3use std::slice;
4
5pub struct OrderedSet<'a, T> {
6 set: HashSet<&'a T>,
7 vec: Vec<&'a T>,
8}
9
10impl<'a, T> OrderedSet<'a, T>
11where
12 T: Hash + Eq,
13{
14 pub fn new() -> Self {
15 OrderedSet {
16 set: HashSet::new(),
17 vec: Vec::new(),
18 }
19 }
20
David Tolnayab914452020-05-04 00:21:37 -070021 pub fn insert(&mut self, value: &'a T) -> bool {
22 let new = self.set.insert(value);
23 if new {
David Tolnay7db73692019-10-20 14:51:12 -040024 self.vec.push(value);
25 }
David Tolnayab914452020-05-04 00:21:37 -070026 new
David Tolnay7db73692019-10-20 14:51:12 -040027 }
28
29 pub fn contains(&self, value: &T) -> bool {
30 self.set.contains(value)
31 }
32}
33
34impl<'s, 'a, T> IntoIterator for &'s OrderedSet<'a, T> {
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
42pub struct Iter<'s, 'a, T>(slice::Iter<'s, &'a T>);
43
44impl<'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}