indexmap_amortized/
set.rs

1//! A hash set implemented using `IndexMap`
2
3#[cfg(feature = "rayon")]
4pub use crate::rayon::set as rayon;
5
6#[cfg(has_std)]
7use std::collections::hash_map::RandomState;
8
9use crate::EntryVec;
10use core::cmp::Ordering;
11use core::fmt;
12use core::hash::{BuildHasher, Hash};
13use core::iter::{Chain, FromIterator};
14use core::ops::{BitAnd, BitOr, BitXor, Index, RangeBounds, Sub};
15
16use super::{Entries, Equivalent, IndexMap};
17
18type Bucket<T> = super::Bucket<T, ()>;
19
20/// A hash set where the iteration order of the values is independent of their
21/// hash values.
22///
23/// The interface is closely compatible with the standard `HashSet`, but also
24/// has additional features.
25///
26/// # Order
27///
28/// The values have a consistent order that is determined by the sequence of
29/// insertion and removal calls on the set. The order does not depend on the
30/// values or the hash function at all. Note that insertion order and value
31/// are not affected if a re-insertion is attempted once an element is
32/// already present.
33///
34/// All iterators traverse the set *in order*.  Set operation iterators like
35/// `union` produce a concatenated order, as do their matching "bitwise"
36/// operators.  See their documentation for specifics.
37///
38/// The insertion order is preserved, with **notable exceptions** like the
39/// `.remove()` or `.swap_remove()` methods. Methods such as `.sort_by()` of
40/// course result in a new order, depending on the sorting order.
41///
42/// # Indices
43///
44/// The values are indexed in a compact range without holes in the range
45/// `0..self.len()`. For example, the method `.get_full` looks up the index for
46/// a value, and the method `.get_index` looks up the value by index.
47///
48/// # Examples
49///
50/// ```
51/// use indexmap_amortized::IndexSet;
52///
53/// // Collects which letters appear in a sentence.
54/// let letters: IndexSet<_> = "a short treatise on fungi".chars().collect();
55///
56/// assert!(letters.contains(&'s'));
57/// assert!(letters.contains(&'t'));
58/// assert!(letters.contains(&'u'));
59/// assert!(!letters.contains(&'y'));
60/// ```
61#[cfg(has_std)]
62pub struct IndexSet<T, S = RandomState> {
63    map: IndexMap<T, (), S>,
64}
65#[cfg(not(has_std))]
66pub struct IndexSet<T, S> {
67    map: IndexMap<T, (), S>,
68}
69
70impl<T, S> Clone for IndexSet<T, S>
71where
72    T: Clone,
73    S: Clone,
74{
75    fn clone(&self) -> Self {
76        IndexSet {
77            map: self.map.clone(),
78        }
79    }
80
81    fn clone_from(&mut self, other: &Self) {
82        self.map.clone_from(&other.map);
83    }
84}
85
86impl<T, S> Entries for IndexSet<T, S> {
87    type Entry = Bucket<T>;
88
89    #[inline]
90    fn into_entries(self) -> EntryVec<Self::Entry> {
91        self.map.into_entries()
92    }
93
94    #[inline]
95    fn as_entries(&self) -> &EntryVec<Self::Entry> {
96        self.map.as_entries()
97    }
98
99    #[inline]
100    fn as_entries_mut(&mut self) -> &mut EntryVec<Self::Entry> {
101        self.map.as_entries_mut()
102    }
103
104    fn with_entries<F>(&mut self, f: F)
105    where
106        F: FnOnce(&mut EntryVec<Self::Entry>),
107    {
108        self.map.with_entries(f);
109    }
110}
111
112impl<T, S> fmt::Debug for IndexSet<T, S>
113where
114    T: fmt::Debug,
115{
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        if cfg!(not(feature = "test_debug")) {
118            f.debug_set().entries(self.iter()).finish()
119        } else {
120            // Let the inner `IndexMap` print all of its details
121            f.debug_struct("IndexSet").field("map", &self.map).finish()
122        }
123    }
124}
125
126#[cfg(has_std)]
127impl<T> IndexSet<T> {
128    /// Create a new set. (Does not allocate.)
129    pub fn new() -> Self {
130        IndexSet {
131            map: IndexMap::new(),
132        }
133    }
134
135    /// Create a new set with capacity for `n` elements.
136    /// (Does not allocate if `n` is zero.)
137    ///
138    /// Computes in **O(n)** time.
139    pub fn with_capacity(n: usize) -> Self {
140        IndexSet {
141            map: IndexMap::with_capacity(n),
142        }
143    }
144}
145
146impl<T, S> IndexSet<T, S> {
147    /// Create a new set with capacity for `n` elements.
148    /// (Does not allocate if `n` is zero.)
149    ///
150    /// Computes in **O(n)** time.
151    pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self {
152        IndexSet {
153            map: IndexMap::with_capacity_and_hasher(n, hash_builder),
154        }
155    }
156
157    /// Create a new set with `hash_builder`
158    pub fn with_hasher(hash_builder: S) -> Self {
159        IndexSet {
160            map: IndexMap::with_hasher(hash_builder),
161        }
162    }
163
164    /// Computes in **O(1)** time.
165    pub fn capacity(&self) -> usize {
166        self.map.capacity()
167    }
168
169    /// Return a reference to the set's `BuildHasher`.
170    pub fn hasher(&self) -> &S {
171        self.map.hasher()
172    }
173
174    /// Return the number of elements in the set.
175    ///
176    /// Computes in **O(1)** time.
177    pub fn len(&self) -> usize {
178        self.map.len()
179    }
180
181    /// Returns true if the set contains no elements.
182    ///
183    /// Computes in **O(1)** time.
184    pub fn is_empty(&self) -> bool {
185        self.map.is_empty()
186    }
187
188    /// Return an iterator over the values of the set, in their order
189    pub fn iter(&self) -> Iter<'_, T> {
190        Iter {
191            iter: self.map.keys().iter,
192        }
193    }
194
195    /// Remove all elements in the set, while preserving its capacity.
196    ///
197    /// Computes in **O(n)** time.
198    pub fn clear(&mut self) {
199        self.map.clear();
200    }
201
202    /// Shortens the set, keeping the first `len` elements and dropping the rest.
203    ///
204    /// If `len` is greater than the set's current length, this has no effect.
205    pub fn truncate(&mut self, len: usize) {
206        self.map.truncate(len);
207    }
208
209    /// Clears the `IndexSet` in the given index range, returning those values
210    /// as a drain iterator.
211    ///
212    /// The range may be any type that implements `RangeBounds<usize>`,
213    /// including all of the `std::ops::Range*` types, or even a tuple pair of
214    /// `Bound` start and end values. To drain the set entirely, use `RangeFull`
215    /// like `set.drain(..)`.
216    ///
217    /// This shifts down all entries following the drained range to fill the
218    /// gap, and keeps the allocated memory for reuse.
219    ///
220    /// ***Panics*** if the starting point is greater than the end point or if
221    /// the end point is greater than the length of the set.
222    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
223    where
224        R: RangeBounds<usize>,
225    {
226        Drain {
227            iter: self.map.drain(range).iter,
228        }
229    }
230
231    /// Splits the collection into two at the given index.
232    ///
233    /// Returns a newly allocated set containing the elements in the range
234    /// `[at, len)`. After the call, the original set will be left containing
235    /// the elements `[0, at)` with its previous capacity unchanged.
236    ///
237    /// ***Panics*** if `at > len`.
238    pub fn split_off(&mut self, at: usize) -> Self
239    where
240        S: Clone,
241    {
242        Self {
243            map: self.map.split_off(at),
244        }
245    }
246}
247
248impl<T, S> IndexSet<T, S>
249where
250    T: Hash + Eq,
251    S: BuildHasher,
252{
253    /// Reserve capacity for `additional` more values.
254    ///
255    /// Computes in **O(n)** time.
256    pub fn reserve(&mut self, additional: usize) {
257        self.map.reserve(additional);
258    }
259
260    /// Shrink the capacity of the set as much as possible.
261    ///
262    /// Computes in **O(n)** time.
263    pub fn shrink_to_fit(&mut self) {
264        self.map.shrink_to_fit();
265    }
266
267    /// Insert the value into the set.
268    ///
269    /// If an equivalent item already exists in the set, it returns
270    /// `false` leaving the original value in the set and without
271    /// altering its insertion order. Otherwise, it inserts the new
272    /// item and returns `true`.
273    ///
274    /// Computes in **O(1)** time (amortized average).
275    pub fn insert(&mut self, value: T) -> bool {
276        self.map.insert(value, ()).is_none()
277    }
278
279    /// Insert the value into the set, and get its index.
280    ///
281    /// If an equivalent item already exists in the set, it returns
282    /// the index of the existing item and `false`, leaving the
283    /// original value in the set and without altering its insertion
284    /// order. Otherwise, it inserts the new item and returns the index
285    /// of the inserted item and `true`.
286    ///
287    /// Computes in **O(1)** time (amortized average).
288    pub fn insert_full(&mut self, value: T) -> (usize, bool) {
289        use super::map::Entry::*;
290
291        match self.map.entry(value) {
292            Occupied(e) => (e.index(), false),
293            Vacant(e) => {
294                let index = e.index();
295                e.insert(());
296                (index, true)
297            }
298        }
299    }
300
301    /// Return an iterator over the values that are in `self` but not `other`.
302    ///
303    /// Values are produced in the same order that they appear in `self`.
304    pub fn difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Difference<'a, T, S2>
305    where
306        S2: BuildHasher,
307    {
308        Difference {
309            iter: self.iter(),
310            other,
311        }
312    }
313
314    /// Return an iterator over the values that are in `self` or `other`,
315    /// but not in both.
316    ///
317    /// Values from `self` are produced in their original order, followed by
318    /// values from `other` in their original order.
319    pub fn symmetric_difference<'a, S2>(
320        &'a self,
321        other: &'a IndexSet<T, S2>,
322    ) -> SymmetricDifference<'a, T, S, S2>
323    where
324        S2: BuildHasher,
325    {
326        SymmetricDifference {
327            iter: self.difference(other).chain(other.difference(self)),
328        }
329    }
330
331    /// Return an iterator over the values that are in both `self` and `other`.
332    ///
333    /// Values are produced in the same order that they appear in `self`.
334    pub fn intersection<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Intersection<'a, T, S2>
335    where
336        S2: BuildHasher,
337    {
338        Intersection {
339            iter: self.iter(),
340            other,
341        }
342    }
343
344    /// Return an iterator over all values that are in `self` or `other`.
345    ///
346    /// Values from `self` are produced in their original order, followed by
347    /// values that are unique to `other` in their original order.
348    pub fn union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Union<'a, T, S>
349    where
350        S2: BuildHasher,
351    {
352        Union {
353            iter: self.iter().chain(other.difference(self)),
354        }
355    }
356
357    /// Return `true` if an equivalent to `value` exists in the set.
358    ///
359    /// Computes in **O(1)** time (average).
360    pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
361    where
362        Q: Hash + Equivalent<T>,
363    {
364        self.map.contains_key(value)
365    }
366
367    /// Return a reference to the value stored in the set, if it is present,
368    /// else `None`.
369    ///
370    /// Computes in **O(1)** time (average).
371    pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
372    where
373        Q: Hash + Equivalent<T>,
374    {
375        self.map.get_key_value(value).map(|(x, &())| x)
376    }
377
378    /// Return item index and value
379    pub fn get_full<Q: ?Sized>(&self, value: &Q) -> Option<(usize, &T)>
380    where
381        Q: Hash + Equivalent<T>,
382    {
383        self.map.get_full(value).map(|(i, x, &())| (i, x))
384    }
385
386    /// Return item index, if it exists in the set
387    pub fn get_index_of<Q: ?Sized>(&self, value: &Q) -> Option<usize>
388    where
389        Q: Hash + Equivalent<T>,
390    {
391        self.map.get_index_of(value)
392    }
393
394    /// Adds a value to the set, replacing the existing value, if any, that is
395    /// equal to the given one. Returns the replaced value.
396    ///
397    /// Computes in **O(1)** time (average).
398    pub fn replace(&mut self, value: T) -> Option<T> {
399        use super::map::Entry::*;
400
401        match self.map.entry(value) {
402            Vacant(e) => {
403                e.insert(());
404                None
405            }
406            Occupied(e) => Some(e.replace_key()),
407        }
408    }
409
410    /// Remove the value from the set, and return `true` if it was present.
411    ///
412    /// **NOTE:** This is equivalent to `.swap_remove(value)`, if you want
413    /// to preserve the order of the values in the set, use `.shift_remove(value)`.
414    ///
415    /// Computes in **O(1)** time (average).
416    pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
417    where
418        Q: Hash + Equivalent<T>,
419    {
420        self.swap_remove(value)
421    }
422
423    /// Remove the value from the set, and return `true` if it was present.
424    ///
425    /// Like `Vec::swap_remove`, the value is removed by swapping it with the
426    /// last element of the set and popping it off. **This perturbs
427    /// the postion of what used to be the last element!**
428    ///
429    /// Return `false` if `value` was not in the set.
430    ///
431    /// Computes in **O(1)** time (average).
432    pub fn swap_remove<Q: ?Sized>(&mut self, value: &Q) -> bool
433    where
434        Q: Hash + Equivalent<T>,
435    {
436        self.map.swap_remove(value).is_some()
437    }
438
439    /// Remove the value from the set, and return `true` if it was present.
440    ///
441    /// Like `Vec::remove`, the value is removed by shifting all of the
442    /// elements that follow it, preserving their relative order.
443    /// **This perturbs the index of all of those elements!**
444    ///
445    /// Return `false` if `value` was not in the set.
446    ///
447    /// Computes in **O(n)** time (average).
448    pub fn shift_remove<Q: ?Sized>(&mut self, value: &Q) -> bool
449    where
450        Q: Hash + Equivalent<T>,
451    {
452        self.map.shift_remove(value).is_some()
453    }
454
455    /// Removes and returns the value in the set, if any, that is equal to the
456    /// given one.
457    ///
458    /// **NOTE:** This is equivalent to `.swap_take(value)`, if you need to
459    /// preserve the order of the values in the set, use `.shift_take(value)`
460    /// instead.
461    ///
462    /// Computes in **O(1)** time (average).
463    pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
464    where
465        Q: Hash + Equivalent<T>,
466    {
467        self.swap_take(value)
468    }
469
470    /// Removes and returns the value in the set, if any, that is equal to the
471    /// given one.
472    ///
473    /// Like `Vec::swap_remove`, the value is removed by swapping it with the
474    /// last element of the set and popping it off. **This perturbs
475    /// the postion of what used to be the last element!**
476    ///
477    /// Return `None` if `value` was not in the set.
478    ///
479    /// Computes in **O(1)** time (average).
480    pub fn swap_take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
481    where
482        Q: Hash + Equivalent<T>,
483    {
484        self.map.swap_remove_entry(value).map(|(x, ())| x)
485    }
486
487    /// Removes and returns the value in the set, if any, that is equal to the
488    /// given one.
489    ///
490    /// Like `Vec::remove`, the value is removed by shifting all of the
491    /// elements that follow it, preserving their relative order.
492    /// **This perturbs the index of all of those elements!**
493    ///
494    /// Return `None` if `value` was not in the set.
495    ///
496    /// Computes in **O(n)** time (average).
497    pub fn shift_take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
498    where
499        Q: Hash + Equivalent<T>,
500    {
501        self.map.shift_remove_entry(value).map(|(x, ())| x)
502    }
503
504    /// Remove the value from the set return it and the index it had.
505    ///
506    /// Like `Vec::swap_remove`, the value is removed by swapping it with the
507    /// last element of the set and popping it off. **This perturbs
508    /// the postion of what used to be the last element!**
509    ///
510    /// Return `None` if `value` was not in the set.
511    pub fn swap_remove_full<Q: ?Sized>(&mut self, value: &Q) -> Option<(usize, T)>
512    where
513        Q: Hash + Equivalent<T>,
514    {
515        self.map.swap_remove_full(value).map(|(i, x, ())| (i, x))
516    }
517
518    /// Remove the value from the set return it and the index it had.
519    ///
520    /// Like `Vec::remove`, the value is removed by shifting all of the
521    /// elements that follow it, preserving their relative order.
522    /// **This perturbs the index of all of those elements!**
523    ///
524    /// Return `None` if `value` was not in the set.
525    pub fn shift_remove_full<Q: ?Sized>(&mut self, value: &Q) -> Option<(usize, T)>
526    where
527        Q: Hash + Equivalent<T>,
528    {
529        self.map.shift_remove_full(value).map(|(i, x, ())| (i, x))
530    }
531
532    /// Remove the last value
533    ///
534    /// Computes in **O(1)** time (average).
535    pub fn pop(&mut self) -> Option<T> {
536        self.map.pop().map(|(x, ())| x)
537    }
538
539    /// Scan through each value in the set and keep those where the
540    /// closure `keep` returns `true`.
541    ///
542    /// The elements are visited in order, and remaining elements keep their
543    /// order.
544    ///
545    /// Computes in **O(n)** time (average).
546    pub fn retain<F>(&mut self, mut keep: F)
547    where
548        F: FnMut(&T) -> bool,
549    {
550        self.map.retain(move |x, &mut ()| keep(x))
551    }
552
553    /// Sort the set’s values by their default ordering.
554    ///
555    /// See `sort_by` for details.
556    pub fn sort(&mut self)
557    where
558        T: Ord,
559    {
560        self.map.sort_keys()
561    }
562
563    /// Sort the set’s values in place using the comparison function `compare`.
564    ///
565    /// Computes in **O(n log n)** time and **O(n)** space. The sort is stable.
566    pub fn sort_by<F>(&mut self, mut compare: F)
567    where
568        F: FnMut(&T, &T) -> Ordering,
569    {
570        self.map.sort_by(move |a, _, b, _| compare(a, b));
571    }
572
573    /// Sort the values of the set and return a by value iterator of
574    /// the values with the result.
575    ///
576    /// The sort is stable.
577    pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<T>
578    where
579        F: FnMut(&T, &T) -> Ordering,
580    {
581        IntoIter {
582            iter: self.map.sorted_by(move |a, &(), b, &()| cmp(a, b)).iter,
583        }
584    }
585
586    /// Reverses the order of the set’s values in place.
587    ///
588    /// Computes in **O(n)** time and **O(1)** space.
589    pub fn reverse(&mut self) {
590        self.map.reverse()
591    }
592}
593
594impl<T, S> IndexSet<T, S> {
595    /// Get a value by index
596    ///
597    /// Valid indices are *0 <= index < self.len()*
598    ///
599    /// Computes in **O(1)** time.
600    pub fn get_index(&self, index: usize) -> Option<&T> {
601        self.as_entries().get(index).map(Bucket::key_ref)
602    }
603
604    /// Get the first value
605    ///
606    /// Computes in **O(1)** time.
607    pub fn first(&self) -> Option<&T> {
608        self.as_entries().first().map(Bucket::key_ref)
609    }
610
611    /// Get the last value
612    ///
613    /// Computes in **O(1)** time.
614    pub fn last(&self) -> Option<&T> {
615        self.as_entries().last().map(Bucket::key_ref)
616    }
617
618    /// Remove the value by index
619    ///
620    /// Valid indices are *0 <= index < self.len()*
621    ///
622    /// Like `Vec::swap_remove`, the value is removed by swapping it with the
623    /// last element of the set and popping it off. **This perturbs
624    /// the postion of what used to be the last element!**
625    ///
626    /// Computes in **O(1)** time (average).
627    pub fn swap_remove_index(&mut self, index: usize) -> Option<T> {
628        self.map.swap_remove_index(index).map(|(x, ())| x)
629    }
630
631    /// Remove the value by index
632    ///
633    /// Valid indices are *0 <= index < self.len()*
634    ///
635    /// Like `Vec::remove`, the value is removed by shifting all of the
636    /// elements that follow it, preserving their relative order.
637    /// **This perturbs the index of all of those elements!**
638    ///
639    /// Computes in **O(n)** time (average).
640    pub fn shift_remove_index(&mut self, index: usize) -> Option<T> {
641        self.map.shift_remove_index(index).map(|(x, ())| x)
642    }
643
644    /// Swaps the position of two values in the set.
645    ///
646    /// ***Panics*** if `a` or `b` are out of bounds.
647    pub fn swap_indices(&mut self, a: usize, b: usize) {
648        self.map.swap_indices(a, b)
649    }
650}
651
652/// Access `IndexSet` values at indexed positions.
653///
654/// # Examples
655///
656/// ```
657/// use indexmap_amortized::IndexSet;
658///
659/// let mut set = IndexSet::new();
660/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
661///     set.insert(word.to_string());
662/// }
663/// assert_eq!(set[0], "Lorem");
664/// assert_eq!(set[1], "ipsum");
665/// set.reverse();
666/// assert_eq!(set[0], "amet");
667/// assert_eq!(set[1], "sit");
668/// set.sort();
669/// assert_eq!(set[0], "Lorem");
670/// assert_eq!(set[1], "amet");
671/// ```
672///
673/// ```should_panic
674/// use indexmap_amortized::IndexSet;
675///
676/// let mut set = IndexSet::new();
677/// set.insert("foo");
678/// println!("{:?}", set[10]); // panics!
679/// ```
680impl<T, S> Index<usize> for IndexSet<T, S> {
681    type Output = T;
682
683    /// Returns a reference to the value at the supplied `index`.
684    ///
685    /// ***Panics*** if `index` is out of bounds.
686    fn index(&self, index: usize) -> &T {
687        self.get_index(index)
688            .expect("IndexSet: index out of bounds")
689    }
690}
691
692/// An owning iterator over the items of a `IndexSet`.
693///
694/// This `struct` is created by the [`into_iter`] method on [`IndexSet`]
695/// (provided by the `IntoIterator` trait). See its documentation for more.
696///
697/// [`IndexSet`]: struct.IndexSet.html
698/// [`into_iter`]: struct.IndexSet.html#method.into_iter
699pub struct IntoIter<T> {
700    iter: <EntryVec<Bucket<T>> as IntoIterator>::IntoIter,
701}
702
703impl<T> Iterator for IntoIter<T> {
704    type Item = T;
705
706    iterator_methods!(Bucket::key);
707}
708
709impl<T> DoubleEndedIterator for IntoIter<T> {
710    fn next_back(&mut self) -> Option<Self::Item> {
711        self.iter.next_back().map(Bucket::key)
712    }
713}
714
715impl<T> ExactSizeIterator for IntoIter<T> {
716    fn len(&self) -> usize {
717        self.iter.len()
718    }
719}
720
721impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        f.debug_struct("IntoIter").finish()
724    }
725}
726
727/// An iterator over the items of a `IndexSet`.
728///
729/// This `struct` is created by the [`iter`] method on [`IndexSet`].
730/// See its documentation for more.
731///
732/// [`IndexSet`]: struct.IndexSet.html
733/// [`iter`]: struct.IndexSet.html#method.iter
734pub struct Iter<'a, T> {
735    iter: <&'a EntryVec<Bucket<T>> as IntoIterator>::IntoIter,
736}
737
738impl<'a, T> Iterator for Iter<'a, T> {
739    type Item = &'a T;
740
741    iterator_methods!(Bucket::key_ref);
742}
743
744impl<T> DoubleEndedIterator for Iter<'_, T> {
745    fn next_back(&mut self) -> Option<Self::Item> {
746        self.iter.next_back().map(Bucket::key_ref)
747    }
748}
749
750impl<T> ExactSizeIterator for Iter<'_, T> {
751    fn len(&self) -> usize {
752        self.iter.len()
753    }
754}
755
756impl<T> Clone for Iter<'_, T> {
757    fn clone(&self) -> Self {
758        Iter {
759            iter: self.iter.clone(),
760        }
761    }
762}
763
764impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
765    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
766        f.debug_list().entries(self.clone()).finish()
767    }
768}
769
770/// A draining iterator over the items of a `IndexSet`.
771///
772/// This `struct` is created by the [`drain`] method on [`IndexSet`].
773/// See its documentation for more.
774///
775/// [`IndexSet`]: struct.IndexSet.html
776/// [`drain`]: struct.IndexSet.html#method.drain
777pub struct Drain<'a, T> {
778    iter: atone::vc::Drain<'a, Bucket<T>>,
779}
780
781impl<T> Iterator for Drain<'_, T> {
782    type Item = T;
783
784    iterator_methods!(Bucket::key);
785}
786
787impl<T> DoubleEndedIterator for Drain<'_, T> {
788    double_ended_iterator_methods!(Bucket::key);
789}
790
791impl<'a, T, S> IntoIterator for &'a IndexSet<T, S> {
792    type Item = &'a T;
793    type IntoIter = Iter<'a, T>;
794
795    fn into_iter(self) -> Self::IntoIter {
796        self.iter()
797    }
798}
799
800impl<T, S> IntoIterator for IndexSet<T, S> {
801    type Item = T;
802    type IntoIter = IntoIter<T>;
803
804    fn into_iter(self) -> Self::IntoIter {
805        IntoIter {
806            iter: self.map.into_iter().iter,
807        }
808    }
809}
810
811impl<T, S> FromIterator<T> for IndexSet<T, S>
812where
813    T: Hash + Eq,
814    S: BuildHasher + Default,
815{
816    fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Self {
817        let iter = iterable.into_iter().map(|x| (x, ()));
818        IndexSet {
819            map: IndexMap::from_iter(iter),
820        }
821    }
822}
823
824impl<T, S> Extend<T> for IndexSet<T, S>
825where
826    T: Hash + Eq,
827    S: BuildHasher,
828{
829    fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
830        let iter = iterable.into_iter().map(|x| (x, ()));
831        self.map.extend(iter);
832    }
833}
834
835impl<'a, T, S> Extend<&'a T> for IndexSet<T, S>
836where
837    T: Hash + Eq + Copy + 'a,
838    S: BuildHasher,
839{
840    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iterable: I) {
841        let iter = iterable.into_iter().cloned(); // FIXME: use `copied` in Rust 1.36
842        self.extend(iter);
843    }
844}
845
846impl<T, S> Default for IndexSet<T, S>
847where
848    S: Default,
849{
850    /// Return an empty `IndexSet`
851    fn default() -> Self {
852        IndexSet {
853            map: IndexMap::default(),
854        }
855    }
856}
857
858impl<T, S1, S2> PartialEq<IndexSet<T, S2>> for IndexSet<T, S1>
859where
860    T: Hash + Eq,
861    S1: BuildHasher,
862    S2: BuildHasher,
863{
864    fn eq(&self, other: &IndexSet<T, S2>) -> bool {
865        self.len() == other.len() && self.is_subset(other)
866    }
867}
868
869impl<T, S> Eq for IndexSet<T, S>
870where
871    T: Eq + Hash,
872    S: BuildHasher,
873{
874}
875
876impl<T, S> IndexSet<T, S>
877where
878    T: Eq + Hash,
879    S: BuildHasher,
880{
881    /// Returns `true` if `self` has no elements in common with `other`.
882    pub fn is_disjoint<S2>(&self, other: &IndexSet<T, S2>) -> bool
883    where
884        S2: BuildHasher,
885    {
886        if self.len() <= other.len() {
887            self.iter().all(move |value| !other.contains(value))
888        } else {
889            other.iter().all(move |value| !self.contains(value))
890        }
891    }
892
893    /// Returns `true` if all elements of `self` are contained in `other`.
894    pub fn is_subset<S2>(&self, other: &IndexSet<T, S2>) -> bool
895    where
896        S2: BuildHasher,
897    {
898        self.len() <= other.len() && self.iter().all(move |value| other.contains(value))
899    }
900
901    /// Returns `true` if all elements of `other` are contained in `self`.
902    pub fn is_superset<S2>(&self, other: &IndexSet<T, S2>) -> bool
903    where
904        S2: BuildHasher,
905    {
906        other.is_subset(self)
907    }
908}
909
910/// A lazy iterator producing elements in the difference of `IndexSet`s.
911///
912/// This `struct` is created by the [`difference`] method on [`IndexSet`].
913/// See its documentation for more.
914///
915/// [`IndexSet`]: struct.IndexSet.html
916/// [`difference`]: struct.IndexSet.html#method.difference
917pub struct Difference<'a, T, S> {
918    iter: Iter<'a, T>,
919    other: &'a IndexSet<T, S>,
920}
921
922impl<'a, T, S> Iterator for Difference<'a, T, S>
923where
924    T: Eq + Hash,
925    S: BuildHasher,
926{
927    type Item = &'a T;
928
929    fn next(&mut self) -> Option<Self::Item> {
930        while let Some(item) = self.iter.next() {
931            if !self.other.contains(item) {
932                return Some(item);
933            }
934        }
935        None
936    }
937
938    fn size_hint(&self) -> (usize, Option<usize>) {
939        (0, self.iter.size_hint().1)
940    }
941}
942
943impl<T, S> DoubleEndedIterator for Difference<'_, T, S>
944where
945    T: Eq + Hash,
946    S: BuildHasher,
947{
948    fn next_back(&mut self) -> Option<Self::Item> {
949        while let Some(item) = self.iter.next_back() {
950            if !self.other.contains(item) {
951                return Some(item);
952            }
953        }
954        None
955    }
956}
957
958impl<T, S> Clone for Difference<'_, T, S> {
959    fn clone(&self) -> Self {
960        Difference {
961            iter: self.iter.clone(),
962            ..*self
963        }
964    }
965}
966
967impl<T, S> fmt::Debug for Difference<'_, T, S>
968where
969    T: fmt::Debug + Eq + Hash,
970    S: BuildHasher,
971{
972    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
973        f.debug_list().entries(self.clone()).finish()
974    }
975}
976
977/// A lazy iterator producing elements in the intersection of `IndexSet`s.
978///
979/// This `struct` is created by the [`intersection`] method on [`IndexSet`].
980/// See its documentation for more.
981///
982/// [`IndexSet`]: struct.IndexSet.html
983/// [`intersection`]: struct.IndexSet.html#method.intersection
984pub struct Intersection<'a, T, S> {
985    iter: Iter<'a, T>,
986    other: &'a IndexSet<T, S>,
987}
988
989impl<'a, T, S> Iterator for Intersection<'a, T, S>
990where
991    T: Eq + Hash,
992    S: BuildHasher,
993{
994    type Item = &'a T;
995
996    fn next(&mut self) -> Option<Self::Item> {
997        while let Some(item) = self.iter.next() {
998            if self.other.contains(item) {
999                return Some(item);
1000            }
1001        }
1002        None
1003    }
1004
1005    fn size_hint(&self) -> (usize, Option<usize>) {
1006        (0, self.iter.size_hint().1)
1007    }
1008}
1009
1010impl<T, S> DoubleEndedIterator for Intersection<'_, T, S>
1011where
1012    T: Eq + Hash,
1013    S: BuildHasher,
1014{
1015    fn next_back(&mut self) -> Option<Self::Item> {
1016        while let Some(item) = self.iter.next_back() {
1017            if self.other.contains(item) {
1018                return Some(item);
1019            }
1020        }
1021        None
1022    }
1023}
1024
1025impl<T, S> Clone for Intersection<'_, T, S> {
1026    fn clone(&self) -> Self {
1027        Intersection {
1028            iter: self.iter.clone(),
1029            ..*self
1030        }
1031    }
1032}
1033
1034impl<T, S> fmt::Debug for Intersection<'_, T, S>
1035where
1036    T: fmt::Debug + Eq + Hash,
1037    S: BuildHasher,
1038{
1039    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1040        f.debug_list().entries(self.clone()).finish()
1041    }
1042}
1043
1044/// A lazy iterator producing elements in the symmetric difference of `IndexSet`s.
1045///
1046/// This `struct` is created by the [`symmetric_difference`] method on
1047/// [`IndexSet`]. See its documentation for more.
1048///
1049/// [`IndexSet`]: struct.IndexSet.html
1050/// [`symmetric_difference`]: struct.IndexSet.html#method.symmetric_difference
1051pub struct SymmetricDifference<'a, T, S1, S2> {
1052    iter: Chain<Difference<'a, T, S2>, Difference<'a, T, S1>>,
1053}
1054
1055impl<'a, T, S1, S2> Iterator for SymmetricDifference<'a, T, S1, S2>
1056where
1057    T: Eq + Hash,
1058    S1: BuildHasher,
1059    S2: BuildHasher,
1060{
1061    type Item = &'a T;
1062
1063    fn next(&mut self) -> Option<Self::Item> {
1064        self.iter.next()
1065    }
1066
1067    fn size_hint(&self) -> (usize, Option<usize>) {
1068        self.iter.size_hint()
1069    }
1070
1071    fn fold<B, F>(self, init: B, f: F) -> B
1072    where
1073        F: FnMut(B, Self::Item) -> B,
1074    {
1075        self.iter.fold(init, f)
1076    }
1077}
1078
1079impl<T, S1, S2> DoubleEndedIterator for SymmetricDifference<'_, T, S1, S2>
1080where
1081    T: Eq + Hash,
1082    S1: BuildHasher,
1083    S2: BuildHasher,
1084{
1085    fn next_back(&mut self) -> Option<Self::Item> {
1086        self.iter.next_back()
1087    }
1088}
1089
1090impl<T, S1, S2> Clone for SymmetricDifference<'_, T, S1, S2> {
1091    fn clone(&self) -> Self {
1092        SymmetricDifference {
1093            iter: self.iter.clone(),
1094        }
1095    }
1096}
1097
1098impl<T, S1, S2> fmt::Debug for SymmetricDifference<'_, T, S1, S2>
1099where
1100    T: fmt::Debug + Eq + Hash,
1101    S1: BuildHasher,
1102    S2: BuildHasher,
1103{
1104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105        f.debug_list().entries(self.clone()).finish()
1106    }
1107}
1108
1109/// A lazy iterator producing elements in the union of `IndexSet`s.
1110///
1111/// This `struct` is created by the [`union`] method on [`IndexSet`].
1112/// See its documentation for more.
1113///
1114/// [`IndexSet`]: struct.IndexSet.html
1115/// [`union`]: struct.IndexSet.html#method.union
1116pub struct Union<'a, T, S> {
1117    iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1118}
1119
1120impl<'a, T, S> Iterator for Union<'a, T, S>
1121where
1122    T: Eq + Hash,
1123    S: BuildHasher,
1124{
1125    type Item = &'a T;
1126
1127    fn next(&mut self) -> Option<Self::Item> {
1128        self.iter.next()
1129    }
1130
1131    fn size_hint(&self) -> (usize, Option<usize>) {
1132        self.iter.size_hint()
1133    }
1134
1135    fn fold<B, F>(self, init: B, f: F) -> B
1136    where
1137        F: FnMut(B, Self::Item) -> B,
1138    {
1139        self.iter.fold(init, f)
1140    }
1141}
1142
1143impl<T, S> DoubleEndedIterator for Union<'_, T, S>
1144where
1145    T: Eq + Hash,
1146    S: BuildHasher,
1147{
1148    fn next_back(&mut self) -> Option<Self::Item> {
1149        self.iter.next_back()
1150    }
1151}
1152
1153impl<T, S> Clone for Union<'_, T, S> {
1154    fn clone(&self) -> Self {
1155        Union {
1156            iter: self.iter.clone(),
1157        }
1158    }
1159}
1160
1161impl<T, S> fmt::Debug for Union<'_, T, S>
1162where
1163    T: fmt::Debug + Eq + Hash,
1164    S: BuildHasher,
1165{
1166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167        f.debug_list().entries(self.clone()).finish()
1168    }
1169}
1170
1171impl<T, S1, S2> BitAnd<&IndexSet<T, S2>> for &IndexSet<T, S1>
1172where
1173    T: Eq + Hash + Clone,
1174    S1: BuildHasher + Default,
1175    S2: BuildHasher,
1176{
1177    type Output = IndexSet<T, S1>;
1178
1179    /// Returns the set intersection, cloned into a new set.
1180    ///
1181    /// Values are collected in the same order that they appear in `self`.
1182    fn bitand(self, other: &IndexSet<T, S2>) -> Self::Output {
1183        self.intersection(other).cloned().collect()
1184    }
1185}
1186
1187impl<T, S1, S2> BitOr<&IndexSet<T, S2>> for &IndexSet<T, S1>
1188where
1189    T: Eq + Hash + Clone,
1190    S1: BuildHasher + Default,
1191    S2: BuildHasher,
1192{
1193    type Output = IndexSet<T, S1>;
1194
1195    /// Returns the set union, cloned into a new set.
1196    ///
1197    /// Values from `self` are collected in their original order, followed by
1198    /// values that are unique to `other` in their original order.
1199    fn bitor(self, other: &IndexSet<T, S2>) -> Self::Output {
1200        self.union(other).cloned().collect()
1201    }
1202}
1203
1204impl<T, S1, S2> BitXor<&IndexSet<T, S2>> for &IndexSet<T, S1>
1205where
1206    T: Eq + Hash + Clone,
1207    S1: BuildHasher + Default,
1208    S2: BuildHasher,
1209{
1210    type Output = IndexSet<T, S1>;
1211
1212    /// Returns the set symmetric-difference, cloned into a new set.
1213    ///
1214    /// Values from `self` are collected in their original order, followed by
1215    /// values from `other` in their original order.
1216    fn bitxor(self, other: &IndexSet<T, S2>) -> Self::Output {
1217        self.symmetric_difference(other).cloned().collect()
1218    }
1219}
1220
1221impl<T, S1, S2> Sub<&IndexSet<T, S2>> for &IndexSet<T, S1>
1222where
1223    T: Eq + Hash + Clone,
1224    S1: BuildHasher + Default,
1225    S2: BuildHasher,
1226{
1227    type Output = IndexSet<T, S1>;
1228
1229    /// Returns the set difference, cloned into a new set.
1230    ///
1231    /// Values are collected in the same order that they appear in `self`.
1232    fn sub(self, other: &IndexSet<T, S2>) -> Self::Output {
1233        self.difference(other).cloned().collect()
1234    }
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use super::*;
1240    use crate::util::enumerate;
1241    use std::string::String;
1242    use std::vec::Vec;
1243
1244    #[test]
1245    fn it_works() {
1246        let mut set = IndexSet::new();
1247        assert_eq!(set.is_empty(), true);
1248        set.insert(1);
1249        set.insert(1);
1250        assert_eq!(set.len(), 1);
1251        assert!(set.get(&1).is_some());
1252        assert_eq!(set.is_empty(), false);
1253    }
1254
1255    #[test]
1256    fn new() {
1257        let set = IndexSet::<String>::new();
1258        println!("{:?}", set);
1259        assert_eq!(set.capacity(), 0);
1260        assert_eq!(set.len(), 0);
1261        assert_eq!(set.is_empty(), true);
1262    }
1263
1264    #[test]
1265    fn insert() {
1266        let insert = [0, 4, 2, 12, 8, 7, 11, 5];
1267        let not_present = [1, 3, 6, 9, 10];
1268        let mut set = IndexSet::with_capacity(insert.len());
1269
1270        for (i, &elt) in enumerate(&insert) {
1271            assert_eq!(set.len(), i);
1272            set.insert(elt);
1273            assert_eq!(set.len(), i + 1);
1274            assert_eq!(set.get(&elt), Some(&elt));
1275        }
1276        println!("{:?}", set);
1277
1278        for &elt in &not_present {
1279            assert!(set.get(&elt).is_none());
1280        }
1281    }
1282
1283    #[test]
1284    fn insert_full() {
1285        let insert = vec![9, 2, 7, 1, 4, 6, 13];
1286        let present = vec![1, 6, 2];
1287        let mut set = IndexSet::with_capacity(insert.len());
1288
1289        for (i, &elt) in enumerate(&insert) {
1290            assert_eq!(set.len(), i);
1291            let (index, success) = set.insert_full(elt);
1292            assert!(success);
1293            assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1294            assert_eq!(set.len(), i + 1);
1295        }
1296
1297        let len = set.len();
1298        for &elt in &present {
1299            let (index, success) = set.insert_full(elt);
1300            assert!(!success);
1301            assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1302            assert_eq!(set.len(), len);
1303        }
1304    }
1305
1306    #[test]
1307    fn insert_2() {
1308        let mut set = IndexSet::with_capacity(16);
1309
1310        let mut values = vec![];
1311        values.extend(0..16);
1312        values.extend(128..267);
1313
1314        for &i in &values {
1315            let old_set = set.clone();
1316            set.insert(i);
1317            for value in old_set.iter() {
1318                if set.get(value).is_none() {
1319                    println!("old_set: {:?}", old_set);
1320                    println!("set: {:?}", set);
1321                    panic!("did not find {} in set", value);
1322                }
1323            }
1324        }
1325
1326        for &i in &values {
1327            assert!(set.get(&i).is_some(), "did not find {}", i);
1328        }
1329    }
1330
1331    #[test]
1332    fn insert_dup() {
1333        let mut elements = vec![0, 2, 4, 6, 8];
1334        let mut set: IndexSet<u8> = elements.drain(..).collect();
1335        {
1336            let (i, v) = set.get_full(&0).unwrap();
1337            assert_eq!(set.len(), 5);
1338            assert_eq!(i, 0);
1339            assert_eq!(*v, 0);
1340        }
1341        {
1342            let inserted = set.insert(0);
1343            let (i, v) = set.get_full(&0).unwrap();
1344            assert_eq!(set.len(), 5);
1345            assert_eq!(inserted, false);
1346            assert_eq!(i, 0);
1347            assert_eq!(*v, 0);
1348        }
1349    }
1350
1351    #[test]
1352    fn insert_order() {
1353        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1354        let mut set = IndexSet::new();
1355
1356        for &elt in &insert {
1357            set.insert(elt);
1358        }
1359
1360        assert_eq!(set.iter().count(), set.len());
1361        assert_eq!(set.iter().count(), insert.len());
1362        for (a, b) in insert.iter().zip(set.iter()) {
1363            assert_eq!(a, b);
1364        }
1365        for (i, v) in (0..insert.len()).zip(set.iter()) {
1366            assert_eq!(set.get_index(i).unwrap(), v);
1367        }
1368    }
1369
1370    #[test]
1371    fn grow() {
1372        let insert = [0, 4, 2, 12, 8, 7, 11];
1373        let not_present = [1, 3, 6, 9, 10];
1374        let mut set = IndexSet::with_capacity(insert.len());
1375
1376        for (i, &elt) in enumerate(&insert) {
1377            assert_eq!(set.len(), i);
1378            set.insert(elt);
1379            assert_eq!(set.len(), i + 1);
1380            assert_eq!(set.get(&elt), Some(&elt));
1381        }
1382
1383        println!("{:?}", set);
1384        for &elt in &insert {
1385            set.insert(elt * 10);
1386        }
1387        for &elt in &insert {
1388            set.insert(elt * 100);
1389        }
1390        for (i, &elt) in insert.iter().cycle().enumerate().take(100) {
1391            set.insert(elt * 100 + i as i32);
1392        }
1393        println!("{:?}", set);
1394        for &elt in &not_present {
1395            assert!(set.get(&elt).is_none());
1396        }
1397    }
1398
1399    #[test]
1400    fn reserve() {
1401        let mut set = IndexSet::<usize>::new();
1402        assert_eq!(set.capacity(), 0);
1403        set.reserve(100);
1404        let capacity = set.capacity();
1405        assert!(capacity >= 100);
1406        for i in 0..capacity {
1407            assert_eq!(set.len(), i);
1408            set.insert(i);
1409            assert_eq!(set.len(), i + 1);
1410            assert_eq!(set.capacity(), capacity);
1411            assert_eq!(set.get(&i), Some(&i));
1412        }
1413        set.insert(capacity);
1414        assert_eq!(set.len(), capacity + 1);
1415        assert!(set.capacity() > capacity);
1416        assert_eq!(set.get(&capacity), Some(&capacity));
1417    }
1418
1419    #[test]
1420    fn shrink_to_fit() {
1421        let mut set = IndexSet::<usize>::new();
1422        assert_eq!(set.capacity(), 0);
1423        for i in 0..100 {
1424            assert_eq!(set.len(), i);
1425            set.insert(i);
1426            assert_eq!(set.len(), i + 1);
1427            assert!(set.capacity() >= i + 1);
1428            assert_eq!(set.get(&i), Some(&i));
1429            set.shrink_to_fit();
1430            assert_eq!(set.len(), i + 1);
1431            assert_eq!(set.get(&i), Some(&i));
1432        }
1433    }
1434
1435    #[test]
1436    fn remove() {
1437        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1438        let mut set = IndexSet::new();
1439
1440        for &elt in &insert {
1441            set.insert(elt);
1442        }
1443
1444        assert_eq!(set.iter().count(), set.len());
1445        assert_eq!(set.iter().count(), insert.len());
1446        for (a, b) in insert.iter().zip(set.iter()) {
1447            assert_eq!(a, b);
1448        }
1449
1450        let remove_fail = [99, 77];
1451        let remove = [4, 12, 8, 7];
1452
1453        for &value in &remove_fail {
1454            assert!(set.swap_remove_full(&value).is_none());
1455        }
1456        println!("{:?}", set);
1457        for &value in &remove {
1458            //println!("{:?}", set);
1459            let index = set.get_full(&value).unwrap().0;
1460            assert_eq!(set.swap_remove_full(&value), Some((index, value)));
1461        }
1462        println!("{:?}", set);
1463
1464        for value in &insert {
1465            assert_eq!(set.get(value).is_some(), !remove.contains(value));
1466        }
1467        assert_eq!(set.len(), insert.len() - remove.len());
1468        assert_eq!(set.iter().count(), insert.len() - remove.len());
1469    }
1470
1471    #[test]
1472    fn swap_remove_index() {
1473        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1474        let mut set = IndexSet::new();
1475
1476        for &elt in &insert {
1477            set.insert(elt);
1478        }
1479
1480        let mut vector = insert.to_vec();
1481        let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1];
1482
1483        // check that the same swap remove sequence on vec and set
1484        // have the same result.
1485        for &rm in remove_sequence {
1486            let out_vec = vector.swap_remove(rm);
1487            let out_set = set.swap_remove_index(rm).unwrap();
1488            assert_eq!(out_vec, out_set);
1489        }
1490        assert_eq!(vector.len(), set.len());
1491        for (a, b) in vector.iter().zip(set.iter()) {
1492            assert_eq!(a, b);
1493        }
1494    }
1495
1496    #[test]
1497    fn partial_eq_and_eq() {
1498        let mut set_a = IndexSet::new();
1499        set_a.insert(1);
1500        set_a.insert(2);
1501        let mut set_b = set_a.clone();
1502        assert_eq!(set_a, set_b);
1503        set_b.swap_remove(&1);
1504        assert_ne!(set_a, set_b);
1505
1506        let set_c: IndexSet<_> = set_b.into_iter().collect();
1507        assert_ne!(set_a, set_c);
1508        assert_ne!(set_c, set_a);
1509    }
1510
1511    #[test]
1512    fn extend() {
1513        let mut set = IndexSet::new();
1514        set.extend(vec![&1, &2, &3, &4]);
1515        set.extend(vec![5, 6]);
1516        assert_eq!(set.into_iter().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5, 6]);
1517    }
1518
1519    #[test]
1520    fn comparisons() {
1521        let set_a: IndexSet<_> = (0..3).collect();
1522        let set_b: IndexSet<_> = (3..6).collect();
1523        let set_c: IndexSet<_> = (0..6).collect();
1524        let set_d: IndexSet<_> = (3..9).collect();
1525
1526        assert!(!set_a.is_disjoint(&set_a));
1527        assert!(set_a.is_subset(&set_a));
1528        assert!(set_a.is_superset(&set_a));
1529
1530        assert!(set_a.is_disjoint(&set_b));
1531        assert!(set_b.is_disjoint(&set_a));
1532        assert!(!set_a.is_subset(&set_b));
1533        assert!(!set_b.is_subset(&set_a));
1534        assert!(!set_a.is_superset(&set_b));
1535        assert!(!set_b.is_superset(&set_a));
1536
1537        assert!(!set_a.is_disjoint(&set_c));
1538        assert!(!set_c.is_disjoint(&set_a));
1539        assert!(set_a.is_subset(&set_c));
1540        assert!(!set_c.is_subset(&set_a));
1541        assert!(!set_a.is_superset(&set_c));
1542        assert!(set_c.is_superset(&set_a));
1543
1544        assert!(!set_c.is_disjoint(&set_d));
1545        assert!(!set_d.is_disjoint(&set_c));
1546        assert!(!set_c.is_subset(&set_d));
1547        assert!(!set_d.is_subset(&set_c));
1548        assert!(!set_c.is_superset(&set_d));
1549        assert!(!set_d.is_superset(&set_c));
1550    }
1551
1552    #[test]
1553    fn iter_comparisons() {
1554        use std::iter::empty;
1555
1556        fn check<'a, I1, I2>(iter1: I1, iter2: I2)
1557        where
1558            I1: Iterator<Item = &'a i32>,
1559            I2: Iterator<Item = i32>,
1560        {
1561            assert!(iter1.cloned().eq(iter2));
1562        }
1563
1564        let set_a: IndexSet<_> = (0..3).collect();
1565        let set_b: IndexSet<_> = (3..6).collect();
1566        let set_c: IndexSet<_> = (0..6).collect();
1567        let set_d: IndexSet<_> = (3..9).rev().collect();
1568
1569        check(set_a.difference(&set_a), empty());
1570        check(set_a.symmetric_difference(&set_a), empty());
1571        check(set_a.intersection(&set_a), 0..3);
1572        check(set_a.union(&set_a), 0..3);
1573
1574        check(set_a.difference(&set_b), 0..3);
1575        check(set_b.difference(&set_a), 3..6);
1576        check(set_a.symmetric_difference(&set_b), 0..6);
1577        check(set_b.symmetric_difference(&set_a), (3..6).chain(0..3));
1578        check(set_a.intersection(&set_b), empty());
1579        check(set_b.intersection(&set_a), empty());
1580        check(set_a.union(&set_b), 0..6);
1581        check(set_b.union(&set_a), (3..6).chain(0..3));
1582
1583        check(set_a.difference(&set_c), empty());
1584        check(set_c.difference(&set_a), 3..6);
1585        check(set_a.symmetric_difference(&set_c), 3..6);
1586        check(set_c.symmetric_difference(&set_a), 3..6);
1587        check(set_a.intersection(&set_c), 0..3);
1588        check(set_c.intersection(&set_a), 0..3);
1589        check(set_a.union(&set_c), 0..6);
1590        check(set_c.union(&set_a), 0..6);
1591
1592        check(set_c.difference(&set_d), 0..3);
1593        check(set_d.difference(&set_c), (6..9).rev());
1594        check(
1595            set_c.symmetric_difference(&set_d),
1596            (0..3).chain((6..9).rev()),
1597        );
1598        check(set_d.symmetric_difference(&set_c), (6..9).rev().chain(0..3));
1599        check(set_c.intersection(&set_d), 3..6);
1600        check(set_d.intersection(&set_c), (3..6).rev());
1601        check(set_c.union(&set_d), (0..6).chain((6..9).rev()));
1602        check(set_d.union(&set_c), (3..9).rev().chain(0..3));
1603    }
1604
1605    #[test]
1606    fn ops() {
1607        let empty = IndexSet::<i32>::new();
1608        let set_a: IndexSet<_> = (0..3).collect();
1609        let set_b: IndexSet<_> = (3..6).collect();
1610        let set_c: IndexSet<_> = (0..6).collect();
1611        let set_d: IndexSet<_> = (3..9).rev().collect();
1612
1613        // FIXME: #[allow(clippy::eq_op)] in Rust 1.31
1614        #[cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints, eq_op))]
1615        {
1616            assert_eq!(&set_a & &set_a, set_a);
1617            assert_eq!(&set_a | &set_a, set_a);
1618            assert_eq!(&set_a ^ &set_a, empty);
1619            assert_eq!(&set_a - &set_a, empty);
1620        }
1621
1622        assert_eq!(&set_a & &set_b, empty);
1623        assert_eq!(&set_b & &set_a, empty);
1624        assert_eq!(&set_a | &set_b, set_c);
1625        assert_eq!(&set_b | &set_a, set_c);
1626        assert_eq!(&set_a ^ &set_b, set_c);
1627        assert_eq!(&set_b ^ &set_a, set_c);
1628        assert_eq!(&set_a - &set_b, set_a);
1629        assert_eq!(&set_b - &set_a, set_b);
1630
1631        assert_eq!(&set_a & &set_c, set_a);
1632        assert_eq!(&set_c & &set_a, set_a);
1633        assert_eq!(&set_a | &set_c, set_c);
1634        assert_eq!(&set_c | &set_a, set_c);
1635        assert_eq!(&set_a ^ &set_c, set_b);
1636        assert_eq!(&set_c ^ &set_a, set_b);
1637        assert_eq!(&set_a - &set_c, empty);
1638        assert_eq!(&set_c - &set_a, set_b);
1639
1640        assert_eq!(&set_c & &set_d, set_b);
1641        assert_eq!(&set_d & &set_c, set_b);
1642        assert_eq!(&set_c | &set_d, &set_a | &set_d);
1643        assert_eq!(&set_d | &set_c, &set_a | &set_d);
1644        assert_eq!(&set_c ^ &set_d, &set_a | &(&set_d - &set_b));
1645        assert_eq!(&set_d ^ &set_c, &set_a | &(&set_d - &set_b));
1646        assert_eq!(&set_c - &set_d, set_a);
1647        assert_eq!(&set_d - &set_c, &set_d - &set_b);
1648    }
1649}