indexmap/
set.rs

1//! A hash set implemented using [`IndexMap`]
2
3mod iter;
4mod mutable;
5mod slice;
6
7#[cfg(test)]
8mod tests;
9
10pub use self::iter::{
11    Difference, Drain, Intersection, IntoIter, Iter, Splice, SymmetricDifference, Union,
12};
13pub use self::mutable::MutableValues;
14pub use self::slice::Slice;
15
16#[cfg(feature = "rayon")]
17pub use crate::rayon::set as rayon;
18use crate::TryReserveError;
19
20#[cfg(feature = "std")]
21use std::collections::hash_map::RandomState;
22
23use crate::util::try_simplify_range;
24use alloc::boxed::Box;
25use alloc::vec::Vec;
26use core::cmp::Ordering;
27use core::fmt;
28use core::hash::{BuildHasher, Hash};
29use core::ops::{BitAnd, BitOr, BitXor, Index, RangeBounds, Sub};
30
31use super::{Entries, Equivalent, IndexMap};
32
33type Bucket<T> = super::Bucket<T, ()>;
34
35/// A hash set where the iteration order of the values is independent of their
36/// hash values.
37///
38/// The interface is closely compatible with the standard
39/// [`HashSet`][std::collections::HashSet],
40/// but also has additional features.
41///
42/// # Order
43///
44/// The values have a consistent order that is determined by the sequence of
45/// insertion and removal calls on the set. The order does not depend on the
46/// values or the hash function at all. Note that insertion order and value
47/// are not affected if a re-insertion is attempted once an element is
48/// already present.
49///
50/// All iterators traverse the set *in order*.  Set operation iterators like
51/// [`IndexSet::union`] produce a concatenated order, as do their matching "bitwise"
52/// operators.  See their documentation for specifics.
53///
54/// The insertion order is preserved, with **notable exceptions** like the
55/// [`.remove()`][Self::remove] or [`.swap_remove()`][Self::swap_remove] methods.
56/// Methods such as [`.sort_by()`][Self::sort_by] of
57/// course result in a new order, depending on the sorting order.
58///
59/// # Indices
60///
61/// The values are indexed in a compact range without holes in the range
62/// `0..self.len()`. For example, the method `.get_full` looks up the index for
63/// a value, and the method `.get_index` looks up the value by index.
64///
65/// # Complexity
66///
67/// Internally, `IndexSet<T, S>` just holds an [`IndexMap<T, (), S>`](IndexMap). Thus the complexity
68/// of the two are the same for most methods.
69///
70/// # Examples
71///
72/// ```
73/// use indexmap::IndexSet;
74///
75/// // Collects which letters appear in a sentence.
76/// let letters: IndexSet<_> = "a short treatise on fungi".chars().collect();
77///
78/// assert!(letters.contains(&'s'));
79/// assert!(letters.contains(&'t'));
80/// assert!(letters.contains(&'u'));
81/// assert!(!letters.contains(&'y'));
82/// ```
83#[cfg(feature = "std")]
84pub struct IndexSet<T, S = RandomState> {
85    pub(crate) map: IndexMap<T, (), S>,
86}
87#[cfg(not(feature = "std"))]
88pub struct IndexSet<T, S> {
89    pub(crate) map: IndexMap<T, (), S>,
90}
91
92impl<T, S> Clone for IndexSet<T, S>
93where
94    T: Clone,
95    S: Clone,
96{
97    fn clone(&self) -> Self {
98        IndexSet {
99            map: self.map.clone(),
100        }
101    }
102
103    fn clone_from(&mut self, other: &Self) {
104        self.map.clone_from(&other.map);
105    }
106}
107
108impl<T, S> Entries for IndexSet<T, S> {
109    type Entry = Bucket<T>;
110
111    #[inline]
112    fn into_entries(self) -> Vec<Self::Entry> {
113        self.map.into_entries()
114    }
115
116    #[inline]
117    fn as_entries(&self) -> &[Self::Entry] {
118        self.map.as_entries()
119    }
120
121    #[inline]
122    fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
123        self.map.as_entries_mut()
124    }
125
126    fn with_entries<F>(&mut self, f: F)
127    where
128        F: FnOnce(&mut [Self::Entry]),
129    {
130        self.map.with_entries(f);
131    }
132}
133
134impl<T, S> fmt::Debug for IndexSet<T, S>
135where
136    T: fmt::Debug,
137{
138    #[cfg(not(feature = "test_debug"))]
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.debug_set().entries(self.iter()).finish()
141    }
142
143    #[cfg(feature = "test_debug")]
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        // Let the inner `IndexMap` print all of its details
146        f.debug_struct("IndexSet").field("map", &self.map).finish()
147    }
148}
149
150#[cfg(feature = "std")]
151#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
152impl<T> IndexSet<T> {
153    /// Create a new set. (Does not allocate.)
154    pub fn new() -> Self {
155        IndexSet {
156            map: IndexMap::new(),
157        }
158    }
159
160    /// Create a new set with capacity for `n` elements.
161    /// (Does not allocate if `n` is zero.)
162    ///
163    /// Computes in **O(n)** time.
164    pub fn with_capacity(n: usize) -> Self {
165        IndexSet {
166            map: IndexMap::with_capacity(n),
167        }
168    }
169}
170
171impl<T, S> IndexSet<T, S> {
172    /// Create a new set with capacity for `n` elements.
173    /// (Does not allocate if `n` is zero.)
174    ///
175    /// Computes in **O(n)** time.
176    pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self {
177        IndexSet {
178            map: IndexMap::with_capacity_and_hasher(n, hash_builder),
179        }
180    }
181
182    /// Create a new set with `hash_builder`.
183    ///
184    /// This function is `const`, so it
185    /// can be called in `static` contexts.
186    pub const fn with_hasher(hash_builder: S) -> Self {
187        IndexSet {
188            map: IndexMap::with_hasher(hash_builder),
189        }
190    }
191
192    /// Return the number of elements the set can hold without reallocating.
193    ///
194    /// This number is a lower bound; the set might be able to hold more,
195    /// but is guaranteed to be able to hold at least this many.
196    ///
197    /// Computes in **O(1)** time.
198    pub fn capacity(&self) -> usize {
199        self.map.capacity()
200    }
201
202    /// Return a reference to the set's `BuildHasher`.
203    pub fn hasher(&self) -> &S {
204        self.map.hasher()
205    }
206
207    /// Return the number of elements in the set.
208    ///
209    /// Computes in **O(1)** time.
210    pub fn len(&self) -> usize {
211        self.map.len()
212    }
213
214    /// Returns true if the set contains no elements.
215    ///
216    /// Computes in **O(1)** time.
217    pub fn is_empty(&self) -> bool {
218        self.map.is_empty()
219    }
220
221    /// Return an iterator over the values of the set, in their order
222    pub fn iter(&self) -> Iter<'_, T> {
223        Iter::new(self.as_entries())
224    }
225
226    /// Remove all elements in the set, while preserving its capacity.
227    ///
228    /// Computes in **O(n)** time.
229    pub fn clear(&mut self) {
230        self.map.clear();
231    }
232
233    /// Shortens the set, keeping the first `len` elements and dropping the rest.
234    ///
235    /// If `len` is greater than the set's current length, this has no effect.
236    pub fn truncate(&mut self, len: usize) {
237        self.map.truncate(len);
238    }
239
240    /// Clears the `IndexSet` in the given index range, returning those values
241    /// as a drain iterator.
242    ///
243    /// The range may be any type that implements [`RangeBounds<usize>`],
244    /// including all of the `std::ops::Range*` types, or even a tuple pair of
245    /// `Bound` start and end values. To drain the set entirely, use `RangeFull`
246    /// like `set.drain(..)`.
247    ///
248    /// This shifts down all entries following the drained range to fill the
249    /// gap, and keeps the allocated memory for reuse.
250    ///
251    /// ***Panics*** if the starting point is greater than the end point or if
252    /// the end point is greater than the length of the set.
253    #[track_caller]
254    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
255    where
256        R: RangeBounds<usize>,
257    {
258        Drain::new(self.map.core.drain(range))
259    }
260
261    /// Splits the collection into two at the given index.
262    ///
263    /// Returns a newly allocated set containing the elements in the range
264    /// `[at, len)`. After the call, the original set will be left containing
265    /// the elements `[0, at)` with its previous capacity unchanged.
266    ///
267    /// ***Panics*** if `at > len`.
268    #[track_caller]
269    pub fn split_off(&mut self, at: usize) -> Self
270    where
271        S: Clone,
272    {
273        Self {
274            map: self.map.split_off(at),
275        }
276    }
277
278    /// Reserve capacity for `additional` more values.
279    ///
280    /// Computes in **O(n)** time.
281    pub fn reserve(&mut self, additional: usize) {
282        self.map.reserve(additional);
283    }
284
285    /// Reserve capacity for `additional` more values, without over-allocating.
286    ///
287    /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid
288    /// frequent re-allocations. However, the underlying data structures may still have internal
289    /// capacity requirements, and the allocator itself may give more space than requested, so this
290    /// cannot be relied upon to be precisely minimal.
291    ///
292    /// Computes in **O(n)** time.
293    pub fn reserve_exact(&mut self, additional: usize) {
294        self.map.reserve_exact(additional);
295    }
296
297    /// Try to reserve capacity for `additional` more values.
298    ///
299    /// Computes in **O(n)** time.
300    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
301        self.map.try_reserve(additional)
302    }
303
304    /// Try to reserve capacity for `additional` more values, without over-allocating.
305    ///
306    /// Unlike `try_reserve`, this does not deliberately over-allocate the entry capacity to avoid
307    /// frequent re-allocations. However, the underlying data structures may still have internal
308    /// capacity requirements, and the allocator itself may give more space than requested, so this
309    /// cannot be relied upon to be precisely minimal.
310    ///
311    /// Computes in **O(n)** time.
312    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
313        self.map.try_reserve_exact(additional)
314    }
315
316    /// Shrink the capacity of the set as much as possible.
317    ///
318    /// Computes in **O(n)** time.
319    pub fn shrink_to_fit(&mut self) {
320        self.map.shrink_to_fit();
321    }
322
323    /// Shrink the capacity of the set with a lower limit.
324    ///
325    /// Computes in **O(n)** time.
326    pub fn shrink_to(&mut self, min_capacity: usize) {
327        self.map.shrink_to(min_capacity);
328    }
329}
330
331impl<T, S> IndexSet<T, S>
332where
333    T: Hash + Eq,
334    S: BuildHasher,
335{
336    /// Insert the value into the set.
337    ///
338    /// If an equivalent item already exists in the set, it returns
339    /// `false` leaving the original value in the set and without
340    /// altering its insertion order. Otherwise, it inserts the new
341    /// item and returns `true`.
342    ///
343    /// Computes in **O(1)** time (amortized average).
344    pub fn insert(&mut self, value: T) -> bool {
345        self.map.insert(value, ()).is_none()
346    }
347
348    /// Insert the value into the set, and get its index.
349    ///
350    /// If an equivalent item already exists in the set, it returns
351    /// the index of the existing item and `false`, leaving the
352    /// original value in the set and without altering its insertion
353    /// order. Otherwise, it inserts the new item and returns the index
354    /// of the inserted item and `true`.
355    ///
356    /// Computes in **O(1)** time (amortized average).
357    pub fn insert_full(&mut self, value: T) -> (usize, bool) {
358        let (index, existing) = self.map.insert_full(value, ());
359        (index, existing.is_none())
360    }
361
362    /// Insert the value into the set at its ordered position among sorted values.
363    ///
364    /// This is equivalent to finding the position with
365    /// [`binary_search`][Self::binary_search], and if needed calling
366    /// [`insert_before`][Self::insert_before] for a new value.
367    ///
368    /// If the sorted item is found in the set, it returns the index of that
369    /// existing item and `false`, without any change. Otherwise, it inserts the
370    /// new item and returns its sorted index and `true`.
371    ///
372    /// If the existing items are **not** already sorted, then the insertion
373    /// index is unspecified (like [`slice::binary_search`]), but the value
374    /// is moved to or inserted at that position regardless.
375    ///
376    /// Computes in **O(n)** time (average). Instead of repeating calls to
377    /// `insert_sorted`, it may be faster to call batched [`insert`][Self::insert]
378    /// or [`extend`][Self::extend] and only call [`sort`][Self::sort] or
379    /// [`sort_unstable`][Self::sort_unstable] once.
380    pub fn insert_sorted(&mut self, value: T) -> (usize, bool)
381    where
382        T: Ord,
383    {
384        let (index, existing) = self.map.insert_sorted(value, ());
385        (index, existing.is_none())
386    }
387
388    /// Insert the value into the set before the value at the given index, or at the end.
389    ///
390    /// If an equivalent item already exists in the set, it returns `false` leaving the
391    /// original value in the set, but moved to the new position. The returned index
392    /// will either be the given index or one less, depending on how the value moved.
393    /// (See [`shift_insert`](Self::shift_insert) for different behavior here.)
394    ///
395    /// Otherwise, it inserts the new value exactly at the given index and returns `true`.
396    ///
397    /// ***Panics*** if `index` is out of bounds.
398    /// Valid indices are `0..=set.len()` (inclusive).
399    ///
400    /// Computes in **O(n)** time (average).
401    ///
402    /// # Examples
403    ///
404    /// ```
405    /// use indexmap::IndexSet;
406    /// let mut set: IndexSet<char> = ('a'..='z').collect();
407    ///
408    /// // The new value '*' goes exactly at the given index.
409    /// assert_eq!(set.get_index_of(&'*'), None);
410    /// assert_eq!(set.insert_before(10, '*'), (10, true));
411    /// assert_eq!(set.get_index_of(&'*'), Some(10));
412    ///
413    /// // Moving the value 'a' up will shift others down, so this moves *before* 10 to index 9.
414    /// assert_eq!(set.insert_before(10, 'a'), (9, false));
415    /// assert_eq!(set.get_index_of(&'a'), Some(9));
416    /// assert_eq!(set.get_index_of(&'*'), Some(10));
417    ///
418    /// // Moving the value 'z' down will shift others up, so this moves to exactly 10.
419    /// assert_eq!(set.insert_before(10, 'z'), (10, false));
420    /// assert_eq!(set.get_index_of(&'z'), Some(10));
421    /// assert_eq!(set.get_index_of(&'*'), Some(11));
422    ///
423    /// // Moving or inserting before the endpoint is also valid.
424    /// assert_eq!(set.len(), 27);
425    /// assert_eq!(set.insert_before(set.len(), '*'), (26, false));
426    /// assert_eq!(set.get_index_of(&'*'), Some(26));
427    /// assert_eq!(set.insert_before(set.len(), '+'), (27, true));
428    /// assert_eq!(set.get_index_of(&'+'), Some(27));
429    /// assert_eq!(set.len(), 28);
430    /// ```
431    #[track_caller]
432    pub fn insert_before(&mut self, index: usize, value: T) -> (usize, bool) {
433        let (index, existing) = self.map.insert_before(index, value, ());
434        (index, existing.is_none())
435    }
436
437    /// Insert the value into the set at the given index.
438    ///
439    /// If an equivalent item already exists in the set, it returns `false` leaving
440    /// the original value in the set, but moved to the given index.
441    /// Note that existing values **cannot** be moved to `index == set.len()`!
442    /// (See [`insert_before`](Self::insert_before) for different behavior here.)
443    ///
444    /// Otherwise, it inserts the new value at the given index and returns `true`.
445    ///
446    /// ***Panics*** if `index` is out of bounds.
447    /// Valid indices are `0..set.len()` (exclusive) when moving an existing value, or
448    /// `0..=set.len()` (inclusive) when inserting a new value.
449    ///
450    /// Computes in **O(n)** time (average).
451    ///
452    /// # Examples
453    ///
454    /// ```
455    /// use indexmap::IndexSet;
456    /// let mut set: IndexSet<char> = ('a'..='z').collect();
457    ///
458    /// // The new value '*' goes exactly at the given index.
459    /// assert_eq!(set.get_index_of(&'*'), None);
460    /// assert_eq!(set.shift_insert(10, '*'), true);
461    /// assert_eq!(set.get_index_of(&'*'), Some(10));
462    ///
463    /// // Moving the value 'a' up to 10 will shift others down, including the '*' that was at 10.
464    /// assert_eq!(set.shift_insert(10, 'a'), false);
465    /// assert_eq!(set.get_index_of(&'a'), Some(10));
466    /// assert_eq!(set.get_index_of(&'*'), Some(9));
467    ///
468    /// // Moving the value 'z' down to 9 will shift others up, including the '*' that was at 9.
469    /// assert_eq!(set.shift_insert(9, 'z'), false);
470    /// assert_eq!(set.get_index_of(&'z'), Some(9));
471    /// assert_eq!(set.get_index_of(&'*'), Some(10));
472    ///
473    /// // Existing values can move to len-1 at most, but new values can insert at the endpoint.
474    /// assert_eq!(set.len(), 27);
475    /// assert_eq!(set.shift_insert(set.len() - 1, '*'), false);
476    /// assert_eq!(set.get_index_of(&'*'), Some(26));
477    /// assert_eq!(set.shift_insert(set.len(), '+'), true);
478    /// assert_eq!(set.get_index_of(&'+'), Some(27));
479    /// assert_eq!(set.len(), 28);
480    /// ```
481    ///
482    /// ```should_panic
483    /// use indexmap::IndexSet;
484    /// let mut set: IndexSet<char> = ('a'..='z').collect();
485    ///
486    /// // This is an invalid index for moving an existing value!
487    /// set.shift_insert(set.len(), 'a');
488    /// ```
489    #[track_caller]
490    pub fn shift_insert(&mut self, index: usize, value: T) -> bool {
491        self.map.shift_insert(index, value, ()).is_none()
492    }
493
494    /// Adds a value to the set, replacing the existing value, if any, that is
495    /// equal to the given one, without altering its insertion order. Returns
496    /// the replaced value.
497    ///
498    /// Computes in **O(1)** time (average).
499    pub fn replace(&mut self, value: T) -> Option<T> {
500        self.replace_full(value).1
501    }
502
503    /// Adds a value to the set, replacing the existing value, if any, that is
504    /// equal to the given one, without altering its insertion order. Returns
505    /// the index of the item and its replaced value.
506    ///
507    /// Computes in **O(1)** time (average).
508    pub fn replace_full(&mut self, value: T) -> (usize, Option<T>) {
509        let hash = self.map.hash(&value);
510        match self.map.core.replace_full(hash, value, ()) {
511            (i, Some((replaced, ()))) => (i, Some(replaced)),
512            (i, None) => (i, None),
513        }
514    }
515
516    /// Return an iterator over the values that are in `self` but not `other`.
517    ///
518    /// Values are produced in the same order that they appear in `self`.
519    pub fn difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Difference<'a, T, S2>
520    where
521        S2: BuildHasher,
522    {
523        Difference::new(self, other)
524    }
525
526    /// Return an iterator over the values that are in `self` or `other`,
527    /// but not in both.
528    ///
529    /// Values from `self` are produced in their original order, followed by
530    /// values from `other` in their original order.
531    pub fn symmetric_difference<'a, S2>(
532        &'a self,
533        other: &'a IndexSet<T, S2>,
534    ) -> SymmetricDifference<'a, T, S, S2>
535    where
536        S2: BuildHasher,
537    {
538        SymmetricDifference::new(self, other)
539    }
540
541    /// Return an iterator over the values that are in both `self` and `other`.
542    ///
543    /// Values are produced in the same order that they appear in `self`.
544    pub fn intersection<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Intersection<'a, T, S2>
545    where
546        S2: BuildHasher,
547    {
548        Intersection::new(self, other)
549    }
550
551    /// Return an iterator over all values that are in `self` or `other`.
552    ///
553    /// Values from `self` are produced in their original order, followed by
554    /// values that are unique to `other` in their original order.
555    pub fn union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Union<'a, T, S>
556    where
557        S2: BuildHasher,
558    {
559        Union::new(self, other)
560    }
561
562    /// Creates a splicing iterator that replaces the specified range in the set
563    /// with the given `replace_with` iterator and yields the removed items.
564    /// `replace_with` does not need to be the same length as `range`.
565    ///
566    /// The `range` is removed even if the iterator is not consumed until the
567    /// end. It is unspecified how many elements are removed from the set if the
568    /// `Splice` value is leaked.
569    ///
570    /// The input iterator `replace_with` is only consumed when the `Splice`
571    /// value is dropped. If a value from the iterator matches an existing entry
572    /// in the set (outside of `range`), then the original will be unchanged.
573    /// Otherwise, the new value will be inserted in the replaced `range`.
574    ///
575    /// ***Panics*** if the starting point is greater than the end point or if
576    /// the end point is greater than the length of the set.
577    ///
578    /// # Examples
579    ///
580    /// ```
581    /// use indexmap::IndexSet;
582    ///
583    /// let mut set = IndexSet::from([0, 1, 2, 3, 4]);
584    /// let new = [5, 4, 3, 2, 1];
585    /// let removed: Vec<_> = set.splice(2..4, new).collect();
586    ///
587    /// // 1 and 4 kept their positions, while 5, 3, and 2 were newly inserted.
588    /// assert!(set.into_iter().eq([0, 1, 5, 3, 2, 4]));
589    /// assert_eq!(removed, &[2, 3]);
590    /// ```
591    #[track_caller]
592    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, T, S>
593    where
594        R: RangeBounds<usize>,
595        I: IntoIterator<Item = T>,
596    {
597        Splice::new(self, range, replace_with.into_iter())
598    }
599
600    /// Moves all values from `other` into `self`, leaving `other` empty.
601    ///
602    /// This is equivalent to calling [`insert`][Self::insert] for each value
603    /// from `other` in order, which means that values that already exist
604    /// in `self` are unchanged in their current position.
605    ///
606    /// See also [`union`][Self::union] to iterate the combined values by
607    /// reference, without modifying `self` or `other`.
608    ///
609    /// # Examples
610    ///
611    /// ```
612    /// use indexmap::IndexSet;
613    ///
614    /// let mut a = IndexSet::from([3, 2, 1]);
615    /// let mut b = IndexSet::from([3, 4, 5]);
616    /// let old_capacity = b.capacity();
617    ///
618    /// a.append(&mut b);
619    ///
620    /// assert_eq!(a.len(), 5);
621    /// assert_eq!(b.len(), 0);
622    /// assert_eq!(b.capacity(), old_capacity);
623    ///
624    /// assert!(a.iter().eq(&[3, 2, 1, 4, 5]));
625    /// ```
626    pub fn append<S2>(&mut self, other: &mut IndexSet<T, S2>) {
627        self.map.append(&mut other.map);
628    }
629}
630
631impl<T, S> IndexSet<T, S>
632where
633    S: BuildHasher,
634{
635    /// Return `true` if an equivalent to `value` exists in the set.
636    ///
637    /// Computes in **O(1)** time (average).
638    pub fn contains<Q>(&self, value: &Q) -> bool
639    where
640        Q: ?Sized + Hash + Equivalent<T>,
641    {
642        self.map.contains_key(value)
643    }
644
645    /// Return a reference to the value stored in the set, if it is present,
646    /// else `None`.
647    ///
648    /// Computes in **O(1)** time (average).
649    pub fn get<Q>(&self, value: &Q) -> Option<&T>
650    where
651        Q: ?Sized + Hash + Equivalent<T>,
652    {
653        self.map.get_key_value(value).map(|(x, &())| x)
654    }
655
656    /// Return item index and value
657    pub fn get_full<Q>(&self, value: &Q) -> Option<(usize, &T)>
658    where
659        Q: ?Sized + Hash + Equivalent<T>,
660    {
661        self.map.get_full(value).map(|(i, x, &())| (i, x))
662    }
663
664    /// Return item index, if it exists in the set
665    ///
666    /// Computes in **O(1)** time (average).
667    pub fn get_index_of<Q>(&self, value: &Q) -> Option<usize>
668    where
669        Q: ?Sized + Hash + Equivalent<T>,
670    {
671        self.map.get_index_of(value)
672    }
673
674    /// Remove the value from the set, and return `true` if it was present.
675    ///
676    /// **NOTE:** This is equivalent to [`.swap_remove(value)`][Self::swap_remove], replacing this
677    /// value's position with the last element, and it is deprecated in favor of calling that
678    /// explicitly. If you need to preserve the relative order of the values in the set, use
679    /// [`.shift_remove(value)`][Self::shift_remove] instead.
680    #[deprecated(note = "`remove` disrupts the set order -- \
681        use `swap_remove` or `shift_remove` for explicit behavior.")]
682    pub fn remove<Q>(&mut self, value: &Q) -> bool
683    where
684        Q: ?Sized + Hash + Equivalent<T>,
685    {
686        self.swap_remove(value)
687    }
688
689    /// Remove the value from the set, and return `true` if it was present.
690    ///
691    /// Like [`Vec::swap_remove`], the value is removed by swapping it with the
692    /// last element of the set and popping it off. **This perturbs
693    /// the position of what used to be the last element!**
694    ///
695    /// Return `false` if `value` was not in the set.
696    ///
697    /// Computes in **O(1)** time (average).
698    pub fn swap_remove<Q>(&mut self, value: &Q) -> bool
699    where
700        Q: ?Sized + Hash + Equivalent<T>,
701    {
702        self.map.swap_remove(value).is_some()
703    }
704
705    /// Remove the value from the set, and return `true` if it was present.
706    ///
707    /// Like [`Vec::remove`], the value is removed by shifting all of the
708    /// elements that follow it, preserving their relative order.
709    /// **This perturbs the index of all of those elements!**
710    ///
711    /// Return `false` if `value` was not in the set.
712    ///
713    /// Computes in **O(n)** time (average).
714    pub fn shift_remove<Q>(&mut self, value: &Q) -> bool
715    where
716        Q: ?Sized + Hash + Equivalent<T>,
717    {
718        self.map.shift_remove(value).is_some()
719    }
720
721    /// Removes and returns the value in the set, if any, that is equal to the
722    /// given one.
723    ///
724    /// **NOTE:** This is equivalent to [`.swap_take(value)`][Self::swap_take], replacing this
725    /// value's position with the last element, and it is deprecated in favor of calling that
726    /// explicitly. If you need to preserve the relative order of the values in the set, use
727    /// [`.shift_take(value)`][Self::shift_take] instead.
728    #[deprecated(note = "`take` disrupts the set order -- \
729        use `swap_take` or `shift_take` for explicit behavior.")]
730    pub fn take<Q>(&mut self, value: &Q) -> Option<T>
731    where
732        Q: ?Sized + Hash + Equivalent<T>,
733    {
734        self.swap_take(value)
735    }
736
737    /// Removes and returns the value in the set, if any, that is equal to the
738    /// given one.
739    ///
740    /// Like [`Vec::swap_remove`], the value is removed by swapping it with the
741    /// last element of the set and popping it off. **This perturbs
742    /// the position of what used to be the last element!**
743    ///
744    /// Return `None` if `value` was not in the set.
745    ///
746    /// Computes in **O(1)** time (average).
747    pub fn swap_take<Q>(&mut self, value: &Q) -> Option<T>
748    where
749        Q: ?Sized + Hash + Equivalent<T>,
750    {
751        self.map.swap_remove_entry(value).map(|(x, ())| x)
752    }
753
754    /// Removes and returns the value in the set, if any, that is equal to the
755    /// given one.
756    ///
757    /// Like [`Vec::remove`], the value is removed by shifting all of the
758    /// elements that follow it, preserving their relative order.
759    /// **This perturbs the index of all of those elements!**
760    ///
761    /// Return `None` if `value` was not in the set.
762    ///
763    /// Computes in **O(n)** time (average).
764    pub fn shift_take<Q>(&mut self, value: &Q) -> Option<T>
765    where
766        Q: ?Sized + Hash + Equivalent<T>,
767    {
768        self.map.shift_remove_entry(value).map(|(x, ())| x)
769    }
770
771    /// Remove the value from the set return it and the index it had.
772    ///
773    /// Like [`Vec::swap_remove`], the value is removed by swapping it with the
774    /// last element of the set and popping it off. **This perturbs
775    /// the position of what used to be the last element!**
776    ///
777    /// Return `None` if `value` was not in the set.
778    pub fn swap_remove_full<Q>(&mut self, value: &Q) -> Option<(usize, T)>
779    where
780        Q: ?Sized + Hash + Equivalent<T>,
781    {
782        self.map.swap_remove_full(value).map(|(i, x, ())| (i, x))
783    }
784
785    /// Remove the value from the set return it and the index it had.
786    ///
787    /// Like [`Vec::remove`], the value is removed by shifting all of the
788    /// elements that follow it, preserving their relative order.
789    /// **This perturbs the index of all of those elements!**
790    ///
791    /// Return `None` if `value` was not in the set.
792    pub fn shift_remove_full<Q>(&mut self, value: &Q) -> Option<(usize, T)>
793    where
794        Q: ?Sized + Hash + Equivalent<T>,
795    {
796        self.map.shift_remove_full(value).map(|(i, x, ())| (i, x))
797    }
798}
799
800impl<T, S> IndexSet<T, S> {
801    /// Remove the last value
802    ///
803    /// This preserves the order of the remaining elements.
804    ///
805    /// Computes in **O(1)** time (average).
806    #[doc(alias = "pop_last")] // like `BTreeSet`
807    pub fn pop(&mut self) -> Option<T> {
808        self.map.pop().map(|(x, ())| x)
809    }
810
811    /// Scan through each value in the set and keep those where the
812    /// closure `keep` returns `true`.
813    ///
814    /// The elements are visited in order, and remaining elements keep their
815    /// order.
816    ///
817    /// Computes in **O(n)** time (average).
818    pub fn retain<F>(&mut self, mut keep: F)
819    where
820        F: FnMut(&T) -> bool,
821    {
822        self.map.retain(move |x, &mut ()| keep(x))
823    }
824
825    /// Sort the set’s values by their default ordering.
826    ///
827    /// This is a stable sort -- but equivalent values should not normally coexist in
828    /// a set at all, so [`sort_unstable`][Self::sort_unstable] is preferred
829    /// because it is generally faster and doesn't allocate auxiliary memory.
830    ///
831    /// See [`sort_by`](Self::sort_by) for details.
832    pub fn sort(&mut self)
833    where
834        T: Ord,
835    {
836        self.map.sort_keys()
837    }
838
839    /// Sort the set’s values in place using the comparison function `cmp`.
840    ///
841    /// Computes in **O(n log n)** time and **O(n)** space. The sort is stable.
842    pub fn sort_by<F>(&mut self, mut cmp: F)
843    where
844        F: FnMut(&T, &T) -> Ordering,
845    {
846        self.map.sort_by(move |a, _, b, _| cmp(a, b));
847    }
848
849    /// Sort the values of the set and return a by-value iterator of
850    /// the values with the result.
851    ///
852    /// The sort is stable.
853    pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<T>
854    where
855        F: FnMut(&T, &T) -> Ordering,
856    {
857        let mut entries = self.into_entries();
858        entries.sort_by(move |a, b| cmp(&a.key, &b.key));
859        IntoIter::new(entries)
860    }
861
862    /// Sort the set's values by their default ordering.
863    ///
864    /// See [`sort_unstable_by`](Self::sort_unstable_by) for details.
865    pub fn sort_unstable(&mut self)
866    where
867        T: Ord,
868    {
869        self.map.sort_unstable_keys()
870    }
871
872    /// Sort the set's values in place using the comparison function `cmp`.
873    ///
874    /// Computes in **O(n log n)** time. The sort is unstable.
875    pub fn sort_unstable_by<F>(&mut self, mut cmp: F)
876    where
877        F: FnMut(&T, &T) -> Ordering,
878    {
879        self.map.sort_unstable_by(move |a, _, b, _| cmp(a, b))
880    }
881
882    /// Sort the values of the set and return a by-value iterator of
883    /// the values with the result.
884    pub fn sorted_unstable_by<F>(self, mut cmp: F) -> IntoIter<T>
885    where
886        F: FnMut(&T, &T) -> Ordering,
887    {
888        let mut entries = self.into_entries();
889        entries.sort_unstable_by(move |a, b| cmp(&a.key, &b.key));
890        IntoIter::new(entries)
891    }
892
893    /// Sort the set’s values in place using a key extraction function.
894    ///
895    /// During sorting, the function is called at most once per entry, by using temporary storage
896    /// to remember the results of its evaluation. The order of calls to the function is
897    /// unspecified and may change between versions of `indexmap` or the standard library.
898    ///
899    /// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is
900    /// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable.
901    pub fn sort_by_cached_key<K, F>(&mut self, mut sort_key: F)
902    where
903        K: Ord,
904        F: FnMut(&T) -> K,
905    {
906        self.with_entries(move |entries| {
907            entries.sort_by_cached_key(move |a| sort_key(&a.key));
908        });
909    }
910
911    /// Search over a sorted set for a value.
912    ///
913    /// Returns the position where that value is present, or the position where it can be inserted
914    /// to maintain the sort. See [`slice::binary_search`] for more details.
915    ///
916    /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up
917    /// using [`get_index_of`][IndexSet::get_index_of], but this can also position missing values.
918    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
919    where
920        T: Ord,
921    {
922        self.as_slice().binary_search(x)
923    }
924
925    /// Search over a sorted set with a comparator function.
926    ///
927    /// Returns the position where that value is present, or the position where it can be inserted
928    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
929    ///
930    /// Computes in **O(log(n))** time.
931    #[inline]
932    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
933    where
934        F: FnMut(&'a T) -> Ordering,
935    {
936        self.as_slice().binary_search_by(f)
937    }
938
939    /// Search over a sorted set with an extraction function.
940    ///
941    /// Returns the position where that value is present, or the position where it can be inserted
942    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
943    ///
944    /// Computes in **O(log(n))** time.
945    #[inline]
946    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
947    where
948        F: FnMut(&'a T) -> B,
949        B: Ord,
950    {
951        self.as_slice().binary_search_by_key(b, f)
952    }
953
954    /// Returns the index of the partition point of a sorted set according to the given predicate
955    /// (the index of the first element of the second partition).
956    ///
957    /// See [`slice::partition_point`] for more details.
958    ///
959    /// Computes in **O(log(n))** time.
960    #[must_use]
961    pub fn partition_point<P>(&self, pred: P) -> usize
962    where
963        P: FnMut(&T) -> bool,
964    {
965        self.as_slice().partition_point(pred)
966    }
967
968    /// Reverses the order of the set’s values in place.
969    ///
970    /// Computes in **O(n)** time and **O(1)** space.
971    pub fn reverse(&mut self) {
972        self.map.reverse()
973    }
974
975    /// Returns a slice of all the values in the set.
976    ///
977    /// Computes in **O(1)** time.
978    pub fn as_slice(&self) -> &Slice<T> {
979        Slice::from_slice(self.as_entries())
980    }
981
982    /// Converts into a boxed slice of all the values in the set.
983    ///
984    /// Note that this will drop the inner hash table and any excess capacity.
985    pub fn into_boxed_slice(self) -> Box<Slice<T>> {
986        Slice::from_boxed(self.into_entries().into_boxed_slice())
987    }
988
989    /// Get a value by index
990    ///
991    /// Valid indices are `0 <= index < self.len()`.
992    ///
993    /// Computes in **O(1)** time.
994    pub fn get_index(&self, index: usize) -> Option<&T> {
995        self.as_entries().get(index).map(Bucket::key_ref)
996    }
997
998    /// Returns a slice of values in the given range of indices.
999    ///
1000    /// Valid indices are `0 <= index < self.len()`.
1001    ///
1002    /// Computes in **O(1)** time.
1003    pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<T>> {
1004        let entries = self.as_entries();
1005        let range = try_simplify_range(range, entries.len())?;
1006        entries.get(range).map(Slice::from_slice)
1007    }
1008
1009    /// Get the first value
1010    ///
1011    /// Computes in **O(1)** time.
1012    pub fn first(&self) -> Option<&T> {
1013        self.as_entries().first().map(Bucket::key_ref)
1014    }
1015
1016    /// Get the last value
1017    ///
1018    /// Computes in **O(1)** time.
1019    pub fn last(&self) -> Option<&T> {
1020        self.as_entries().last().map(Bucket::key_ref)
1021    }
1022
1023    /// Remove the value by index
1024    ///
1025    /// Valid indices are `0 <= index < self.len()`.
1026    ///
1027    /// Like [`Vec::swap_remove`], the value is removed by swapping it with the
1028    /// last element of the set and popping it off. **This perturbs
1029    /// the position of what used to be the last element!**
1030    ///
1031    /// Computes in **O(1)** time (average).
1032    pub fn swap_remove_index(&mut self, index: usize) -> Option<T> {
1033        self.map.swap_remove_index(index).map(|(x, ())| x)
1034    }
1035
1036    /// Remove the value by index
1037    ///
1038    /// Valid indices are `0 <= index < self.len()`.
1039    ///
1040    /// Like [`Vec::remove`], the value is removed by shifting all of the
1041    /// elements that follow it, preserving their relative order.
1042    /// **This perturbs the index of all of those elements!**
1043    ///
1044    /// Computes in **O(n)** time (average).
1045    pub fn shift_remove_index(&mut self, index: usize) -> Option<T> {
1046        self.map.shift_remove_index(index).map(|(x, ())| x)
1047    }
1048
1049    /// Moves the position of a value from one index to another
1050    /// by shifting all other values in-between.
1051    ///
1052    /// * If `from < to`, the other values will shift down while the targeted value moves up.
1053    /// * If `from > to`, the other values will shift up while the targeted value moves down.
1054    ///
1055    /// ***Panics*** if `from` or `to` are out of bounds.
1056    ///
1057    /// Computes in **O(n)** time (average).
1058    #[track_caller]
1059    pub fn move_index(&mut self, from: usize, to: usize) {
1060        self.map.move_index(from, to)
1061    }
1062
1063    /// Swaps the position of two values in the set.
1064    ///
1065    /// ***Panics*** if `a` or `b` are out of bounds.
1066    ///
1067    /// Computes in **O(1)** time (average).
1068    #[track_caller]
1069    pub fn swap_indices(&mut self, a: usize, b: usize) {
1070        self.map.swap_indices(a, b)
1071    }
1072}
1073
1074/// Access [`IndexSet`] values at indexed positions.
1075///
1076/// # Examples
1077///
1078/// ```
1079/// use indexmap::IndexSet;
1080///
1081/// let mut set = IndexSet::new();
1082/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1083///     set.insert(word.to_string());
1084/// }
1085/// assert_eq!(set[0], "Lorem");
1086/// assert_eq!(set[1], "ipsum");
1087/// set.reverse();
1088/// assert_eq!(set[0], "amet");
1089/// assert_eq!(set[1], "sit");
1090/// set.sort();
1091/// assert_eq!(set[0], "Lorem");
1092/// assert_eq!(set[1], "amet");
1093/// ```
1094///
1095/// ```should_panic
1096/// use indexmap::IndexSet;
1097///
1098/// let mut set = IndexSet::new();
1099/// set.insert("foo");
1100/// println!("{:?}", set[10]); // panics!
1101/// ```
1102impl<T, S> Index<usize> for IndexSet<T, S> {
1103    type Output = T;
1104
1105    /// Returns a reference to the value at the supplied `index`.
1106    ///
1107    /// ***Panics*** if `index` is out of bounds.
1108    fn index(&self, index: usize) -> &T {
1109        self.get_index(index).unwrap_or_else(|| {
1110            panic!(
1111                "index out of bounds: the len is {len} but the index is {index}",
1112                len = self.len()
1113            );
1114        })
1115    }
1116}
1117
1118impl<T, S> FromIterator<T> for IndexSet<T, S>
1119where
1120    T: Hash + Eq,
1121    S: BuildHasher + Default,
1122{
1123    fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Self {
1124        let iter = iterable.into_iter().map(|x| (x, ()));
1125        IndexSet {
1126            map: IndexMap::from_iter(iter),
1127        }
1128    }
1129}
1130
1131#[cfg(feature = "std")]
1132#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1133impl<T, const N: usize> From<[T; N]> for IndexSet<T, RandomState>
1134where
1135    T: Eq + Hash,
1136{
1137    /// # Examples
1138    ///
1139    /// ```
1140    /// use indexmap::IndexSet;
1141    ///
1142    /// let set1 = IndexSet::from([1, 2, 3, 4]);
1143    /// let set2: IndexSet<_> = [1, 2, 3, 4].into();
1144    /// assert_eq!(set1, set2);
1145    /// ```
1146    fn from(arr: [T; N]) -> Self {
1147        Self::from_iter(arr)
1148    }
1149}
1150
1151impl<T, S> Extend<T> for IndexSet<T, S>
1152where
1153    T: Hash + Eq,
1154    S: BuildHasher,
1155{
1156    fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1157        let iter = iterable.into_iter().map(|x| (x, ()));
1158        self.map.extend(iter);
1159    }
1160}
1161
1162impl<'a, T, S> Extend<&'a T> for IndexSet<T, S>
1163where
1164    T: Hash + Eq + Copy + 'a,
1165    S: BuildHasher,
1166{
1167    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iterable: I) {
1168        let iter = iterable.into_iter().copied();
1169        self.extend(iter);
1170    }
1171}
1172
1173impl<T, S> Default for IndexSet<T, S>
1174where
1175    S: Default,
1176{
1177    /// Return an empty [`IndexSet`]
1178    fn default() -> Self {
1179        IndexSet {
1180            map: IndexMap::default(),
1181        }
1182    }
1183}
1184
1185impl<T, S1, S2> PartialEq<IndexSet<T, S2>> for IndexSet<T, S1>
1186where
1187    T: Hash + Eq,
1188    S1: BuildHasher,
1189    S2: BuildHasher,
1190{
1191    fn eq(&self, other: &IndexSet<T, S2>) -> bool {
1192        self.len() == other.len() && self.is_subset(other)
1193    }
1194}
1195
1196impl<T, S> Eq for IndexSet<T, S>
1197where
1198    T: Eq + Hash,
1199    S: BuildHasher,
1200{
1201}
1202
1203impl<T, S> IndexSet<T, S>
1204where
1205    T: Eq + Hash,
1206    S: BuildHasher,
1207{
1208    /// Returns `true` if `self` has no elements in common with `other`.
1209    pub fn is_disjoint<S2>(&self, other: &IndexSet<T, S2>) -> bool
1210    where
1211        S2: BuildHasher,
1212    {
1213        if self.len() <= other.len() {
1214            self.iter().all(move |value| !other.contains(value))
1215        } else {
1216            other.iter().all(move |value| !self.contains(value))
1217        }
1218    }
1219
1220    /// Returns `true` if all elements of `self` are contained in `other`.
1221    pub fn is_subset<S2>(&self, other: &IndexSet<T, S2>) -> bool
1222    where
1223        S2: BuildHasher,
1224    {
1225        self.len() <= other.len() && self.iter().all(move |value| other.contains(value))
1226    }
1227
1228    /// Returns `true` if all elements of `other` are contained in `self`.
1229    pub fn is_superset<S2>(&self, other: &IndexSet<T, S2>) -> bool
1230    where
1231        S2: BuildHasher,
1232    {
1233        other.is_subset(self)
1234    }
1235}
1236
1237impl<T, S1, S2> BitAnd<&IndexSet<T, S2>> for &IndexSet<T, S1>
1238where
1239    T: Eq + Hash + Clone,
1240    S1: BuildHasher + Default,
1241    S2: BuildHasher,
1242{
1243    type Output = IndexSet<T, S1>;
1244
1245    /// Returns the set intersection, cloned into a new set.
1246    ///
1247    /// Values are collected in the same order that they appear in `self`.
1248    fn bitand(self, other: &IndexSet<T, S2>) -> Self::Output {
1249        self.intersection(other).cloned().collect()
1250    }
1251}
1252
1253impl<T, S1, S2> BitOr<&IndexSet<T, S2>> for &IndexSet<T, S1>
1254where
1255    T: Eq + Hash + Clone,
1256    S1: BuildHasher + Default,
1257    S2: BuildHasher,
1258{
1259    type Output = IndexSet<T, S1>;
1260
1261    /// Returns the set union, cloned into a new set.
1262    ///
1263    /// Values from `self` are collected in their original order, followed by
1264    /// values that are unique to `other` in their original order.
1265    fn bitor(self, other: &IndexSet<T, S2>) -> Self::Output {
1266        self.union(other).cloned().collect()
1267    }
1268}
1269
1270impl<T, S1, S2> BitXor<&IndexSet<T, S2>> for &IndexSet<T, S1>
1271where
1272    T: Eq + Hash + Clone,
1273    S1: BuildHasher + Default,
1274    S2: BuildHasher,
1275{
1276    type Output = IndexSet<T, S1>;
1277
1278    /// Returns the set symmetric-difference, cloned into a new set.
1279    ///
1280    /// Values from `self` are collected in their original order, followed by
1281    /// values from `other` in their original order.
1282    fn bitxor(self, other: &IndexSet<T, S2>) -> Self::Output {
1283        self.symmetric_difference(other).cloned().collect()
1284    }
1285}
1286
1287impl<T, S1, S2> Sub<&IndexSet<T, S2>> for &IndexSet<T, S1>
1288where
1289    T: Eq + Hash + Clone,
1290    S1: BuildHasher + Default,
1291    S2: BuildHasher,
1292{
1293    type Output = IndexSet<T, S1>;
1294
1295    /// Returns the set difference, cloned into a new set.
1296    ///
1297    /// Values are collected in the same order that they appear in `self`.
1298    fn sub(self, other: &IndexSet<T, S2>) -> Self::Output {
1299        self.difference(other).cloned().collect()
1300    }
1301}