1use core::borrow::Borrow;
3use core::iter::IntoIterator;
4use core::fmt;
5use ordered_map;
6use {PhfHash, OrderedMap};
7
8pub struct OrderedSet<T: 'static> {
19 #[doc(hidden)]
20 pub map: OrderedMap<T, ()>,
21}
22
23impl<T> fmt::Debug for OrderedSet<T> where T: fmt::Debug {
24 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
25 fmt.debug_set().entries(self).finish()
26 }
27}
28
29impl<T> OrderedSet<T> {
30 pub fn len(&self) -> usize {
32 self.map.len()
33 }
34
35 pub fn is_empty(&self) -> bool {
37 self.len() == 0
38 }
39
40 pub fn get_key<U: ?Sized>(&self, key: &U) -> Option<&T>
45 where U: Eq + PhfHash,
46 T: Borrow<U>
47 {
48 self.map.get_key(key)
49 }
50
51 pub fn get_index<U: ?Sized>(&self, key: &U) -> Option<usize>
54 where U: Eq + PhfHash,
55 T: Borrow<U>
56 {
57 self.map.get_index(key)
58 }
59
60 pub fn index(&self, index: usize) -> Option<&T> {
63 self.map.index(index).map(|(k, &())| k)
64 }
65
66 pub fn contains<U: ?Sized>(&self, value: &U) -> bool
68 where U: Eq + PhfHash,
69 T: Borrow<U>
70 {
71 self.map.contains_key(value)
72 }
73
74 pub fn iter<'a>(&'a self) -> Iter<'a, T> {
78 Iter { iter: self.map.keys() }
79 }
80}
81
82impl<T> OrderedSet<T> where T: Eq + PhfHash {
83 #[inline]
85 pub fn is_disjoint(&self, other: &OrderedSet<T>) -> bool {
86 !self.iter().any(|value| other.contains(value))
87 }
88
89 #[inline]
91 pub fn is_subset(&self, other: &OrderedSet<T>) -> bool {
92 self.iter().all(|value| other.contains(value))
93 }
94
95 #[inline]
97 pub fn is_superset(&self, other: &OrderedSet<T>) -> bool {
98 other.is_subset(self)
99 }
100}
101
102impl<'a, T> IntoIterator for &'a OrderedSet<T> {
103 type Item = &'a T;
104 type IntoIter = Iter<'a, T>;
105
106 fn into_iter(self) -> Iter<'a, T> {
107 self.iter()
108 }
109}
110
111pub struct Iter<'a, T: 'a> {
113 iter: ordered_map::Keys<'a, T, ()>,
114}
115
116impl<'a, T> Iterator for Iter<'a, T> {
117 type Item = &'a T;
118
119 #[inline]
120 fn next(&mut self) -> Option<&'a T> {
121 self.iter.next()
122 }
123
124 #[inline]
125 fn size_hint(&self) -> (usize, Option<usize>) {
126 self.iter.size_hint()
127 }
128}
129
130impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
131 #[inline]
132 fn next_back(&mut self) -> Option<&'a T> {
133 self.iter.next_back()
134 }
135}
136
137impl<'a, T> ExactSizeIterator for Iter<'a, T> {}