bumpish 0.2.0

A set of collections using bump allocations
Documentation
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
mod iter;

pub use iter::{Drain, IntoIter, Iter};

use crate::map::BumpMap;
use core::fmt::{self, Debug};
use core::hash::{BuildHasher, Hash};
use core::iter::Iterator;
use equivalent::Equivalent;

#[cfg(feature = "std")]
use std::hash::RandomState;

#[cfg(feature = "std")]
pub struct BumpSet<T, S = RandomState> {
    map: BumpMap<T, (), S>,
}

#[cfg(not(feature = "std"))]
pub struct BumpSet<T, S> {
    map: BumpMap<T, (), S>,
}

#[cfg(feature = "std")]
impl<T> BumpSet<T, RandomState> {
    /// Creates an empty `BumpSet`.
    ///
    /// The method will not allocate until it is first inserted into.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    /// let set: BumpSet<i32> = BumpSet::new();
    /// ```
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Default::default()
    }

    /// Creates an empty `BumpSet` with at least the specified capacity.
    ///
    /// The hash set will be able to hold at least `capacity` elements without
    /// reallocating. This method is allowed to allocate for more elements than
    /// `capacity`. If `capacity` is zero, the hash set will not allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    /// let set: BumpSet<i32> = BumpSet::with_capacity(10);
    /// assert!(set.capacity() >= 10);
    /// ```
    #[inline]
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self::with_capacity_and_hasher(capacity, Default::default())
    }
}

impl<T, S> BumpSet<T, S> {
    /// Creates a new empty hash set which will use the given hasher to hash
    /// keys.
    ///
    /// The hash set does not allocate until the first element is inserted.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    /// use std::hash::RandomState;
    ///
    /// let s = RandomState::new();
    /// let mut set = BumpSet::with_hasher(s);
    /// set.insert(2);
    /// ```
    pub const fn with_hasher(hasher: S) -> Self {
        Self {
            map: BumpMap::with_hasher(hasher),
        }
    }

    /// Creates an empty `BumpSet` with at least the specified capacity, using
    /// `hasher` to hash the keys.
    ///
    /// The hash set will be able to hold at least `capacity` elements without
    /// reallocating. This method is allowed to allocate for more elements than
    /// `capacity`. If `capacity` is zero, the hash set will not allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    /// use std::hash::RandomState;
    ///
    /// let s = RandomState::new();
    /// let mut set = BumpSet::with_capacity_and_hasher(10, s);
    /// set.insert(1);
    /// ```
    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
        Self {
            map: BumpMap::with_capacity_and_hasher(capacity, hash_builder),
        }
    }

    /// Returns the number of elements the set can hold without reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let set: BumpSet<i32> = BumpSet::with_capacity(100);
    /// assert!(set.capacity() >= 100);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.map.capacity()
    }

    /// Returns the number of elements in the set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut v = BumpSet::new();
    /// assert_eq!(v.len(), 0);
    /// v.insert(1);
    /// assert_eq!(v.len(), 1);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the set contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut v = BumpSet::new();
    /// assert!(v.is_empty());
    /// v.insert(1);
    /// assert!(!v.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Clears the set, removing all values. Can keep some of the allocated
    /// memory for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut v = BumpSet::new();
    /// v.insert(1);
    /// v.clear();
    /// assert!(v.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.map.clear();
    }

    /// An iterator visiting all elements in insertion order.
    ///
    /// The iterator element type is `&'a T`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut set = BumpSet::new();
    /// set.insert("a");
    /// set.insert("b");
    ///
    /// // Will print in an arbitrary order.
    /// for x in set.iter() {
    ///     println!("{x}");
    /// }
    /// ```
    pub fn iter(&self) -> Iter<'_, T> {
        Iter::new(self.map.iter())
    }
}

impl<T: Eq, S> BumpSet<T, S> {
    /// Clears the set, returning all elements as an iterator. Keeps some of the
    /// allocated memory for reuse.
    ///
    /// If the returned iterator is dropped before being fully consumed, it
    /// drops the remaining elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    ///
    /// let mut set = BumpSet::from([1, 2, 3]);
    /// assert!(!set.is_empty());
    ///
    /// // print 1, 2, 3 in an arbitrary order
    /// for i in set.drain() {
    ///     println!("{i}");
    /// }
    ///
    /// assert!(set.is_empty());
    /// ```
    pub fn drain(&mut self) -> Drain<'_, T> {
        Drain::new(self.map.drain())
    }
}

