1 //! A hash set implemented using `IndexMap`
3 #[cfg(feature = "rayon")]
4 pub use ::rayon::set as rayon;
6 use std::cmp::Ordering;
7 use std::collections::hash_map::RandomState;
9 use std::iter::{FromIterator, Chain};
10 use std::hash::{Hash, BuildHasher};
11 use std::ops::RangeFull;
12 use std::ops::{BitAnd, BitOr, BitXor, Sub};
16 use super::{IndexMap, Equivalent, Entries};
18 type Bucket<T> = super::Bucket<T, ()>;
20 /// A hash set where the iteration order of the values is independent of their
23 /// The interface is closely compatible with the standard `HashSet`, but also
24 /// has additional features.
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
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.
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.
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.
51 /// use indexmap::IndexSet;
53 /// // Collects which letters appear in a sentence.
54 /// let letters: IndexSet<_> = "a short treatise on fungi".chars().collect();
56 /// assert!(letters.contains(&'s'));
57 /// assert!(letters.contains(&'t'));
58 /// assert!(letters.contains(&'u'));
59 /// assert!(!letters.contains(&'y'));
62 pub struct IndexSet<T, S = RandomState> {
63 map: IndexMap<T, (), S>,
66 impl<T, S> Entries for IndexSet<T, S> {
67 type Entry = Bucket<T>;
69 fn into_entries(self) -> Vec<Self::Entry> {
70 self.map.into_entries()
73 fn as_entries(&self) -> &[Self::Entry] {
77 fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
78 self.map.as_entries_mut()
81 fn with_entries<F>(&mut self, f: F)
82 where F: FnOnce(&mut [Self::Entry])
84 self.map.with_entries(f);
88 impl<T, S> fmt::Debug for IndexSet<T, S>
89 where T: fmt::Debug + Hash + Eq,
92 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 if cfg!(not(feature = "test_debug")) {
94 f.debug_set().entries(self.iter()).finish()
96 // Let the inner `IndexMap` print all of its details
97 f.debug_struct("IndexSet").field("map", &self.map).finish()
102 impl<T> IndexSet<T> {
103 /// Create a new set. (Does not allocate.)
104 pub fn new() -> Self {
105 IndexSet { map: IndexMap::new() }
108 /// Create a new set with capacity for `n` elements.
109 /// (Does not allocate if `n` is zero.)
111 /// Computes in **O(n)** time.
112 pub fn with_capacity(n: usize) -> Self {
113 IndexSet { map: IndexMap::with_capacity(n) }
117 impl<T, S> IndexSet<T, S> {
118 /// Create a new set with capacity for `n` elements.
119 /// (Does not allocate if `n` is zero.)
121 /// Computes in **O(n)** time.
122 pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self
125 IndexSet { map: IndexMap::with_capacity_and_hasher(n, hash_builder) }
128 /// Return the number of elements in the set.
130 /// Computes in **O(1)** time.
131 pub fn len(&self) -> usize {
135 /// Returns true if the set contains no elements.
137 /// Computes in **O(1)** time.
138 pub fn is_empty(&self) -> bool {
142 /// Create a new set with `hash_builder`
143 pub fn with_hasher(hash_builder: S) -> Self
146 IndexSet { map: IndexMap::with_hasher(hash_builder) }
149 /// Return a reference to the set's `BuildHasher`.
150 pub fn hasher(&self) -> &S
156 /// Computes in **O(1)** time.
157 pub fn capacity(&self) -> usize {
162 impl<T, S> IndexSet<T, S>
166 /// Remove all elements in the set, while preserving its capacity.
168 /// Computes in **O(n)** time.
169 pub fn clear(&mut self) {
173 /// FIXME Not implemented fully yet
174 pub fn reserve(&mut self, additional: usize) {
175 self.map.reserve(additional);
178 /// Insert the value into the set.
180 /// If an equivalent item already exists in the set, it returns
181 /// `false` leaving the original value in the set and without
182 /// altering its insertion order. Otherwise, it inserts the new
183 /// item and returns `true`.
185 /// Computes in **O(1)** time (amortized average).
186 pub fn insert(&mut self, value: T) -> bool {
187 self.map.insert(value, ()).is_none()
190 /// Insert the value into the set, and get its index.
192 /// If an equivalent item already exists in the set, it returns
193 /// the index of the existing item and `false`, leaving the
194 /// original value in the set and without altering its insertion
195 /// order. Otherwise, it inserts the new item and returns the index
196 /// of the inserted item and `true`.
198 /// Computes in **O(1)** time (amortized average).
199 pub fn insert_full(&mut self, value: T) -> (usize, bool) {
200 use super::map::Entry::*;
202 match self.map.entry(value) {
203 Occupied(e) => (e.index(), false),
205 let index = e.index();
212 /// Return an iterator over the values of the set, in their order
213 pub fn iter(&self) -> Iter<T> {
215 iter: self.map.keys().iter
219 /// Return an iterator over the values that are in `self` but not `other`.
221 /// Values are produced in the same order that they appear in `self`.
222 pub fn difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Difference<'a, T, S2>
223 where S2: BuildHasher
231 /// Return an iterator over the values that are in `self` or `other`,
234 /// Values from `self` are produced in their original order, followed by
235 /// values from `other` in their original order.
236 pub fn symmetric_difference<'a, S2>(&'a self, other: &'a IndexSet<T, S2>)
237 -> SymmetricDifference<'a, T, S, S2>
238 where S2: BuildHasher
240 SymmetricDifference {
241 iter: self.difference(other).chain(other.difference(self)),
245 /// Return an iterator over the values that are in both `self` and `other`.
247 /// Values are produced in the same order that they appear in `self`.
248 pub fn intersection<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Intersection<'a, T, S2>
249 where S2: BuildHasher
257 /// Return an iterator over all values that are in `self` or `other`.
259 /// Values from `self` are produced in their original order, followed by
260 /// values that are unique to `other` in their original order.
261 pub fn union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> Union<'a, T, S>
262 where S2: BuildHasher
265 iter: self.iter().chain(other.difference(self)),
269 /// Return `true` if an equivalent to `value` exists in the set.
271 /// Computes in **O(1)** time (average).
272 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
273 where Q: Hash + Equivalent<T>,
275 self.map.contains_key(value)
278 /// Return a reference to the value stored in the set, if it is present,
281 /// Computes in **O(1)** time (average).
282 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
283 where Q: Hash + Equivalent<T>,
285 self.map.get_full(value).map(|(_, x, &())| x)
288 /// Return item index and value
289 pub fn get_full<Q: ?Sized>(&self, value: &Q) -> Option<(usize, &T)>
290 where Q: Hash + Equivalent<T>,
292 self.map.get_full(value).map(|(i, x, &())| (i, x))
295 /// Adds a value to the set, replacing the existing value, if any, that is
296 /// equal to the given one. Returns the replaced value.
298 /// Computes in **O(1)** time (average).
299 pub fn replace(&mut self, value: T) -> Option<T>
301 use super::map::Entry::*;
303 match self.map.entry(value) {
304 Vacant(e) => { e.insert(()); None },
305 Occupied(e) => Some(e.replace_key()),
309 /// FIXME Same as .swap_remove
311 /// Computes in **O(1)** time (average).
312 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
313 where Q: Hash + Equivalent<T>,
315 self.swap_remove(value)
318 /// Remove the value from the set, and return `true` if it was present.
320 /// Like `Vec::swap_remove`, the value is removed by swapping it with the
321 /// last element of the set and popping it off. **This perturbs
322 /// the postion of what used to be the last element!**
324 /// Return `false` if `value` was not in the set.
326 /// Computes in **O(1)** time (average).
327 pub fn swap_remove<Q: ?Sized>(&mut self, value: &Q) -> bool
328 where Q: Hash + Equivalent<T>,
330 self.map.swap_remove(value).is_some()
333 /// FIXME Same as .swap_take
335 /// Computes in **O(1)** time (average).
336 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
337 where Q: Hash + Equivalent<T>,
339 self.swap_take(value)
342 /// Removes and returns the value in the set, if any, that is equal to the
345 /// Like `Vec::swap_remove`, the value is removed by swapping it with the
346 /// last element of the set and popping it off. **This perturbs
347 /// the postion of what used to be the last element!**
349 /// Return `None` if `value` was not in the set.
351 /// Computes in **O(1)** time (average).
352 pub fn swap_take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
353 where Q: Hash + Equivalent<T>,
355 self.map.swap_remove_full(value).map(|(_, x, ())| x)
358 /// Remove the value from the set return it and the index it had.
360 /// Like `Vec::swap_remove`, the value is removed by swapping it with the
361 /// last element of the set and popping it off. **This perturbs
362 /// the postion of what used to be the last element!**
364 /// Return `None` if `value` was not in the set.
365 pub fn swap_remove_full<Q: ?Sized>(&mut self, value: &Q) -> Option<(usize, T)>
366 where Q: Hash + Equivalent<T>,
368 self.map.swap_remove_full(value).map(|(i, x, ())| (i, x))
371 /// Remove the last value
373 /// Computes in **O(1)** time (average).
374 pub fn pop(&mut self) -> Option<T> {
375 self.map.pop().map(|(x, ())| x)
378 /// Scan through each value in the set and keep those where the
379 /// closure `keep` returns `true`.
381 /// The elements are visited in order, and remaining elements keep their
384 /// Computes in **O(n)** time (average).
385 pub fn retain<F>(&mut self, mut keep: F)
386 where F: FnMut(&T) -> bool,
388 self.map.retain(move |x, &mut ()| keep(x))
391 /// Sort the set’s values by their default ordering.
393 /// See `sort_by` for details.
394 pub fn sort(&mut self)
400 /// Sort the set’s values in place using the comparison function `compare`.
402 /// Computes in **O(n log n)** time and **O(n)** space. The sort is stable.
403 pub fn sort_by<F>(&mut self, mut compare: F)
404 where F: FnMut(&T, &T) -> Ordering,
406 self.map.sort_by(move |a, _, b, _| compare(a, b));
409 /// Sort the values of the set and return a by value iterator of
410 /// the values with the result.
412 /// The sort is stable.
413 pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<T>
414 where F: FnMut(&T, &T) -> Ordering
417 iter: self.map.sorted_by(move |a, &(), b, &()| cmp(a, b)).iter,
421 /// Clears the `IndexSet`, returning all values as a drain iterator.
422 /// Keeps the allocated memory for reuse.
423 pub fn drain(&mut self, range: RangeFull) -> Drain<T> {
425 iter: self.map.drain(range).iter,
430 impl<T, S> IndexSet<T, S> {
431 /// Get a value by index
433 /// Valid indices are *0 <= index < self.len()*
435 /// Computes in **O(1)** time.
436 pub fn get_index(&self, index: usize) -> Option<&T> {
437 self.map.get_index(index).map(|(x, &())| x)
440 /// Remove the key-value pair by index
442 /// Valid indices are *0 <= index < self.len()*
444 /// Computes in **O(1)** time (average).
445 pub fn swap_remove_index(&mut self, index: usize) -> Option<T> {
446 self.map.swap_remove_index(index).map(|(x, ())| x)
451 /// An owning iterator over the items of a `IndexSet`.
453 /// This `struct` is created by the [`into_iter`] method on [`IndexSet`]
454 /// (provided by the `IntoIterator` trait). See its documentation for more.
456 /// [`IndexSet`]: struct.IndexSet.html
457 /// [`into_iter`]: struct.IndexSet.html#method.into_iter
458 pub struct IntoIter<T> {
459 iter: vec::IntoIter<Bucket<T>>,
462 impl<T> Iterator for IntoIter<T> {
465 iterator_methods!(Bucket::key);
468 impl<T> DoubleEndedIterator for IntoIter<T> {
469 fn next_back(&mut self) -> Option<Self::Item> {
470 self.iter.next_back().map(Bucket::key)
474 impl<T> ExactSizeIterator for IntoIter<T> {
475 fn len(&self) -> usize {
480 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 let iter = self.iter.as_slice().iter().map(Bucket::key_ref);
483 f.debug_list().entries(iter).finish()
488 /// An iterator over the items of a `IndexSet`.
490 /// This `struct` is created by the [`iter`] method on [`IndexSet`].
491 /// See its documentation for more.
493 /// [`IndexSet`]: struct.IndexSet.html
494 /// [`iter`]: struct.IndexSet.html#method.iter
495 pub struct Iter<'a, T: 'a> {
496 iter: slice::Iter<'a, Bucket<T>>,
499 impl<'a, T> Iterator for Iter<'a, T> {
502 iterator_methods!(Bucket::key_ref);
505 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
506 fn next_back(&mut self) -> Option<Self::Item> {
507 self.iter.next_back().map(Bucket::key_ref)
511 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
512 fn len(&self) -> usize {
517 impl<'a, T> Clone for Iter<'a, T> {
518 fn clone(&self) -> Self {
519 Iter { iter: self.iter.clone() }
523 impl<'a, T: fmt::Debug> fmt::Debug for Iter<'a, T> {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 f.debug_list().entries(self.clone()).finish()
529 /// A draining iterator over the items of a `IndexSet`.
531 /// This `struct` is created by the [`drain`] method on [`IndexSet`].
532 /// See its documentation for more.
534 /// [`IndexSet`]: struct.IndexSet.html
535 /// [`drain`]: struct.IndexSet.html#method.drain
536 pub struct Drain<'a, T: 'a> {
537 iter: vec::Drain<'a, Bucket<T>>,
540 impl<'a, T> Iterator for Drain<'a, T> {
543 iterator_methods!(Bucket::key);
546 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
547 double_ended_iterator_methods!(Bucket::key);
550 impl<'a, T, S> IntoIterator for &'a IndexSet<T, S>
555 type IntoIter = Iter<'a, T>;
557 fn into_iter(self) -> Self::IntoIter {
562 impl<T, S> IntoIterator for IndexSet<T, S>
567 type IntoIter = IntoIter<T>;
569 fn into_iter(self) -> Self::IntoIter {
571 iter: self.map.into_iter().iter,
576 impl<T, S> FromIterator<T> for IndexSet<T, S>
578 S: BuildHasher + Default,
580 fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Self {
581 let iter = iterable.into_iter().map(|x| (x, ()));
582 IndexSet { map: IndexMap::from_iter(iter) }
586 impl<T, S> Extend<T> for IndexSet<T, S>
590 fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
591 let iter = iterable.into_iter().map(|x| (x, ()));
592 self.map.extend(iter);
596 impl<'a, T, S> Extend<&'a T> for IndexSet<T, S>
597 where T: Hash + Eq + Copy,
600 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iterable: I) {
601 let iter = iterable.into_iter().map(|&x| x);
607 impl<T, S> Default for IndexSet<T, S>
608 where S: BuildHasher + Default,
610 /// Return an empty `IndexSet`
611 fn default() -> Self {
612 IndexSet { map: IndexMap::default() }
616 impl<T, S1, S2> PartialEq<IndexSet<T, S2>> for IndexSet<T, S1>
621 fn eq(&self, other: &IndexSet<T, S2>) -> bool {
622 self.len() == other.len() && self.is_subset(other)
626 impl<T, S> Eq for IndexSet<T, S>
632 impl<T, S> IndexSet<T, S>
636 /// Returns `true` if `self` has no elements in common with `other`.
637 pub fn is_disjoint<S2>(&self, other: &IndexSet<T, S2>) -> bool
638 where S2: BuildHasher
640 if self.len() <= other.len() {
641 self.iter().all(move |value| !other.contains(value))
643 other.iter().all(move |value| !self.contains(value))
647 /// Returns `true` if all elements of `self` are contained in `other`.
648 pub fn is_subset<S2>(&self, other: &IndexSet<T, S2>) -> bool
649 where S2: BuildHasher
651 self.len() <= other.len() && self.iter().all(move |value| other.contains(value))
654 /// Returns `true` if all elements of `other` are contained in `self`.
655 pub fn is_superset<S2>(&self, other: &IndexSet<T, S2>) -> bool
656 where S2: BuildHasher
658 other.is_subset(self)
663 /// A lazy iterator producing elements in the difference of `IndexSet`s.
665 /// This `struct` is created by the [`difference`] method on [`IndexSet`].
666 /// See its documentation for more.
668 /// [`IndexSet`]: struct.IndexSet.html
669 /// [`difference`]: struct.IndexSet.html#method.difference
670 pub struct Difference<'a, T: 'a, S: 'a> {
672 other: &'a IndexSet<T, S>,
675 impl<'a, T, S> Iterator for Difference<'a, T, S>
681 fn next(&mut self) -> Option<Self::Item> {
682 while let Some(item) = self.iter.next() {
683 if !self.other.contains(item) {
690 fn size_hint(&self) -> (usize, Option<usize>) {
691 (0, self.iter.size_hint().1)
695 impl<'a, T, S> DoubleEndedIterator for Difference<'a, T, S>
699 fn next_back(&mut self) -> Option<Self::Item> {
700 while let Some(item) = self.iter.next_back() {
701 if !self.other.contains(item) {
709 impl<'a, T, S> Clone for Difference<'a, T, S> {
710 fn clone(&self) -> Self {
711 Difference { iter: self.iter.clone(), ..*self }
715 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
716 where T: fmt::Debug + Eq + Hash,
719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
720 f.debug_list().entries(self.clone()).finish()
725 /// A lazy iterator producing elements in the intersection of `IndexSet`s.
727 /// This `struct` is created by the [`intersection`] method on [`IndexSet`].
728 /// See its documentation for more.
730 /// [`IndexSet`]: struct.IndexSet.html
731 /// [`intersection`]: struct.IndexSet.html#method.intersection
732 pub struct Intersection<'a, T: 'a, S: 'a> {
734 other: &'a IndexSet<T, S>,
737 impl<'a, T, S> Iterator for Intersection<'a, T, S>
743 fn next(&mut self) -> Option<Self::Item> {
744 while let Some(item) = self.iter.next() {
745 if self.other.contains(item) {
752 fn size_hint(&self) -> (usize, Option<usize>) {
753 (0, self.iter.size_hint().1)
757 impl<'a, T, S> DoubleEndedIterator for Intersection<'a, T, S>
761 fn next_back(&mut self) -> Option<Self::Item> {
762 while let Some(item) = self.iter.next_back() {
763 if self.other.contains(item) {
771 impl<'a, T, S> Clone for Intersection<'a, T, S> {
772 fn clone(&self) -> Self {
773 Intersection { iter: self.iter.clone(), ..*self }
777 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
778 where T: fmt::Debug + Eq + Hash,
781 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
782 f.debug_list().entries(self.clone()).finish()
787 /// A lazy iterator producing elements in the symmetric difference of `IndexSet`s.
789 /// This `struct` is created by the [`symmetric_difference`] method on
790 /// [`IndexSet`]. See its documentation for more.
792 /// [`IndexSet`]: struct.IndexSet.html
793 /// [`symmetric_difference`]: struct.IndexSet.html#method.symmetric_difference
794 pub struct SymmetricDifference<'a, T: 'a, S1: 'a, S2: 'a> {
795 iter: Chain<Difference<'a, T, S2>, Difference<'a, T, S1>>,
798 impl<'a, T, S1, S2> Iterator for SymmetricDifference<'a, T, S1, S2>
805 fn next(&mut self) -> Option<Self::Item> {
809 fn size_hint(&self) -> (usize, Option<usize>) {
810 self.iter.size_hint()
813 fn fold<B, F>(self, init: B, f: F) -> B
814 where F: FnMut(B, Self::Item) -> B
816 self.iter.fold(init, f)
820 impl<'a, T, S1, S2> DoubleEndedIterator for SymmetricDifference<'a, T, S1, S2>
825 fn next_back(&mut self) -> Option<Self::Item> {
826 self.iter.next_back()
830 impl<'a, T, S1, S2> Clone for SymmetricDifference<'a, T, S1, S2> {
831 fn clone(&self) -> Self {
832 SymmetricDifference { iter: self.iter.clone() }
836 impl<'a, T, S1, S2> fmt::Debug for SymmetricDifference<'a, T, S1, S2>
837 where T: fmt::Debug + Eq + Hash,
841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 f.debug_list().entries(self.clone()).finish()
847 /// A lazy iterator producing elements in the union of `IndexSet`s.
849 /// This `struct` is created by the [`union`] method on [`IndexSet`].
850 /// See its documentation for more.
852 /// [`IndexSet`]: struct.IndexSet.html
853 /// [`union`]: struct.IndexSet.html#method.union
854 pub struct Union<'a, T: 'a, S: 'a> {
855 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
858 impl<'a, T, S> Iterator for Union<'a, T, S>
864 fn next(&mut self) -> Option<Self::Item> {
868 fn size_hint(&self) -> (usize, Option<usize>) {
869 self.iter.size_hint()
872 fn fold<B, F>(self, init: B, f: F) -> B
873 where F: FnMut(B, Self::Item) -> B
875 self.iter.fold(init, f)
879 impl<'a, T, S> DoubleEndedIterator for Union<'a, T, S>
883 fn next_back(&mut self) -> Option<Self::Item> {
884 self.iter.next_back()
888 impl<'a, T, S> Clone for Union<'a, T, S> {
889 fn clone(&self) -> Self {
890 Union { iter: self.iter.clone() }
894 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
895 where T: fmt::Debug + Eq + Hash,
898 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
899 f.debug_list().entries(self.clone()).finish()
904 impl<'a, 'b, T, S1, S2> BitAnd<&'b IndexSet<T, S2>> for &'a IndexSet<T, S1>
905 where T: Eq + Hash + Clone,
906 S1: BuildHasher + Default,
909 type Output = IndexSet<T, S1>;
911 /// Returns the set intersection, cloned into a new set.
913 /// Values are collected in the same order that they appear in `self`.
914 fn bitand(self, other: &'b IndexSet<T, S2>) -> Self::Output {
915 self.intersection(other).cloned().collect()
919 impl<'a, 'b, T, S1, S2> BitOr<&'b IndexSet<T, S2>> for &'a IndexSet<T, S1>
920 where T: Eq + Hash + Clone,
921 S1: BuildHasher + Default,
924 type Output = IndexSet<T, S1>;
926 /// Returns the set union, cloned into a new set.
928 /// Values from `self` are collected in their original order, followed by
929 /// values that are unique to `other` in their original order.
930 fn bitor(self, other: &'b IndexSet<T, S2>) -> Self::Output {
931 self.union(other).cloned().collect()
935 impl<'a, 'b, T, S1, S2> BitXor<&'b IndexSet<T, S2>> for &'a IndexSet<T, S1>
936 where T: Eq + Hash + Clone,
937 S1: BuildHasher + Default,
940 type Output = IndexSet<T, S1>;
942 /// Returns the set symmetric-difference, cloned into a new set.
944 /// Values from `self` are collected in their original order, followed by
945 /// values from `other` in their original order.
946 fn bitxor(self, other: &'b IndexSet<T, S2>) -> Self::Output {
947 self.symmetric_difference(other).cloned().collect()
951 impl<'a, 'b, T, S1, S2> Sub<&'b IndexSet<T, S2>> for &'a IndexSet<T, S1>
952 where T: Eq + Hash + Clone,
953 S1: BuildHasher + Default,
956 type Output = IndexSet<T, S1>;
958 /// Returns the set difference, cloned into a new set.
960 /// Values are collected in the same order that they appear in `self`.
961 fn sub(self, other: &'b IndexSet<T, S2>) -> Self::Output {
962 self.difference(other).cloned().collect()
974 let mut set = IndexSet::new();
975 assert_eq!(set.is_empty(), true);
978 assert_eq!(set.len(), 1);
979 assert!(set.get(&1).is_some());
980 assert_eq!(set.is_empty(), false);
985 let set = IndexSet::<String>::new();
986 println!("{:?}", set);
987 assert_eq!(set.capacity(), 0);
988 assert_eq!(set.len(), 0);
989 assert_eq!(set.is_empty(), true);
994 let insert = [0, 4, 2, 12, 8, 7, 11, 5];
995 let not_present = [1, 3, 6, 9, 10];
996 let mut set = IndexSet::with_capacity(insert.len());
998 for (i, &elt) in enumerate(&insert) {
999 assert_eq!(set.len(), i);
1001 assert_eq!(set.len(), i + 1);
1002 assert_eq!(set.get(&elt), Some(&elt));
1004 println!("{:?}", set);
1006 for &elt in ¬_present {
1007 assert!(set.get(&elt).is_none());
1013 let insert = vec![9, 2, 7, 1, 4, 6, 13];
1014 let present = vec![1, 6, 2];
1015 let mut set = IndexSet::with_capacity(insert.len());
1017 for (i, &elt) in enumerate(&insert) {
1018 assert_eq!(set.len(), i);
1019 let (index, success) = set.insert_full(elt);
1021 assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1022 assert_eq!(set.len(), i + 1);
1025 let len = set.len();
1026 for &elt in &present {
1027 let (index, success) = set.insert_full(elt);
1029 assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1030 assert_eq!(set.len(), len);
1036 let mut set = IndexSet::with_capacity(16);
1038 let mut values = vec![];
1039 values.extend(0..16);
1040 values.extend(128..267);
1043 let old_set = set.clone();
1045 for value in old_set.iter() {
1046 if !set.get(value).is_some() {
1047 println!("old_set: {:?}", old_set);
1048 println!("set: {:?}", set);
1049 panic!("did not find {} in set", value);
1055 assert!(set.get(&i).is_some(), "did not find {}", i);
1061 let mut elements = vec![0, 2, 4, 6, 8];
1062 let mut set: IndexSet<u8> = elements.drain(..).collect();
1064 let (i, v) = set.get_full(&0).unwrap();
1065 assert_eq!(set.len(), 5);
1070 let inserted = set.insert(0);
1071 let (i, v) = set.get_full(&0).unwrap();
1072 assert_eq!(set.len(), 5);
1073 assert_eq!(inserted, false);
1081 let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1082 let mut set = IndexSet::new();
1084 for &elt in &insert {
1088 assert_eq!(set.iter().count(), set.len());
1089 assert_eq!(set.iter().count(), insert.len());
1090 for (a, b) in insert.iter().zip(set.iter()) {
1093 for (i, v) in (0..insert.len()).zip(set.iter()) {
1094 assert_eq!(set.get_index(i).unwrap(), v);
1100 let insert = [0, 4, 2, 12, 8, 7, 11];
1101 let not_present = [1, 3, 6, 9, 10];
1102 let mut set = IndexSet::with_capacity(insert.len());
1105 for (i, &elt) in enumerate(&insert) {
1106 assert_eq!(set.len(), i);
1108 assert_eq!(set.len(), i + 1);
1109 assert_eq!(set.get(&elt), Some(&elt));
1112 println!("{:?}", set);
1113 for &elt in &insert {
1114 set.insert(elt * 10);
1116 for &elt in &insert {
1117 set.insert(elt * 100);
1119 for (i, &elt) in insert.iter().cycle().enumerate().take(100) {
1120 set.insert(elt * 100 + i as i32);
1122 println!("{:?}", set);
1123 for &elt in ¬_present {
1124 assert!(set.get(&elt).is_none());
1130 let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1131 let mut set = IndexSet::new();
1133 for &elt in &insert {
1137 assert_eq!(set.iter().count(), set.len());
1138 assert_eq!(set.iter().count(), insert.len());
1139 for (a, b) in insert.iter().zip(set.iter()) {
1143 let remove_fail = [99, 77];
1144 let remove = [4, 12, 8, 7];
1146 for &value in &remove_fail {
1147 assert!(set.swap_remove_full(&value).is_none());
1149 println!("{:?}", set);
1150 for &value in &remove {
1151 //println!("{:?}", set);
1152 let index = set.get_full(&value).unwrap().0;
1153 assert_eq!(set.swap_remove_full(&value), Some((index, value)));
1155 println!("{:?}", set);
1157 for value in &insert {
1158 assert_eq!(set.get(value).is_some(), !remove.contains(value));
1160 assert_eq!(set.len(), insert.len() - remove.len());
1161 assert_eq!(set.iter().count(), insert.len() - remove.len());
1165 fn swap_remove_index() {
1166 let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1167 let mut set = IndexSet::new();
1169 for &elt in &insert {
1173 let mut vector = insert.to_vec();
1174 let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1];
1176 // check that the same swap remove sequence on vec and set
1177 // have the same result.
1178 for &rm in remove_sequence {
1179 let out_vec = vector.swap_remove(rm);
1180 let out_set = set.swap_remove_index(rm).unwrap();
1181 assert_eq!(out_vec, out_set);
1183 assert_eq!(vector.len(), set.len());
1184 for (a, b) in vector.iter().zip(set.iter()) {
1190 fn partial_eq_and_eq() {
1191 let mut set_a = IndexSet::new();
1194 let mut set_b = set_a.clone();
1195 assert_eq!(set_a, set_b);
1197 assert_ne!(set_a, set_b);
1199 let set_c: IndexSet<_> = set_b.into_iter().collect();
1200 assert_ne!(set_a, set_c);
1201 assert_ne!(set_c, set_a);
1206 let mut set = IndexSet::new();
1207 set.extend(vec![&1, &2, &3, &4]);
1208 set.extend(vec![5, 6]);
1209 assert_eq!(set.into_iter().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5, 6]);
1214 let set_a: IndexSet<_> = (0..3).collect();
1215 let set_b: IndexSet<_> = (3..6).collect();
1216 let set_c: IndexSet<_> = (0..6).collect();
1217 let set_d: IndexSet<_> = (3..9).collect();
1219 assert!(!set_a.is_disjoint(&set_a));
1220 assert!(set_a.is_subset(&set_a));
1221 assert!(set_a.is_superset(&set_a));
1223 assert!(set_a.is_disjoint(&set_b));
1224 assert!(set_b.is_disjoint(&set_a));
1225 assert!(!set_a.is_subset(&set_b));
1226 assert!(!set_b.is_subset(&set_a));
1227 assert!(!set_a.is_superset(&set_b));
1228 assert!(!set_b.is_superset(&set_a));
1230 assert!(!set_a.is_disjoint(&set_c));
1231 assert!(!set_c.is_disjoint(&set_a));
1232 assert!(set_a.is_subset(&set_c));
1233 assert!(!set_c.is_subset(&set_a));
1234 assert!(!set_a.is_superset(&set_c));
1235 assert!(set_c.is_superset(&set_a));
1237 assert!(!set_c.is_disjoint(&set_d));
1238 assert!(!set_d.is_disjoint(&set_c));
1239 assert!(!set_c.is_subset(&set_d));
1240 assert!(!set_d.is_subset(&set_c));
1241 assert!(!set_c.is_superset(&set_d));
1242 assert!(!set_d.is_superset(&set_c));
1246 fn iter_comparisons() {
1247 use std::iter::empty;
1249 fn check<'a, I1, I2>(iter1: I1, iter2: I2)
1250 where I1: Iterator<Item = &'a i32>,
1251 I2: Iterator<Item = i32>,
1253 assert!(iter1.cloned().eq(iter2));
1256 let set_a: IndexSet<_> = (0..3).collect();
1257 let set_b: IndexSet<_> = (3..6).collect();
1258 let set_c: IndexSet<_> = (0..6).collect();
1259 let set_d: IndexSet<_> = (3..9).rev().collect();
1261 check(set_a.difference(&set_a), empty());
1262 check(set_a.symmetric_difference(&set_a), empty());
1263 check(set_a.intersection(&set_a), 0..3);
1264 check(set_a.union(&set_a), 0..3);
1266 check(set_a.difference(&set_b), 0..3);
1267 check(set_b.difference(&set_a), 3..6);
1268 check(set_a.symmetric_difference(&set_b), 0..6);
1269 check(set_b.symmetric_difference(&set_a), (3..6).chain(0..3));
1270 check(set_a.intersection(&set_b), empty());
1271 check(set_b.intersection(&set_a), empty());
1272 check(set_a.union(&set_b), 0..6);
1273 check(set_b.union(&set_a), (3..6).chain(0..3));
1275 check(set_a.difference(&set_c), empty());
1276 check(set_c.difference(&set_a), 3..6);
1277 check(set_a.symmetric_difference(&set_c), 3..6);
1278 check(set_c.symmetric_difference(&set_a), 3..6);
1279 check(set_a.intersection(&set_c), 0..3);
1280 check(set_c.intersection(&set_a), 0..3);
1281 check(set_a.union(&set_c), 0..6);
1282 check(set_c.union(&set_a), 0..6);
1284 check(set_c.difference(&set_d), 0..3);
1285 check(set_d.difference(&set_c), (6..9).rev());
1286 check(set_c.symmetric_difference(&set_d), (0..3).chain((6..9).rev()));
1287 check(set_d.symmetric_difference(&set_c), (6..9).rev().chain(0..3));
1288 check(set_c.intersection(&set_d), 3..6);
1289 check(set_d.intersection(&set_c), (3..6).rev());
1290 check(set_c.union(&set_d), (0..6).chain((6..9).rev()));
1291 check(set_d.union(&set_c), (3..9).rev().chain(0..3));
1296 let empty = IndexSet::<i32>::new();
1297 let set_a: IndexSet<_> = (0..3).collect();
1298 let set_b: IndexSet<_> = (3..6).collect();
1299 let set_c: IndexSet<_> = (0..6).collect();
1300 let set_d: IndexSet<_> = (3..9).rev().collect();
1302 assert_eq!(&set_a & &set_a, set_a);
1303 assert_eq!(&set_a | &set_a, set_a);
1304 assert_eq!(&set_a ^ &set_a, empty);
1305 assert_eq!(&set_a - &set_a, empty);
1307 assert_eq!(&set_a & &set_b, empty);
1308 assert_eq!(&set_b & &set_a, empty);
1309 assert_eq!(&set_a | &set_b, set_c);
1310 assert_eq!(&set_b | &set_a, set_c);
1311 assert_eq!(&set_a ^ &set_b, set_c);
1312 assert_eq!(&set_b ^ &set_a, set_c);
1313 assert_eq!(&set_a - &set_b, set_a);
1314 assert_eq!(&set_b - &set_a, set_b);
1316 assert_eq!(&set_a & &set_c, set_a);
1317 assert_eq!(&set_c & &set_a, set_a);
1318 assert_eq!(&set_a | &set_c, set_c);
1319 assert_eq!(&set_c | &set_a, set_c);
1320 assert_eq!(&set_a ^ &set_c, set_b);
1321 assert_eq!(&set_c ^ &set_a, set_b);
1322 assert_eq!(&set_a - &set_c, empty);
1323 assert_eq!(&set_c - &set_a, set_b);
1325 assert_eq!(&set_c & &set_d, set_b);
1326 assert_eq!(&set_d & &set_c, set_b);
1327 assert_eq!(&set_c | &set_d, &set_a | &set_d);
1328 assert_eq!(&set_d | &set_c, &set_a | &set_d);
1329 assert_eq!(&set_c ^ &set_d, &set_a | &(&set_d - &set_b));
1330 assert_eq!(&set_d ^ &set_c, &set_a | &(&set_d - &set_b));
1331 assert_eq!(&set_c - &set_d, set_a);
1332 assert_eq!(&set_d - &set_c, &set_d - &set_b);