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