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> Set<T> {
32 #[inline]
34 pub const fn len(&self) -> usize {
35 self.map.len()
36 }
37
38 #[inline]
40 pub const fn is_empty(&self) -> bool {
41 self.len() == 0
42 }
43
44 pub fn get_key<U: ?Sized>(&self, key: &U) -> Option<&T>
49 where
50 U: Eq + PhfHash,
51 T: PhfBorrow<U>,
52 {
53 self.map.get_key(key)
54 }
55
56 pub fn contains<U: ?Sized>(&self, value: &U) -> bool
58 where
59 U: Eq + PhfHash,
60 T: PhfBorrow<U>,
61 {
62 self.map.contains_key(value)
63 }
64
65 pub fn iter(&self) -> Iter<'_, T> {
69 Iter {
70 iter: self.map.keys(),
71 }
72 }
73}
74
75impl<T> Set<T>
76where
77 T: Eq + PhfHash + PhfBorrow<T>,
78{
79 pub fn is_disjoint(&self, other: &Set<T>) -> bool {
81 !self.iter().any(|value| other.contains(value))
82 }
83
84 pub fn is_subset(&self, other: &Set<T>) -> bool {
86 self.iter().all(|value| other.contains(value))
87 }
88
89 pub fn is_superset(&self, other: &Set<T>) -> bool {
91 other.is_subset(self)
92 }
93}
94
95impl<'a, T> IntoIterator for &'a Set<T> {
96 type Item = &'a T;
97 type IntoIter = Iter<'a, T>;
98
99 fn into_iter(self) -> Iter<'a, T> {
100 self.iter()
101 }
102}
103
104pub struct Iter<'a, T: 'static> {
106 iter: map::Keys<'a, T, ()>,
107}
108
109impl<'a, T> Clone for Iter<'a, T> {
110 #[inline]
111 fn clone(&self) -> Self {
112 Self {
113 iter: self.iter.clone(),
114 }
115 }
116}
117
118impl<'a, T> fmt::Debug for Iter<'a, T>
119where
120 T: fmt::Debug,
121{
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 f.debug_list().entries(self.clone()).finish()
124 }
125}
126
127impl<'a, T> Iterator for Iter<'a, T> {
128 type Item = &'a T;
129
130 fn next(&mut self) -> Option<&'a T> {
131 self.iter.next()
132 }
133
134 fn size_hint(&self) -> (usize, Option<usize>) {
135 self.iter.size_hint()
136 }
137}
138
139impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
140 fn next_back(&mut self) -> Option<&'a T> {
141 self.iter.next_back()
142 }
143}
144
145impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
146
147impl<'a, T> FusedIterator for Iter<'a, T> {}