impl<T, S> BumpSet<T, S>
where
    S: BuildHasher,
{
    /// Returns a reference to the set's [`BuildHasher`].
    ///
    /// [`BuildHasher`]: https://doc.rust-lang.org/beta/std/hash/trait.BuildHasher.html
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    /// use std::hash::RandomState;
    ///
    /// let hasher = RandomState::new();
    /// let set: BumpSet<i32> = BumpSet::with_hasher(hasher);
    /// let hasher: &RandomState = set.hasher();
    /// ```
    #[inline]
    pub fn hasher(&self) -> &S {
        self.map.hasher()
    }

    /// Returns `true` if the set contains a value.
    ///
    /// The `Q` type **must** hash like `K`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let set = BumpSet::from([1, 2, 3]);
    /// assert_eq!(set.contains(&1), true);
    /// assert_eq!(set.contains(&4), false);
    /// ```
    pub fn contains<Q>(&self, value: &Q) -> bool
    where
        Q: ?Sized + Hash + Equivalent<T>,
    {
        self.map.contains_key(value)
    }

    /// Returns a reference to the value in the set, if any, that is equal to
    /// the given value.
    ///
    /// The `Q` type **must** hash like `K`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let set = BumpSet::from([1, 2, 3]);
    /// assert_eq!(set.get(&2), Some(&2));
    /// assert_eq!(set.get(&4), None);
    /// ```
    pub fn get<Q>(&self, value: &Q) -> Option<&T>
    where
        Q: ?Sized + Hash + Equivalent<T>,
    {
        self.map.get_key_value(value).map(|(k, _)| k)
    }
}

impl<T, S> BumpSet<T, S>
where
    T: Hash + Eq,
    S: BuildHasher,
{
    /// 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,
    ///   and the set is not modified: original value is not replaced,
    ///   and the value passed as argument is dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut set = BumpSet::new();
    ///
    /// assert_eq!(set.insert(2), Some(&2));
    /// assert_eq!(set.insert(2), None);
    /// assert_eq!(set.len(), 1);
    /// ```
    #[inline]
    pub fn insert(&self, value: T) -> Option<&T> {
        self.map.insert_full(value, ()).map(|(old, _)| old)
    }

    /// Adds a value to the set, replacing the existing value, if any, that is
    /// equal to the given one. Returns the replaced value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bumpish::BumpSet;
    /// let mut set = BumpSet::new();
    /// assert_eq!(set.replace(Vec::<u32>::new()), None);
    ///
    /// let old_vec = set.replace(Vec::with_capacity(10)).unwrap();
    /// assert_eq!(old_vec.capacity(), 0);
    ///
    /// let new_vec = set.into_iter().next().unwrap();
    /// assert!(new_vec.capacity() >= 10);
    /// ```
    pub fn replace(&mut self, value: T) -> Option<T> {
        self.map.replace_full(value, ()).map(|(old, _)| old)
    }
}

impl<T, S> core::clone::Clone for BumpSet<T, S>
where
    T: Clone,
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            map: self.map.clone(),
        }
    }
}

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

impl<T, S> Default for BumpSet<T, S>
where
    S: Default,
{
    /// Creates an empty `BumpSet<K, V, S>`, with the `Default` value for the
    /// hasher.
    #[inline]
    fn default() -> Self {
        Self::with_hasher(Default::default())
    }
}

impl<T, S> PartialEq for BumpSet<T, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }
        self.iter().all(|k| other.contains(k))
    }
}

#[cfg(feature = "std")]
impl<T, const N: usize> From<[T; N]> for BumpSet<T, RandomState>
where
    T: Eq + Hash,
{
    /// Converts a `[T; N]` into a `BumpSet<T>`.
    ///
    /// If the array contains any equal values,
    /// all but one will be dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use bumpish::BumpSet;
    ///
    /// let set1 = BumpSet::from([1, 2, 3, 4]);
    /// let set2: BumpSet<_> = [1, 2, 3, 4].into();
    /// assert_eq!(set1, set2);
    /// ```
    fn from(arr: [T; N]) -> Self {
        let mut set = Self::with_capacity(N);
        set.extend(arr);
        set
    }
}

impl<T, S> FromIterator<T> for BumpSet<T, S>
where
    T: Eq + Hash,
    S: BuildHasher + Default,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut set = BumpSet::with_hasher(Default::default());
        set.extend(iter);
        set
    }
}

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

impl<'a, T, S> Extend<&'a T> for BumpSet<T, S>
where
    T: 'a + Eq + Hash + Copy,
    S: BuildHasher,
{
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.extend(iter.into_iter().copied());
    }
}

impl<'a, T, S> core::iter::IntoIterator for &'a BumpSet<T, S> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<T, S> core::iter::IntoIterator for BumpSet<T, S> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self.map.into_iter())
    }
}