1use core::borrow::Borrow;
6use core::fmt;
7
8use kevy_hash::KevyHash;
9
10use crate::iter::Iter;
11use crate::map::KevyMap;
12
13#[derive(Clone)]
20pub struct KevySet<K>(KevyMap<K, ()>);
21
22impl<K> KevySet<K> {
23 pub fn new() -> Self {
25 Self(KevyMap::new())
26 }
27
28 pub fn with_capacity(cap_hint: usize) -> Self {
30 Self(KevyMap::with_capacity(cap_hint))
31 }
32
33 #[inline]
35 pub fn len(&self) -> usize {
36 self.0.len()
37 }
38 #[inline]
40 pub fn is_empty(&self) -> bool {
41 self.0.is_empty()
42 }
43 #[inline]
45 pub fn capacity(&self) -> usize {
46 self.0.capacity()
47 }
48 pub fn clear(&mut self) {
50 self.0.clear();
51 }
52
53 pub fn iter(&self) -> SetIter<'_, K> {
55 SetIter(self.0.iter())
56 }
57
58 pub fn iter_from_slot(&self, start: usize) -> impl Iterator<Item = &K> {
71 let cap = self.0.capacity();
72 let start = if cap == 0 { 0 } else { start % cap };
73 self.0
74 .iter_from_bucket(start)
75 .chain(self.0.iter().take(start))
76 .map(|(k, ())| k)
77 }
78
79 pub fn as_map(&self) -> &KevyMap<K, ()> {
81 &self.0
82 }
83}
84
85impl<K: KevyHash + Eq> KevySet<K> {
86 pub fn insert(&mut self, key: K) -> bool {
89 self.0.insert(key, ()).is_none()
90 }
91}
92
93impl<K> KevySet<K> {
94 pub fn contains<Q>(&self, key: &Q) -> bool
96 where
97 K: Borrow<Q>,
98 Q: KevyHash + Eq + ?Sized,
99 {
100 self.0.contains_key(key)
101 }
102
103 pub fn remove<Q>(&mut self, key: &Q) -> bool
105 where
106 K: Borrow<Q>,
107 Q: KevyHash + Eq + ?Sized,
108 {
109 self.0.remove(key).is_some()
110 }
111}
112
113impl<K> Default for KevySet<K> {
114 fn default() -> Self {
115 Self::new()
116 }
117}
118
119impl<K: fmt::Debug> fmt::Debug for KevySet<K> {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.debug_set().entries(self.iter()).finish()
122 }
123}
124
125pub struct SetIter<'a, K>(Iter<'a, K, ()>);
127
128impl<'a, K> Iterator for SetIter<'a, K> {
129 type Item = &'a K;
130 fn next(&mut self) -> Option<Self::Item> {
131 self.0.next().map(|(k, ())| k)
132 }
133}
134
135impl<'a, K> IntoIterator for &'a KevySet<K> {
136 type Item = &'a K;
137 type IntoIter = SetIter<'a, K>;
138 fn into_iter(self) -> Self::IntoIter {
139 self.iter()
140 }
141}
142
143impl<K: KevyHash + Eq> FromIterator<K> for KevySet<K> {
144 fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
145 let iter = iter.into_iter();
146 let mut s = match iter.size_hint() {
147 (lo, Some(hi)) if hi <= lo.saturating_mul(2) => Self::with_capacity(hi),
148 (lo, _) => Self::with_capacity(lo),
149 };
150 for k in iter {
151 s.insert(k);
152 }
153 s
154 }
155}
156
157impl<K: KevyHash + Eq> Extend<K> for KevySet<K> {
158 fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
159 for k in iter {
160 self.insert(k);
161 }
162 }
163}