vecmap/
set.rs

1//! `VecSet` is a vector-based set implementation which retains the order of inserted elements.
2
3mod impls;
4mod iter;
5#[cfg(feature = "serde")]
6mod serde;
7
8use super::{Entries, Slot, TryReserveError, VecMap};
9use alloc::vec::Vec;
10use core::borrow::Borrow;
11use core::cmp::Ordering;
12use core::ops::RangeBounds;
13use core::ptr;
14
15pub use self::iter::*;
16
17/// A vector-based set implementation which retains the order of inserted elements.
18///
19/// Internally it is represented as a `Vec<T>` to support keys that are neither `Hash` nor `Ord`.
20#[derive(Clone, Debug)]
21pub struct VecSet<T> {
22    base: VecMap<T, ()>,
23}
24
25impl<T> VecSet<T> {
26    /// Create a new set. (Does not allocate.)
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// use vecmap::VecSet;
32    ///
33    /// let mut set: VecSet<&str> = VecSet::new();
34    /// ```
35    pub const fn new() -> Self {
36        VecSet {
37            base: VecMap::new(),
38        }
39    }
40
41    /// Create a new set with capacity for `capacity` key-value pairs. (Does not allocate if
42    /// `capacity` is zero.)
43    ///
44    /// # Examples
45    ///
46    /// ```
47    /// use vecmap::VecSet;
48    ///
49    /// let mut set: VecSet<&str> = VecSet::with_capacity(10);
50    /// assert_eq!(set.len(), 0);
51    /// assert!(set.capacity() >= 10);
52    /// ```
53    pub fn with_capacity(capacity: usize) -> Self {
54        VecSet {
55            base: VecMap::with_capacity(capacity),
56        }
57    }
58
59    /// Returns the number of elements the set can hold without reallocating.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use vecmap::VecSet;
65    ///
66    /// let mut set: VecSet<&str> = VecSet::with_capacity(10);
67    /// assert_eq!(set.capacity(), 10);
68    /// ```
69    pub fn capacity(&self) -> usize {
70        self.base.capacity()
71    }
72
73    /// Returns the number of elements in the set, also referred to as its 'length'.
74    ///
75    /// # Examples
76    ///
77    /// ```
78    /// use vecmap::VecSet;
79    ///
80    /// let mut a = VecSet::new();
81    /// assert_eq!(a.len(), 0);
82    /// a.insert(1);
83    /// assert_eq!(a.len(), 1);
84    /// ```
85    pub fn len(&self) -> usize {
86        self.base.len()
87    }
88
89    /// Returns `true` if the set contains no elements.
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use vecmap::VecSet;
95    ///
96    /// let mut a = VecSet::new();
97    /// assert!(a.is_empty());
98    /// a.insert(1);
99    /// assert!(!a.is_empty());
100    /// ```
101    pub fn is_empty(&self) -> bool {
102        self.base.is_empty()
103    }
104
105    /// Clears the set, removing all elements.
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// use vecmap::VecSet;
111    ///
112    /// let mut a = VecSet::new();
113    /// a.insert(1);
114    /// a.clear();
115    /// assert!(a.is_empty());
116    /// ```
117    pub fn clear(&mut self) {
118        self.base.clear();
119    }
120
121    /// Shortens the set, keeping the first `len` elements and dropping the rest.
122    ///
123    /// If `len` is greater than the set's current length, this has no effect.
124    ///
125    /// # Examples
126    ///
127    /// Truncating a four element set to two elements:
128    ///
129    /// ```
130    /// use vecmap::VecSet;
131    ///
132    /// let mut set = VecSet::from(["a", "b", "c", "d"]);
133    /// set.truncate(2);
134    /// assert_eq!(set, VecSet::from(["a", "b"]));
135    /// ```
136    ///
137    /// No truncation occurs when `len` is greater than the set's current length:
138    ///
139    /// ```
140    /// use vecmap::VecSet;
141    ///
142    /// let mut set = VecSet::from(["a", "b", "c", "d"]);
143    /// set.truncate(8);
144    /// assert_eq!(set, VecSet::from(["a", "b", "c", "d"]));
145    /// ```
146    pub fn truncate(&mut self, len: usize) {
147        self.base.truncate(len);
148    }
149
150    /// Reverses the order of entries in the set, in place.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use vecmap::VecSet;
156    ///
157    /// let mut set = VecSet::from_iter(["a", "b", "c"]);
158    /// set.reverse();
159    /// assert_eq!(set, VecSet::from_iter(["c", "b", "a"]));
160    /// ```
161    pub fn reverse(&mut self) {
162        self.base.reverse();
163    }
164
165    /// Reserves capacity for at least `additional` more elements to be inserted in the given
166    /// `VecSet<T>`. The collection may reserve more space to speculatively avoid frequent
167    /// reallocations. After calling `reserve`, capacity will be greater than or equal to
168    /// `self.len() + additional`. Does nothing if capacity is already sufficient.
169    ///
170    /// # Panics
171    ///
172    /// Panics if the new capacity exceeds `isize::MAX` bytes.
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use vecmap::VecSet;
178    ///
179    /// let mut set = VecSet::from_iter(["a"]);
180    /// set.reserve(10);
181    /// assert!(set.capacity() >= 11);
182    /// ```
183    pub fn reserve(&mut self, additional: usize) {
184        self.base.reserve(additional);
185    }
186
187    /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
188    /// given `VecSet<T>`. Unlike [`reserve`], this will not deliberately over-allocate to
189    /// speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be
190    /// greater than or equal to `self.len() + additional`. Does nothing if the capacity is already
191    /// sufficient.
192    ///
193    /// Note that the allocator may give the collection more space than it requests. Therefore,
194    /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
195    /// insertions are expected.
196    ///
197    /// [`reserve`]: VecSet::reserve
198    ///
199    /// # Panics
200    ///
201    /// Panics if the new capacity exceeds `isize::MAX` bytes.
202    ///
203    /// # Examples
204    ///
205    /// ```
206    /// use vecmap::VecSet;
207    ///
208    /// let mut set = VecSet::from_iter(["a"]);
209    /// set.reserve(10);
210    /// assert!(set.capacity() >= 11);
211    /// ```
212    pub fn reserve_exact(&mut self, additional: usize) {
213        self.base.reserve_exact(additional);
214    }
215
216    /// Tries to reserve capacity for at least `additional` more elements to be inserted in the
217    /// given `VecSet<T>`. The collection may reserve more space to speculatively avoid frequent
218    /// reallocations. After calling `try_reserve`, capacity will be greater than or equal to
219    /// `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already
220    /// sufficient. This method preserves the contents even if an error occurs.
221    ///
222    /// # Errors
223    ///
224    /// If the capacity overflows, or the allocator reports a failure, then an error
225    /// is returned.
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use vecmap::{TryReserveError, VecSet};
231    ///
232    /// fn process_data(data: &[u32]) -> Result<VecSet<u32>, TryReserveError> {
233    ///     let mut output = VecSet::new();
234    ///
235    ///     // Pre-reserve the memory, exiting if we can't
236    ///     output.try_reserve(data.len())?;
237    ///
238    ///     // Now we know this can't OOM in the middle of our complex work
239    ///     output.extend(data.iter().map(|&v| {
240    ///         v * 2 + 5 // very complicated
241    ///     }));
242    ///
243    ///     Ok(output)
244    /// }
245    /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing?");
246    /// ```
247    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
248        self.base.try_reserve(additional)
249    }
250
251    /// Tries to reserve the minimum capacity for at least `additional` elements to be inserted in
252    /// the given `VecSet<T>`. Unlike [`try_reserve`], this will not deliberately over-allocate
253    /// to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity
254    /// will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does
255    /// nothing if the capacity is already sufficient.
256    ///
257    /// Note that the allocator may give the collection more space than it requests. Therefore,
258    /// capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`] if future
259    /// insertions are expected.
260    ///
261    /// [`try_reserve`]: VecSet::try_reserve
262    ///
263    /// # Errors
264    ///
265    /// If the capacity overflows, or the allocator reports a failure, then an error is returned.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use vecmap::{TryReserveError, VecSet};
271    ///
272    /// fn process_data(data: &[u32]) -> Result<VecSet<u32>, TryReserveError> {
273    ///     let mut output = VecSet::new();
274    ///
275    ///     // Pre-reserve the memory, exiting if we can't
276    ///     output.try_reserve_exact(data.len())?;
277    ///
278    ///     // Now we know this can't OOM in the middle of our complex work
279    ///     output.extend(data.iter().map(|&v| {
280    ///         v * 2 + 5 // very complicated
281    ///     }));
282    ///
283    ///     Ok(output)
284    /// }
285    /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing?");
286    /// ```
287    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
288        self.base.try_reserve_exact(additional)
289    }
290
291    /// Retains only the elements specified by the predicate.
292    ///
293    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use vecmap::VecSet;
299    ///
300    /// let mut set: VecSet<i32> = VecSet::from([0, 1, 2, 3, 4, 5, 6, 7]);
301    /// set.retain(|&e| e % 2 == 0);
302    /// assert_eq!(set.len(), 4);
303    /// ```
304    pub fn retain<F>(&mut self, mut f: F)
305    where
306        F: FnMut(&T) -> bool,
307    {
308        self.base.retain(|k, ()| f(k));
309    }
310
311    /// Shrinks the capacity of the set as much as possible. It will drop down as much as possible
312    /// while maintaining the internal rules and possibly leaving some space in accordance with the
313    /// resize policy.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use vecmap::VecSet;
319    ///
320    /// let mut set: VecSet<i32> = VecSet::with_capacity(100);
321    /// set.insert(1);
322    /// set.insert(2);
323    /// assert!(set.capacity() >= 100);
324    /// set.shrink_to_fit();
325    /// assert!(set.capacity() >= 2);
326    /// ```
327    pub fn shrink_to_fit(&mut self) {
328        self.base.shrink_to_fit();
329    }
330
331    /// Shrinks the capacity of the set with a lower limit. It will drop down no lower than the
332    /// supplied limit while maintaining the internal rules and possibly leaving some space in
333    /// accordance with the resize policy.
334    ///
335    /// If the current capacity is less than the lower limit, this is a no-op.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use vecmap::VecSet;
341    ///
342    /// let mut set: VecSet<i32> = VecSet::with_capacity(100);
343    /// set.insert(1);
344    /// set.insert(2);
345    /// assert!(set.capacity() >= 100);
346    /// set.shrink_to(10);
347    /// assert!(set.capacity() >= 10);
348    /// set.shrink_to(0);
349    /// assert!(set.capacity() >= 2);
350    /// ```
351    pub fn shrink_to(&mut self, min_capacity: usize) {
352        self.base.shrink_to(min_capacity);
353    }
354
355    /// Splits the set into two at the given index.
356    ///
357    /// Returns a newly allocated set containing the elements in the range `[at, len)`. After the
358    /// call, the original set will be left containing the elements `[0, at)` with its previous
359    /// capacity unchanged.
360    ///
361    /// # Panics
362    ///
363    /// Panics if `at > len`.
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// use vecmap::VecSet;
369    ///
370    /// let mut set = VecSet::from(["a", "b", "c"]);
371    /// let set2 = set.split_off(1);
372    /// assert_eq!(set, VecSet::from(["a"]));
373    /// assert_eq!(set2, VecSet::from(["b", "c"]));
374    /// ```
375    pub fn split_off(&mut self, at: usize) -> VecSet<T> {
376        VecSet {
377            base: self.base.split_off(at),
378        }
379    }
380
381    /// Search over a sorted set for a value.
382    ///
383    /// Returns the position where that key is present, or the position where it can be inserted to
384    /// maintain the sort. See [`slice::binary_search`] for more details.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use vecmap::VecSet;
390    ///
391    /// let set = VecSet::from(["a", "b", "d"]);
392    /// assert_eq!(set.binary_search(&"b"), Ok(1));
393    /// assert_eq!(set.binary_search(&"c"), Err(2));
394    /// assert_eq!(set.binary_search(&"z"), Err(3));
395    /// ```
396    pub fn binary_search(&self, value: &T) -> Result<usize, usize>
397    where
398        T: Ord,
399    {
400        self.binary_search_by(|v| v.cmp(value))
401    }
402
403    /// Search over a sorted set with a comparator function.
404    ///
405    /// Returns the position where that value is present, or the position where it can be inserted
406    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
407    ///
408    /// # Examples
409    ///
410    /// ```
411    /// use vecmap::VecSet;
412    ///
413    /// let set = VecSet::from(["a", "b", "d"]);
414    ///
415    /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"b")), Ok(1));
416    /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"c")), Err(2));
417    /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"z")), Err(3));
418    /// ```
419    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
420    where
421        F: FnMut(&'a T) -> Ordering,
422    {
423        self.as_slice().binary_search_by(f)
424    }
425
426    /// Search over a sorted set with an extraction function.
427    ///
428    /// Returns the position where that value is present, or the position where it can be inserted
429    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
430    ///
431    /// # Examples
432    ///
433    /// ```
434    /// use vecmap::VecSet;
435    ///
436    /// let map = VecSet::from([("a", 1), ("b", 2), ("d", 4)]);
437    /// assert_eq!(map.binary_search_by_key(&"b", |&(k, _)| k), Ok(1));
438    /// assert_eq!(map.binary_search_by_key(&"c", |&(k, _)| k), Err(2));
439    /// assert_eq!(map.binary_search_by_key(&"z", |&(k, _)| k), Err(3));
440    /// assert_eq!(map.binary_search_by_key(&4, |&(_, v)| v), Ok(2));
441    /// ```
442    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
443    where
444        F: FnMut(&'a T) -> B,
445        B: Ord,
446    {
447        self.as_slice().binary_search_by_key(b, f)
448    }
449
450    /// Returns the index of the partition point of a sorted set according to the given predicate
451    /// (the index of the first element of the second partition).
452    ///
453    /// See [`slice::partition_point`] for more details.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// use vecmap::VecSet;
459    ///
460    /// let map = VecSet::from([1, 2, 4]);
461    /// assert_eq!(map.partition_point(|&v| v < 2), 1);
462    /// assert_eq!(map.partition_point(|&v| v > 100), 0);
463    /// assert_eq!(map.partition_point(|&v| v < 100), 3);
464    /// ```
465    pub fn partition_point<P>(&self, pred: P) -> usize
466    where
467        P: FnMut(&T) -> bool,
468    {
469        self.as_slice().partition_point(pred)
470    }
471
472    /// Removes the specified range from the vector in bulk, returning all removed elements as an
473    /// iterator. If the iterator is dropped before being fully consumed, it drops the remaining
474    /// removed elements.
475    ///
476    /// The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
477    ///
478    /// # Panics
479    ///
480    /// Panics if the starting point is greater than the end point or if the end point is greater
481    /// than the length of the vector.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// use vecmap::VecSet;
487    ///
488    /// let mut v = VecSet::from([1, 2, 3]);
489    /// let u: VecSet<_> = v.drain(1..).collect();
490    /// assert_eq!(v, VecSet::from([1]));
491    /// assert_eq!(u, VecSet::from([2, 3]));
492    ///
493    /// // A full range clears the vector, like `clear()` does
494    /// v.drain(..);
495    /// assert_eq!(v, VecSet::new());
496    /// ```
497    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
498    where
499        R: RangeBounds<usize>,
500    {
501        Drain::new(self, range)
502    }
503
504    /// An iterator visiting all elements in insertion order. The iterator element type is
505    /// `&'a T`.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use vecmap::VecSet;
511    ///
512    /// let set = VecSet::from(["a", "b", "c"]);
513    ///
514    /// for elem in set.iter() {
515    ///     println!("elem: {elem}");
516    /// }
517    /// ```
518    pub fn iter(&self) -> Iter<'_, T> {
519        Iter::new(self.as_entries())
520    }
521
522    /// Sorts the set.
523    ///
524    /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
525    /// worst-case.
526    ///
527    /// When applicable, unstable sorting is preferred because it is generally faster than stable
528    /// sorting and it doesn't allocate auxiliary memory. See
529    /// [`sort_unstable`](VecSet::sort_unstable).
530    ///
531    /// # Examples
532    ///
533    /// ```
534    /// use vecmap::VecSet;
535    ///
536    /// let mut set = VecSet::from(["b", "a", "c"]);
537    ///
538    /// set.sort();
539    /// let vec: Vec<_> = set.into_iter().collect();
540    /// assert_eq!(vec, ["a", "b", "c"]);
541    /// ```
542    pub fn sort(&mut self)
543    where
544        T: Ord,
545    {
546        self.base.sort_keys();
547    }
548
549    /// Sorts the set.
550    ///
551    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
552    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
553    ///
554    /// # Examples
555    ///
556    /// ```
557    /// use vecmap::VecSet;
558    ///
559    /// let mut set = VecSet::from(["b", "a", "c"]);
560    ///
561    /// set.sort_unstable();
562    /// let vec: Vec<_> = set.into_iter().collect();
563    /// assert_eq!(vec, ["a", "b", "c"]);
564    /// ```
565    pub fn sort_unstable(&mut self)
566    where
567        T: Ord,
568    {
569        self.base.sort_unstable_keys();
570    }
571
572    /// Sorts the set with a comparator function.
573    ///
574    /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
575    /// worst-case.
576    ///
577    /// # Examples
578    ///
579    /// ```
580    /// use vecmap::VecSet;
581    ///
582    /// let mut set = VecSet::from(["b", "a", "c"]);
583    ///
584    /// set.sort_by(|a, b| b.cmp(&a));
585    /// let vec: Vec<_> = set.into_iter().collect();
586    /// assert_eq!(vec, ["c", "b", "a"]);
587    /// ```
588    pub fn sort_by<F>(&mut self, mut compare: F)
589    where
590        F: FnMut(&T, &T) -> Ordering,
591    {
592        self.base.sort_by(|a, b| compare(a.0, b.0));
593    }
594
595    /// Sorts the set with a comparator function.
596    ///
597    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
598    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
599    ///
600    /// # Examples
601    ///
602    /// ```
603    /// use vecmap::VecSet;
604    ///
605    /// let mut set = VecSet::from(["b", "a", "c"]);
606    ///
607    /// set.sort_unstable_by(|a, b| b.cmp(&a));
608    /// let vec: Vec<_> = set.into_iter().collect();
609    /// assert_eq!(vec, ["c", "b", "a"]);
610    /// ```
611    pub fn sort_unstable_by<F>(&mut self, mut compare: F)
612    where
613        F: FnMut(&T, &T) -> Ordering,
614    {
615        self.base.sort_unstable_by(|a, b| compare(a.0, b.0));
616    }
617
618    /// Sort the set’s values in place using a key extraction function.
619    ///
620    /// During sorting, the function is called at most once per entry, by using temporary storage
621    /// to remember the results of its evaluation. The order of calls to the function is
622    /// unspecified and may change between versions of `vecmap-rs` or the standard library.
623    ///
624    /// See [`slice::sort_by_cached_key`] for more details.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use vecmap::VecSet;
630    ///
631    /// let mut set = VecSet::from(["b", "a", "c"]);
632    ///
633    /// set.sort_by_cached_key(|k| k.to_string());
634    /// assert_eq!(set.as_slice(), ["a", "b", "c"]);
635    /// ```
636    pub fn sort_by_cached_key<K, F>(&mut self, mut sort_key: F)
637    where
638        K: Ord,
639        F: FnMut(&T) -> K,
640    {
641        self.base.sort_by_cached_key(|k, ()| sort_key(k));
642    }
643
644    /// Extracts a slice containing the set elements.
645    ///
646    /// ```
647    /// use vecmap::VecSet;
648    ///
649    /// let set = VecSet::from(["b", "a", "c"]);
650    /// let slice = set.as_slice();
651    /// assert_eq!(slice, ["b", "a", "c"]);
652    /// ```
653    pub fn as_slice(&self) -> &[T] {
654        // SAFETY: `&[(T, ())]` and `&[T]` have the same memory layout.
655        unsafe { &*(ptr::from_ref::<[(T, ())]>(self.base.as_slice()) as *const [T]) }
656    }
657
658    /// Copies the set elements into a new `Vec<T>`.
659    ///
660    /// ```
661    /// use vecmap::VecSet;
662    ///
663    /// let set = VecSet::from(["b", "a", "c"]);
664    /// let vec = set.to_vec();
665    /// assert_eq!(vec, ["b", "a", "c"]);
666    /// // Here, `set` and `vec` can be modified independently.
667    /// ```
668    pub fn to_vec(&self) -> Vec<T>
669    where
670        T: Clone,
671    {
672        self.iter().cloned().collect()
673    }
674
675    /// Takes ownership of the set and returns its elements as a `Vec<T>`.
676    ///
677    /// ```
678    /// use vecmap::VecSet;
679    ///
680    /// let set = VecSet::from(["b", "a", "c"]);
681    /// let vec = set.into_vec();
682    /// assert_eq!(vec, ["b", "a", "c"]);
683    /// ```
684    pub fn into_vec(self) -> Vec<T> {
685        // SAFETY: `Vec<Slot<T, ()>>` and `Vec<T>` have the same memory layout.
686        unsafe { super::transmute_vec(self.base.base) }
687    }
688
689    /// Takes ownership of provided vector and converts it into `VecSet`.
690    ///
691    /// # Safety
692    ///
693    /// The vector must have no duplicate elements. One way to guarantee it is to sort the vector
694    /// (e.g. by using [`[T]::sort`][slice-sort]) and then drop duplicate elements (e.g. by using
695    /// [`Vec::dedup`]).
696    ///
697    /// # Example
698    ///
699    /// ```
700    /// use vecmap::VecSet;
701    ///
702    /// let mut vec = vec!["b", "a", "c", "b"];
703    /// vec.sort();
704    /// vec.dedup();
705    /// // SAFETY: We've just deduplicated the vector.
706    /// let set = unsafe { VecSet::from_vec_unchecked(vec) };
707    ///
708    /// assert_eq!(set, VecSet::from(["b", "a", "c"]));
709    /// ```
710    ///
711    /// [slice-sort]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort
712    pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {
713        // SAFETY: `Vec<T>` and `Vec<Slot<T, ()>>` have the same memory layout.
714        let base = unsafe { super::transmute_vec(vec) };
715        VecSet {
716            base: VecMap { base },
717        }
718    }
719}
720
721// Lookup operations.
722impl<T> VecSet<T> {
723    /// Return `true` if an equivalent to `key` exists in the set.
724    ///
725    /// # Examples
726    ///
727    /// ```
728    /// use vecmap::VecSet;
729    ///
730    /// let mut set = VecSet::new();
731    /// set.insert(1);
732    /// assert_eq!(set.contains(&1), true);
733    /// assert_eq!(set.contains(&2), false);
734    /// ```
735    pub fn contains<Q>(&self, value: &Q) -> bool
736    where
737        T: Borrow<Q>,
738        Q: Eq + ?Sized,
739    {
740        self.base.contains_key(value)
741    }
742
743    /// Get the first element.
744    ///
745    /// ```
746    /// use vecmap::VecSet;
747    ///
748    /// let mut set = VecSet::from_iter(["a", "b"]);
749    /// assert_eq!(set.first(), Some(&"a"));
750    /// ```
751    pub fn first(&self) -> Option<&T> {
752        self.base.first().map(|(k, ())| k)
753    }
754
755    /// Get the last element.
756    ///
757    /// # Examples
758    ///
759    /// ```
760    /// use vecmap::VecSet;
761    ///
762    /// let mut set = VecSet::from_iter(["a", "b"]);
763    /// assert_eq!(set.last(), Some(&"b"));
764    /// set.pop();
765    /// set.pop();
766    /// assert_eq!(set.last(), None);
767    /// ```
768    pub fn last(&self) -> Option<&T> {
769        self.base.last().map(|(k, ())| k)
770    }
771
772    /// Returns a reference to the value in the set, if any, that is equal to the given value.
773    ///
774    /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
775    /// *must* match those for the value type.
776    ///
777    /// # Examples
778    ///
779    /// ```
780    /// use vecmap::VecSet;
781    ///
782    /// let set = VecSet::from([1, 2, 3]);
783    /// assert_eq!(set.get(&2), Some(&2));
784    /// assert_eq!(set.get(&4), None);
785    /// ```
786    pub fn get<Q>(&self, value: &Q) -> Option<&T>
787    where
788        T: Borrow<Q>,
789        Q: ?Sized + Eq,
790    {
791        self.base.get_key_value(value).map(|(k, ())| k)
792    }
793
794    /// Return references to the element stored at `index`, if it is present, else `None`.
795    ///
796    /// # Examples
797    ///
798    /// ```
799    /// use vecmap::VecSet;
800    ///
801    /// let mut set = VecSet::new();
802    /// set.insert(1);
803    /// assert_eq!(set.get_index(0), Some(&1));
804    /// assert_eq!(set.get_index(1), None);
805    /// ```
806    pub fn get_index(&self, index: usize) -> Option<&T> {
807        self.base.get_index(index).map(|(k, ())| k)
808    }
809
810    /// Returns the index and a reference to the value in the set, if any, that is equal to the
811    /// given value.
812    ///
813    /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
814    /// *must* match those for the value type.
815    ///
816    /// # Examples
817    ///
818    /// ```
819    /// use vecmap::VecSet;
820    ///
821    /// let set = VecSet::from([1, 2, 3]);
822    /// assert_eq!(set.get_full(&2), Some((1, &2)));
823    /// assert_eq!(set.get_full(&4), None);
824    /// ```
825    pub fn get_full<Q>(&self, value: &Q) -> Option<(usize, &T)>
826    where
827        T: Borrow<Q>,
828        Q: ?Sized + Eq,
829    {
830        self.base.get_full(value).map(|(index, k, ())| (index, k))
831    }
832
833    /// Return item index, if it exists in the set.
834    ///
835    /// # Examples
836    ///
837    /// ```
838    /// use vecmap::VecSet;
839    ///
840    /// let mut set = VecSet::new();
841    /// set.insert("a");
842    /// set.insert("b");
843    /// assert_eq!(set.get_index_of("a"), Some(0));
844    /// assert_eq!(set.get_index_of("b"), Some(1));
845    /// assert_eq!(set.get_index_of("c"), None);
846    /// ```
847    pub fn get_index_of<Q>(&self, value: &Q) -> Option<usize>
848    where
849        T: Borrow<Q>,
850        Q: Eq + ?Sized,
851    {
852        self.base.get_index_of(value)
853    }
854}
855
856// Removal operations.
857impl<T> VecSet<T> {
858    /// Removes the last element from the set and returns it, or [`None`] if it is empty.
859    ///
860    /// # Examples
861    ///
862    /// ```
863    /// use vecmap::VecSet;
864    ///
865    /// let mut set = VecSet::from_iter(["a", "b"]);
866    /// assert_eq!(set.pop(), Some("b"));
867    /// assert_eq!(set.pop(), Some("a"));
868    /// assert!(set.is_empty());
869    /// assert_eq!(set.pop(), None);
870    /// ```
871    pub fn pop(&mut self) -> Option<T> {
872        self.base.pop().map(|(k, ())| k)
873    }
874
875    /// Remove the element equivalent to `value`.
876    ///
877    /// Like `Vec::remove`, the element is removed by shifting all of the elements that follow it,
878    /// preserving their relative order. **This perturbs the index of all of those elements!**
879    ///
880    /// Returns `true` if `value` was found in the set.
881    ///
882    /// # Examples
883    ///
884    /// ```
885    /// use vecmap::VecSet;
886    ///
887    /// let mut set = VecSet::from_iter([1, 2, 3, 4]);
888    /// assert_eq!(set.remove(&2), true);
889    /// assert_eq!(set.remove(&2), false);
890    /// assert_eq!(set, VecSet::from_iter([1, 3, 4]));
891    /// ```
892    pub fn remove<Q>(&mut self, value: &Q) -> bool
893    where
894        T: Borrow<Q>,
895        Q: Eq + ?Sized,
896    {
897        self.base.remove(value).is_some()
898    }
899
900    /// Removes and returns the element at position `index` within the set, shifting all elements
901    /// after it to the left.
902    ///
903    /// If you don't need the order of elements to be preserved, use [`swap_remove`] instead.
904    ///
905    /// [`swap_remove`]: VecSet::swap_remove
906    ///
907    /// # Panics
908    ///
909    /// Panics if `index` is out of bounds.
910    ///
911    /// # Examples
912    ///
913    /// ```
914    /// use vecmap::VecSet;
915    ///
916    /// let mut v = VecSet::from(["a", "b", "c"]);
917    /// assert_eq!(v.remove_index(1), "b");
918    /// assert_eq!(v, VecSet::from(["a", "c"]));
919    /// ```
920    pub fn remove_index(&mut self, index: usize) -> T {
921        self.base.remove_index(index).0
922    }
923
924    /// Remove the element equivalent to `value`.
925    ///
926    /// Like `Vec::swap_remove`, the element is removed by swapping it with the last element of the
927    /// map and popping it off. **This perturbs the position of what used to be the last element!**
928    ///
929    /// Returns `true` if `value` was found in the set.
930    ///
931    /// ```
932    /// use vecmap::VecSet;
933    ///
934    /// let mut set = VecSet::from_iter([1, 2, 3, 4]);
935    /// assert_eq!(set.swap_remove(&2), true);
936    /// assert_eq!(set.swap_remove(&2), false);
937    /// assert_eq!(set, VecSet::from_iter([1, 4, 3]));
938    /// ```
939    pub fn swap_remove<Q>(&mut self, value: &Q) -> bool
940    where
941        T: Borrow<Q>,
942        Q: Eq + ?Sized,
943    {
944        self.base.swap_remove(value).is_some()
945    }
946
947    /// Removes an element from the set and returns it.
948    ///
949    /// The removed element is replaced by the last element of the set.
950    ///
951    /// If you need to preserve the element order, use [`remove`] instead.
952    ///
953    /// [`remove`]: VecSet::remove
954    ///
955    /// # Panics
956    ///
957    /// Panics if `index` is out of bounds.
958    ///
959    /// # Examples
960    ///
961    /// ```
962    /// use vecmap::VecSet;
963    ///
964    /// let mut v = VecSet::from(["foo", "bar", "baz", "qux"]);
965    ///
966    /// assert_eq!(v.swap_remove_index(0), "foo");
967    /// assert_eq!(v, VecSet::from(["qux", "bar", "baz"]));
968    ///
969    /// assert_eq!(v.swap_remove_index(0), "qux");
970    /// assert_eq!(v, VecSet::from(["baz", "bar"]));
971    /// ```
972    pub fn swap_remove_index(&mut self, index: usize) -> T {
973        self.base.swap_remove_index(index).0
974    }
975
976    /// Swaps the position of two elements in the set.
977    ///
978    /// # Arguments
979    ///
980    /// * a - The index of the first element
981    /// * b - The index of the second element
982    ///
983    /// # Panics
984    ///
985    /// Panics if `a` or `b` are out of bounds.
986    ///
987    /// # Examples
988    ///
989    /// ```
990    /// use vecmap::VecSet;
991    ///
992    /// let mut set = VecSet::from(["a", "b", "c", "d"]);
993    /// set.swap_indices(1, 3);
994    /// assert_eq!(set.to_vec(), ["a", "d", "c", "b"]);
995    /// ```
996    pub fn swap_indices(&mut self, a: usize, b: usize) {
997        self.base.swap_indices(a, b);
998    }
999
1000    /// Removes and returns the value in the set, if any, that is equal to the given one.
1001    ///
1002    /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
1003    /// *must* match those for the value type.
1004    ///
1005    /// Like `Vec::remove`, the element is removed by shifting all of the elements that follow it,
1006    /// preserving their relative order. **This perturbs the index of all of those elements!**
1007    ///
1008    /// # Examples
1009    ///
1010    /// ```
1011    /// use vecmap::VecSet;
1012    ///
1013    /// let mut set = VecSet::from([1, 2, 3]);
1014    /// assert_eq!(set.take(&2), Some(2));
1015    /// assert_eq!(set.take(&2), None);
1016    /// ```
1017    pub fn take<Q>(&mut self, value: &Q) -> Option<T>
1018    where
1019        T: Borrow<Q>,
1020        Q: ?Sized + Eq,
1021    {
1022        self.base.remove_entry(value).map(|(k, ())| k)
1023    }
1024
1025    /// Removes and returns the value in the set, if any, that is equal to the given one.
1026    ///
1027    /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
1028    /// *must* match those for the value type.
1029    ///
1030    /// Like `Vec::swap_remove`, the element is removed by swapping it with the last element of the
1031    /// map and popping it off. **This perturbs the position of what used to be the last element!**
1032    ///
1033    /// # Examples
1034    ///
1035    /// ```
1036    /// use vecmap::VecSet;
1037    ///
1038    /// let mut set = VecSet::from([1, 2, 3]);
1039    /// assert_eq!(set.take(&2), Some(2));
1040    /// assert_eq!(set.take(&2), None);
1041    /// ```
1042    pub fn swap_take<Q>(&mut self, value: &Q) -> Option<T>
1043    where
1044        T: Borrow<Q>,
1045        Q: ?Sized + Eq,
1046    {
1047        self.base.swap_remove_entry(value).map(|(k, ())| k)
1048    }
1049}
1050
1051// Insertion operations.
1052impl<T> VecSet<T>
1053where
1054    T: Eq,
1055{
1056    /// Adds a value to the set.
1057    ///
1058    /// Returns whether the value was newly inserted. That is:
1059    ///
1060    /// - If the set did not previously contain this value, `true` is returned.
1061    /// - If the set already contained this value, `false` is returned.
1062    ///
1063    /// # Examples
1064    ///
1065    /// ```
1066    /// use vecmap::VecSet;
1067    ///
1068    /// let mut set = VecSet::new();
1069    ///
1070    /// assert_eq!(set.insert(2), true);
1071    /// assert_eq!(set.insert(2), false);
1072    /// assert_eq!(set.len(), 1);
1073    /// ```
1074    pub fn insert(&mut self, value: T) -> bool {
1075        self.base.insert(value, ()).is_none()
1076    }
1077
1078    /// Moves all values from `other` into `self`, leaving `other` empty.
1079    ///
1080    /// This is equivalent to calling [`insert`][Self::insert] for each value from `other` in
1081    /// order, which means that values that already exist in `self` are unchanged in their current
1082    /// position.
1083    ///
1084    /// See also [`union`][Self::union] to iterate the combined values by reference, without
1085    /// modifying `self` or `other`.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// use vecmap::VecSet;
1091    ///
1092    /// let mut a = VecSet::from([3, 2, 1]);
1093    /// let mut b = VecSet::from([3, 4, 5]);
1094    /// let old_capacity = b.capacity();
1095    ///
1096    /// a.append(&mut b);
1097    ///
1098    /// assert_eq!(a.len(), 5);
1099    /// assert_eq!(b.len(), 0);
1100    /// assert_eq!(b.capacity(), old_capacity);
1101    ///
1102    /// assert!(a.iter().eq(&[3, 2, 1, 4, 5]));
1103    /// ```
1104    pub fn append(&mut self, other: &mut VecSet<T>) {
1105        self.base.append(&mut other.base);
1106    }
1107}
1108
1109// Set operations.
1110impl<T> VecSet<T>
1111where
1112    T: Eq,
1113{
1114    /// Visits the values representing the difference, i.e., the values that are in `self` but not
1115    /// in `other`.
1116    ///
1117    /// # Examples
1118    ///
1119    /// ```
1120    /// use vecmap::VecSet;
1121    /// let a = VecSet::from([1, 2, 3]);
1122    /// let b = VecSet::from([4, 2, 3, 4]);
1123    ///
1124    /// // Can be seen as `a - b`.
1125    /// for x in a.difference(&b) {
1126    ///     println!("{x}"); // Print 1
1127    /// }
1128    ///
1129    /// let diff: VecSet<_> = a.difference(&b).collect();
1130    /// assert_eq!(diff, [1].iter().collect());
1131    ///
1132    /// // Note that difference is not symmetric,
1133    /// // and `b - a` means something else:
1134    /// let diff: VecSet<_> = b.difference(&a).collect();
1135    /// assert_eq!(diff, [4].iter().collect());
1136    /// ```
1137    pub fn difference<'a>(&'a self, other: &'a VecSet<T>) -> Difference<'a, T> {
1138        Difference::new(self, other)
1139    }
1140
1141    /// Visits the values representing the intersection, i.e., the values that are both in `self`
1142    /// and `other`.
1143    ///
1144    /// When an equal element is present in `self` and `other` then the resulting `Intersection`
1145    /// may yield references to one or the other. This can be relevant if `T` contains fields which
1146    /// are not compared by its `Eq` implementation, and may hold different value between the two
1147    /// equal copies of `T` in the two sets.
1148    ///
1149    /// # Examples
1150    ///
1151    /// ```
1152    /// use vecmap::VecSet;
1153    /// let a = VecSet::from([1, 2, 3]);
1154    /// let b = VecSet::from([4, 2, 3, 4]);
1155    ///
1156    /// // Print 2, 3 in arbitrary order.
1157    /// for x in a.intersection(&b) {
1158    ///     println!("{x}");
1159    /// }
1160    ///
1161    /// let intersection: VecSet<_> = a.intersection(&b).collect();
1162    /// assert_eq!(intersection, [2, 3].iter().collect());
1163    /// ```
1164    pub fn intersection<'a>(&'a self, other: &'a VecSet<T>) -> Intersection<'a, T> {
1165        if self.len() <= other.len() {
1166            Intersection::new(self, other)
1167        } else {
1168            Intersection::new(other, self)
1169        }
1170    }
1171
1172    /// Visits the values representing the symmetric difference, i.e., the values that are in
1173    /// `self` or in `other` but not in both.
1174    ///
1175    /// # Examples
1176    ///
1177    /// ```
1178    /// use vecmap::VecSet;
1179    /// let a = VecSet::from([1, 2, 3]);
1180    /// let b = VecSet::from([4, 2, 3, 4]);
1181    ///
1182    /// // Print 1, 4 in arbitrary order.
1183    /// for x in a.symmetric_difference(&b) {
1184    ///     println!("{x}");
1185    /// }
1186    ///
1187    /// let diff1: VecSet<_> = a.symmetric_difference(&b).collect();
1188    /// let diff2: VecSet<_> = b.symmetric_difference(&a).collect();
1189    ///
1190    /// assert_eq!(diff1, diff2);
1191    /// assert_eq!(diff1, [1, 4].iter().collect());
1192    /// ```
1193    pub fn symmetric_difference<'a>(&'a self, other: &'a VecSet<T>) -> SymmetricDifference<'a, T> {
1194        SymmetricDifference::new(self, other)
1195    }
1196
1197    /// Visits the values representing the union, i.e., all the values in `self` or `other`,
1198    /// without duplicates.
1199    ///
1200    /// # Examples
1201    ///
1202    /// ```
1203    /// use vecmap::VecSet;
1204    /// let a = VecSet::from([1, 2, 3]);
1205    /// let b = VecSet::from([4, 2, 3, 4]);
1206    ///
1207    /// // Print 1, 2, 3, 4 in arbitrary order.
1208    /// for x in a.union(&b) {
1209    ///     println!("{x}");
1210    /// }
1211    ///
1212    /// let union: VecSet<_> = a.union(&b).collect();
1213    /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
1214    /// ```
1215    pub fn union<'a>(&'a self, other: &'a VecSet<T>) -> Union<'a, T> {
1216        if self.len() >= other.len() {
1217            Union::new(self, other)
1218        } else {
1219            Union::new(other, self)
1220        }
1221    }
1222
1223    /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
1224    /// checking for an empty intersection.
1225    ///
1226    /// # Examples
1227    ///
1228    /// ```
1229    /// use vecmap::VecSet;
1230    ///
1231    /// let a = VecSet::from([1, 2, 3]);
1232    /// let mut b = VecSet::new();
1233    ///
1234    /// assert_eq!(a.is_disjoint(&b), true);
1235    /// b.insert(4);
1236    /// assert_eq!(a.is_disjoint(&b), true);
1237    /// b.insert(1);
1238    /// assert_eq!(a.is_disjoint(&b), false);
1239    /// ```
1240    pub fn is_disjoint(&self, other: &VecSet<T>) -> bool {
1241        if self.len() <= other.len() {
1242            self.iter().all(|v| !other.contains(v))
1243        } else {
1244            other.iter().all(|v| !self.contains(v))
1245        }
1246    }
1247
1248    /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all the
1249    /// values in `self`.
1250    ///
1251    /// # Examples
1252    ///
1253    /// ```
1254    /// use vecmap::VecSet;
1255    ///
1256    /// let sup = VecSet::from([1, 2, 3]);
1257    /// let mut set = VecSet::new();
1258    ///
1259    /// assert_eq!(set.is_subset(&sup), true);
1260    /// set.insert(2);
1261    /// assert_eq!(set.is_subset(&sup), true);
1262    /// set.insert(4);
1263    /// assert_eq!(set.is_subset(&sup), false);
1264    /// ```
1265    pub fn is_subset(&self, other: &VecSet<T>) -> bool {
1266        if self.len() <= other.len() {
1267            self.iter().all(|v| other.contains(v))
1268        } else {
1269            false
1270        }
1271    }
1272
1273    /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
1274    /// values in `other`.
1275    ///
1276    /// # Examples
1277    ///
1278    /// ```
1279    /// use vecmap::VecSet;
1280    ///
1281    /// let sub = VecSet::from([1, 2]);
1282    /// let mut set = VecSet::new();
1283    ///
1284    /// assert_eq!(set.is_superset(&sub), false);
1285    ///
1286    /// set.insert(0);
1287    /// set.insert(1);
1288    /// assert_eq!(set.is_superset(&sub), false);
1289    ///
1290    /// set.insert(2);
1291    /// assert_eq!(set.is_superset(&sub), true);
1292    /// ```
1293    pub fn is_superset(&self, other: &VecSet<T>) -> bool {
1294        other.is_subset(self)
1295    }
1296}
1297
1298impl<T> Entries for VecSet<T> {
1299    type Entry = Slot<T, ()>;
1300
1301    fn as_entries(&self) -> &[Self::Entry] {
1302        self.base.as_entries()
1303    }
1304
1305    fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
1306        self.base.as_entries_mut()
1307    }
1308
1309    fn into_entries(self) -> Vec<Self::Entry> {
1310        self.base.into_entries()
1311    }
1312}