1use core::fmt;
3use core::iter::FusedIterator;
4use core::iter::IntoIterator;
5
6use phf_shared::{PhfBorrow, PhfHash};
7
8use crate::{map, Map};
9
10pub struct Set<T: 'static> {
18 #[doc(hidden)]
19 pub map: Map<T, ()>,
20}
21
22impl<T> fmt::Debug for Set<T>
23where
24 T: fmt::Debug,
25{
26 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
27 fmt.debug_set().entries(self).finish()
28 }
29}
30
31impl<T> PartialEq for Set<T>
32where
33 T: PartialEq,
34{
35 fn eq(&self, other: &Self) -> bool {
36 self.map == other.map
37 }
38}
39
40impl<T> Eq for Set<T> where T: Eq {}
41
42impl<T> Set<T> {
43 #[inline]
45 pub const fn len(&self) -> usize {
46 self.map.len()
47 }
48
49 #[inline]
51 pub const fn is_empty(&self) -> bool {
52 self.len() == 0
53 }
54
55 pub fn get_key<U: ?Sized>(&self, key: &U) -> Option<&T>
60 where
61 U: Eq + PhfHash,
62 T: PhfBorrow<U>,
63 {
64 self.map.get_key(key)
65 }
66
67 pub fn contains<U: ?Sized>(&self, value: &U) -> bool
69 where
70 U: Eq + PhfHash,
71 T: PhfBorrow<U>,
72 {
73 self.map.contains_key(value)
74 }
75
76 pub fn iter(&self) -> Iter<'_, T> {
80 Iter {
81 iter: self.map.keys(),
82 }
83 }
84}
85
86impl<T> Set<T>
87where
88 T: Eq + PhfHash + PhfBorrow<T>,
89{
90 pub fn is_disjoint(&self, other: &Set<T>) -> bool {
92 !self.iter().any(|value| other.contains(value))
93 }
94
95 pub fn is_subset(&self, other: &Set<T>) -> bool {
97 self.iter().all(|value| other.contains(value))
98 }
99
100 pub fn is_superset(&self, other: &Set<T>) -> bool {
102 other.is_subset(self)
103 }
104}
105
106impl<'a, T> IntoIterator for &'a Set<T> {
107 type Item = &'a T;
108 type IntoIter = Iter<'a, T>;
109
110 fn into_iter(self) -> Iter<'a, T> {
111 self.iter()
112 }
113}
114
115pub struct Iter<'a, T: 'static> {
117 iter: map::Keys<'a, T, ()>,
118}
119
120impl<'a, T> Clone for Iter<'a, T> {
121 #[inline]
122 fn clone(&self) -> Self {
123 Self {
124 iter: self.iter.clone(),
125 }
126 }
127}
128
129impl<'a, T> fmt::Debug for Iter<'a, T>
130where
131 T: fmt::Debug,
132{
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 f.debug_list().entries(self.clone()).finish()
135 }
136}
137
138impl<'a, T> Iterator for Iter<'a, T> {
139 type Item = &'a T;
140
141 fn next(&mut self) -> Option<&'a T> {
142 self.iter.next()
143 }
144
145 fn size_hint(&self) -> (usize, Option<usize>) {
146 self.iter.size_hint()
147 }
148}
149
150impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
151 fn next_back(&mut self) -> Option<&'a T> {
152 self.iter.next_back()
153 }
154}
155
156impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
157
158impl<'a, T> FusedIterator for Iter<'a, T> {}