1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::fmt;
use std::hash::Hash;
use std::iter::FromIterator;

use super::map::SsoHashMap;

/// Small-storage-optimized implementation of a set.
///
/// Stores elements in a small array up to a certain length
/// and switches to `HashSet` when that length is exceeded.
//
// FIXME: Implements subset of HashSet API.
//
// Missing HashSet API:
//   all hasher-related
//   try_reserve
//   shrink_to (unstable)
//   drain_filter (unstable)
//   replace
//   get_or_insert/get_or_insert_owned/get_or_insert_with (unstable)
//   difference/symmetric_difference/intersection/union
//   is_disjoint/is_subset/is_superset
//   PartialEq/Eq (requires SsoHashMap implementation)
//   BitOr/BitAnd/BitXor/Sub
#[derive(Clone)]
pub struct SsoHashSet<T> {
    map: SsoHashMap<T, ()>,
}

/// Adapter function used ot return
/// result if SsoHashMap functions into
/// result SsoHashSet should return.
#[inline(always)]
fn entry_to_key<K, V>((k, _v): (K, V)) -> K {
    k
}

impl<T> SsoHashSet<T> {
    /// Creates an empty `SsoHashSet`.
    #[inline]
    pub fn new() -> Self {
        Self { map: SsoHashMap::new() }
    }

    /// Creates an empty `SsoHashSet` with the specified capacity.
    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        Self { map: SsoHashMap::with_capacity(cap) }
    }

    /// Clears the set, removing all values.
    #[inline]
    pub fn clear(&mut self) {
        self.map.clear()
    }

    /// Returns the number of elements the set can hold without reallocating.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.map.capacity()
    }

    /// Returns the number of elements in the set.
    #[inline]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the set contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// An iterator visiting all elements in arbitrary order.
    /// The iterator element type is `&'a T`.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.into_iter()
    }

    /// Clears the set, returning all elements in an iterator.
    #[inline]
    pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ {
        self.map.drain().map(entry_to_key)
    }
}

impl<T: Eq + Hash> SsoHashSet<T> {
    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the `SsoHashSet`. The collection may reserve more space to avoid
    /// frequent reallocations.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.map.reserve(additional)
    }

    /// Shrinks the capacity of the set as much as possible. It will drop
    /// down as much as possible while maintaining the internal rules
    /// and possibly leaving some space in accordance with the resize policy.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.map.shrink_to_fit()
    }

    /// Retains only the elements specified by the predicate.
    #[inline]
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        self.map.retain(|k, _v| f(k))
    }

    /// Removes and returns the value in the set, if any, that is equal to the given one.
    #[inline]
    pub fn take(&mut self, value: &T) -> Option<T> {
        self.map.remove_entry(value).map(entry_to_key)
    }

    /// Returns a reference to the value in the set, if any, that is equal to the given value.
    #[inline]
    pub fn get(&self, value: &T) -> Option<&T> {
        self.map.get_key_value(value).map(entry_to_key)
    }

    /// Adds a value to the set.
    ///
    /// Returns whether the value was newly inserted. That is:
    ///
    /// - If the set did not previously contain this value, `true` is returned.
    /// - If the set already contained this value, `false` is returned.
    #[inline]
    pub fn insert(&mut self, elem: T) -> bool {
        self.map.insert(elem, ()).is_none()
    }

    /// Removes a value from the set. Returns whether the value was
    /// present in the set.
    #[inline]
    pub fn remove(&mut self, value: &T) -> bool {
        self.map.remove(value).is_some()
    }

    /// Returns `true` if the set contains a value.
    #[inline]
    pub fn contains(&self, value: &T) -> bool {
        self.map.contains_key(value)
    }
}

impl<T: Eq + Hash> FromIterator<T> for SsoHashSet<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> SsoHashSet<T> {
        let mut set: SsoHashSet<T> = Default::default();
        set.extend(iter);
        set
    }
}

impl<T> Default for SsoHashSet<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Eq + Hash> Extend<T> for SsoHashSet<T> {
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        for val in iter.into_iter() {
            self.insert(val);
        }
    }

    #[inline]
    fn extend_one(&mut self, item: T) {
        self.insert(item);
    }

    #[inline]
    fn extend_reserve(&mut self, additional: usize) {
        self.map.extend_reserve(additional)
    }
}

impl<'a, T> Extend<&'a T> for SsoHashSet<T>
where
    T: 'a + Eq + Hash + Copy,
{
    #[inline]
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.extend(iter.into_iter().cloned());
    }

    #[inline]
    fn extend_one(&mut self, &item: &'a T) {
        self.insert(item);
    }

    #[inline]
    fn extend_reserve(&mut self, additional: usize) {
        Extend::<T>::extend_reserve(self, additional)
    }
}

impl<T> IntoIterator for SsoHashSet<T> {
    type IntoIter = std::iter::Map<<SsoHashMap<T, ()> as IntoIterator>::IntoIter, fn((T, ())) -> T>;
    type Item = <Self::IntoIter as Iterator>::Item;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.map.into_iter().map(entry_to_key)
    }
}

impl<'a, T> IntoIterator for &'a SsoHashSet<T> {
    type IntoIter = std::iter::Map<
        <&'a SsoHashMap<T, ()> as IntoIterator>::IntoIter,
        fn((&'a T, &'a ())) -> &'a T,
    >;
    type Item = <Self::IntoIter as Iterator>::Item;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.map.iter().map(entry_to_key)
    }
}

impl<T> fmt::Debug for SsoHashSet<T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}