Skip to main content

indexmap/
set.rs

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