blob: b553169f3e0863ac6a7a1ab8d5d2e36356cec8ee [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use std::collections::HashSet;
David Tolnay599fad82020-10-03 19:42:16 -07002use std::fmt::{self, Debug};
David Tolnay7db73692019-10-20 14:51:12 -04003use std::hash::Hash;
4use std::slice;
5
David Tolnay45f3f892020-08-29 19:19:56 -07006pub struct OrderedSet<T> {
7 set: HashSet<T>,
8 vec: Vec<T>,
David Tolnay7db73692019-10-20 14:51:12 -04009}
10
David Tolnay45f3f892020-08-29 19:19:56 -070011impl<'a, T> OrderedSet<&'a T>
David Tolnay7db73692019-10-20 14:51:12 -040012where
13 T: Hash + Eq,
14{
15 pub fn new() -> Self {
16 OrderedSet {
17 set: HashSet::new(),
18 vec: Vec::new(),
19 }
20 }
21
David Tolnayab914452020-05-04 00:21:37 -070022 pub fn insert(&mut self, value: &'a T) -> bool {
23 let new = self.set.insert(value);
24 if new {
David Tolnay7db73692019-10-20 14:51:12 -040025 self.vec.push(value);
26 }
David Tolnayab914452020-05-04 00:21:37 -070027 new
David Tolnay7db73692019-10-20 14:51:12 -040028 }
29
30 pub fn contains(&self, value: &T) -> bool {
31 self.set.contains(value)
32 }
33}
34
David Tolnay45f3f892020-08-29 19:19:56 -070035impl<'s, 'a, T> IntoIterator for &'s OrderedSet<&'a T> {
David Tolnay7db73692019-10-20 14:51:12 -040036 type Item = &'a T;
37 type IntoIter = Iter<'s, 'a, T>;
38 fn into_iter(self) -> Self::IntoIter {
39 Iter(self.vec.iter())
40 }
41}
42
43pub struct Iter<'s, 'a, T>(slice::Iter<'s, &'a T>);
44
45impl<'s, 'a, T> Iterator for Iter<'s, 'a, T> {
46 type Item = &'a T;
47 fn next(&mut self) -> Option<Self::Item> {
48 self.0.next().copied()
49 }
50}
David Tolnay599fad82020-10-03 19:42:16 -070051
52impl<'a, T> Debug for OrderedSet<&'a T>
53where
54 T: Debug,
55{
56 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
57 formatter.debug_set().entries(self).finish()
58 }
59}