Bug 1608150 [wpt PR 21112] - Add missing space in `./wpt lint` command line docs...
[gecko.git] / third_party / rust / indexmap / src / set.rs
blobf89123261e92ada55b045628ae5df808eb8a0219
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;
8 use std::fmt;
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};
13 use std::slice;
14 use std::vec;
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
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::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 #[derive(Clone)]
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()
71     }
73     fn as_entries(&self) -> &[Self::Entry] {
74         self.map.as_entries()
75     }
77     fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
78         self.map.as_entries_mut()
79     }
81     fn with_entries<F>(&mut self, f: F)
82         where F: FnOnce(&mut [Self::Entry])
83     {
84         self.map.with_entries(f);
85     }
88 impl<T, S> fmt::Debug for IndexSet<T, S>
89     where T: fmt::Debug + Hash + Eq,
90           S: BuildHasher,
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()
95         } else {
96             // Let the inner `IndexMap` print all of its details
97             f.debug_struct("IndexSet").field("map", &self.map).finish()
98         }
99     }
102 impl<T> IndexSet<T> {
103     /// Create a new set. (Does not allocate.)
104     pub fn new() -> Self {
105         IndexSet { map: IndexMap::new() }
106     }
108     /// Create a new set with capacity for `n` elements.
109     /// (Does not allocate if `n` is zero.)
110     ///
111     /// Computes in **O(n)** time.
112     pub fn with_capacity(n: usize) -> Self {
113         IndexSet { map: IndexMap::with_capacity(n) }
114     }
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.)
120     ///
121     /// Computes in **O(n)** time.
122     pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self
123         where S: BuildHasher
124     {
125         IndexSet { map: IndexMap::with_capacity_and_hasher(n, hash_builder) }
126     }
128     /// Return the number of elements in the set.
129     ///
130     /// Computes in **O(1)** time.
131     pub fn len(&self) -> usize {
132         self.map.len()
133     }
135     /// Returns true if the set contains no elements.
136     ///
137     /// Computes in **O(1)** time.
138     pub fn is_empty(&self) -> bool {
139         self.map.is_empty()
140     }
142     /// Create a new set with `hash_builder`
143     pub fn with_hasher(hash_builder: S) -> Self
144         where S: BuildHasher
145     {
146         IndexSet { map: IndexMap::with_hasher(hash_builder) }
147     }
149     /// Return a reference to the set's `BuildHasher`.
150     pub fn hasher(&self) -> &S
151         where S: BuildHasher
152     {
153         self.map.hasher()
154     }
156     /// Computes in **O(1)** time.
157     pub fn capacity(&self) -> usize {
158         self.map.capacity()
159     }
162 impl<T, S> IndexSet<T, S>
163     where T: Hash + Eq,
164           S: BuildHasher,
166     /// Remove all elements in the set, while preserving its capacity.
167     ///
168     /// Computes in **O(n)** time.
169     pub fn clear(&mut self) {
170         self.map.clear();
171     }
173     /// FIXME Not implemented fully yet
174     pub fn reserve(&mut self, additional: usize) {
175         self.map.reserve(additional);
176     }
178     /// Insert the value into the set.
179     ///
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`.
184     ///
185     /// Computes in **O(1)** time (amortized average).
186     pub fn insert(&mut self, value: T) -> bool {
187         self.map.insert(value, ()).is_none()
188     }
190     /// Insert the value into the set, and get its index.
191     ///
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`.
197     ///
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),
204             Vacant(e) => {
205                 let index = e.index();
206                 e.insert(());
207                 (index, true)
208             }
209         }
210     }
212     /// Return an iterator over the values of the set, in their order
213     pub fn iter(&self) -> Iter<T> {
214         Iter {
215             iter: self.map.keys().iter
216         }
217     }
219     /// Return an iterator over the values that are in `self` but not `other`.
220     ///
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
224     {
225         Difference {
226             iter: self.iter(),
227             other: other,
228         }
229     }
231     /// Return an iterator over the values that are in `self` or `other`,
232     /// but not in both.
233     ///
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
239     {
240         SymmetricDifference {
241             iter: self.difference(other).chain(other.difference(self)),
242         }
243     }
245     /// Return an iterator over the values that are in both `self` and `other`.
246     ///
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
250     {
251         Intersection {
252             iter: self.iter(),
253             other: other,
254         }
255     }
257     /// Return an iterator over all values that are in `self` or `other`.
258     ///
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
263     {
264         Union {
265             iter: self.iter().chain(other.difference(self)),
266         }
267     }
269     /// Return `true` if an equivalent to `value` exists in the set.
270     ///
271     /// Computes in **O(1)** time (average).
272     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
273         where Q: Hash + Equivalent<T>,
274     {
275         self.map.contains_key(value)
276     }
278     /// Return a reference to the value stored in the set, if it is present,
279     /// else `None`.
280     ///
281     /// Computes in **O(1)** time (average).
282     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
283         where Q: Hash + Equivalent<T>,
284     {
285         self.map.get_full(value).map(|(_, x, &())| x)
286     }
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>,
291     {
292         self.map.get_full(value).map(|(i, x, &())| (i, x))
293     }
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.
297     ///
298     /// Computes in **O(1)** time (average).
299     pub fn replace(&mut self, value: T) -> Option<T>
300     {
301         use super::map::Entry::*;
303         match self.map.entry(value) {
304             Vacant(e) => { e.insert(()); None },
305             Occupied(e) => Some(e.replace_key()),
306         }
307     }
309     /// FIXME Same as .swap_remove
310     ///
311     /// Computes in **O(1)** time (average).
312     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
313         where Q: Hash + Equivalent<T>,
314     {
315         self.swap_remove(value)
316     }
318     /// Remove the value from the set, and return `true` if it was present.
319     ///
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!**
323     ///
324     /// Return `false` if `value` was not in the set.
325     ///
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>,
329     {
330         self.map.swap_remove(value).is_some()
331     }
333     /// FIXME Same as .swap_take
334     ///
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>,
338     {
339         self.swap_take(value)
340     }
342     /// Removes and returns the value in the set, if any, that is equal to the
343     /// given one.
344     ///
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!**
348     ///
349     /// Return `None` if `value` was not in the set.
350     ///
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>,
354     {
355         self.map.swap_remove_full(value).map(|(_, x, ())| x)
356     }
358     /// Remove the value from the set return it and the index it had.
359     ///
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!**
363     ///
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>,
367     {
368         self.map.swap_remove_full(value).map(|(i, x, ())| (i, x))
369     }
371     /// Remove the last value
372     ///
373     /// Computes in **O(1)** time (average).
374     pub fn pop(&mut self) -> Option<T> {
375         self.map.pop().map(|(x, ())| x)
376     }
378     /// Scan through each value in the set and keep those where the
379     /// closure `keep` returns `true`.
380     ///
381     /// The elements are visited in order, and remaining elements keep their
382     /// order.
383     ///
384     /// Computes in **O(n)** time (average).
385     pub fn retain<F>(&mut self, mut keep: F)
386         where F: FnMut(&T) -> bool,
387     {
388         self.map.retain(move |x, &mut ()| keep(x))
389     }
391     /// Sort the set’s values by their default ordering.
392     ///
393     /// See `sort_by` for details.
394     pub fn sort(&mut self)
395         where T: Ord,
396     {
397         self.map.sort_keys()
398     }
400     /// Sort the set’s values in place using the comparison function `compare`.
401     ///
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,
405     {
406         self.map.sort_by(move |a, _, b, _| compare(a, b));
407     }
409     /// Sort the values of the set and return a by value iterator of
410     /// the values with the result.
411     ///
412     /// The sort is stable.
413     pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<T>
414         where F: FnMut(&T, &T) -> Ordering
415     {
416         IntoIter {
417             iter: self.map.sorted_by(move |a, &(), b, &()| cmp(a, b)).iter,
418         }
419     }
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> {
424         Drain {
425             iter: self.map.drain(range).iter,
426         }
427     }
430 impl<T, S> IndexSet<T, S> {
431     /// Get a value by index
432     ///
433     /// Valid indices are *0 <= index < self.len()*
434     ///
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)
438     }
440     /// Remove the key-value pair by index
441     ///
442     /// Valid indices are *0 <= index < self.len()*
443     ///
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)
447     }
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> {
463     type Item = 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)
471     }
474 impl<T> ExactSizeIterator for IntoIter<T> {
475     fn len(&self) -> usize {
476         self.iter.len()
477     }
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()
484     }
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> {
500     type Item = &'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)
508     }
511 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
512     fn len(&self) -> usize {
513         self.iter.len()
514     }
517 impl<'a, T> Clone for Iter<'a, T> {
518     fn clone(&self) -> Self {
519         Iter { iter: self.iter.clone() }
520     }
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()
526     }
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> {
541     type Item = 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>
551     where T: Hash + Eq,
552           S: BuildHasher,
554     type Item = &'a T;
555     type IntoIter = Iter<'a, T>;
557     fn into_iter(self) -> Self::IntoIter {
558         self.iter()
559     }
562 impl<T, S> IntoIterator for IndexSet<T, S>
563     where T: Hash + Eq,
564           S: BuildHasher,
566     type Item = T;
567     type IntoIter = IntoIter<T>;
569     fn into_iter(self) -> Self::IntoIter {
570         IntoIter {
571             iter: self.map.into_iter().iter,
572         }
573     }
576 impl<T, S> FromIterator<T> for IndexSet<T, S>
577     where T: Hash + Eq,
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) }
583     }
586 impl<T, S> Extend<T> for IndexSet<T, S>
587     where T: Hash + Eq,
588           S: BuildHasher,
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);
593     }
596 impl<'a, T, S> Extend<&'a T> for IndexSet<T, S>
597     where T: Hash + Eq + Copy,
598           S: BuildHasher,
600     fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iterable: I) {
601         let iter = iterable.into_iter().map(|&x| x);
602         self.extend(iter);
603     }
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() }
613     }
616 impl<T, S1, S2> PartialEq<IndexSet<T, S2>> for IndexSet<T, S1>
617     where T: Hash + Eq,
618           S1: BuildHasher,
619           S2: BuildHasher
621     fn eq(&self, other: &IndexSet<T, S2>) -> bool {
622         self.len() == other.len() && self.is_subset(other)
623     }
626 impl<T, S> Eq for IndexSet<T, S>
627     where T: Eq + Hash,
628           S: BuildHasher
632 impl<T, S> IndexSet<T, S>
633     where T: Eq + Hash,
634           S: BuildHasher
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
639     {
640         if self.len() <= other.len() {
641             self.iter().all(move |value| !other.contains(value))
642         } else {
643             other.iter().all(move |value| !self.contains(value))
644         }
645     }
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
650     {
651         self.len() <= other.len() && self.iter().all(move |value| other.contains(value))
652     }
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
657     {
658         other.is_subset(self)
659     }
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> {
671     iter: Iter<'a, T>,
672     other: &'a IndexSet<T, S>,
675 impl<'a, T, S> Iterator for Difference<'a, T, S>
676     where T: Eq + Hash,
677           S: BuildHasher
679     type Item = &'a T;
681     fn next(&mut self) -> Option<Self::Item> {
682         while let Some(item) = self.iter.next() {
683             if !self.other.contains(item) {
684                 return Some(item);
685             }
686         }
687         None
688     }
690     fn size_hint(&self) -> (usize, Option<usize>) {
691         (0, self.iter.size_hint().1)
692     }
695 impl<'a, T, S> DoubleEndedIterator for Difference<'a, T, S>
696     where T: Eq + Hash,
697           S: BuildHasher
699     fn next_back(&mut self) -> Option<Self::Item> {
700         while let Some(item) = self.iter.next_back() {
701             if !self.other.contains(item) {
702                 return Some(item);
703             }
704         }
705         None
706     }
709 impl<'a, T, S> Clone for Difference<'a, T, S> {
710     fn clone(&self) -> Self {
711         Difference { iter: self.iter.clone(), ..*self }
712     }
715 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
716     where T: fmt::Debug + Eq + Hash,
717           S: BuildHasher
719     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
720         f.debug_list().entries(self.clone()).finish()
721     }
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> {
733     iter: Iter<'a, T>,
734     other: &'a IndexSet<T, S>,
737 impl<'a, T, S> Iterator for Intersection<'a, T, S>
738     where T: Eq + Hash,
739           S: BuildHasher
741     type Item = &'a T;
743     fn next(&mut self) -> Option<Self::Item> {
744         while let Some(item) = self.iter.next() {
745             if self.other.contains(item) {
746                 return Some(item);
747             }
748         }
749         None
750     }
752     fn size_hint(&self) -> (usize, Option<usize>) {
753         (0, self.iter.size_hint().1)
754     }
757 impl<'a, T, S> DoubleEndedIterator for Intersection<'a, T, S>
758     where T: Eq + Hash,
759           S: BuildHasher
761     fn next_back(&mut self) -> Option<Self::Item> {
762         while let Some(item) = self.iter.next_back() {
763             if self.other.contains(item) {
764                 return Some(item);
765             }
766         }
767         None
768     }
771 impl<'a, T, S> Clone for Intersection<'a, T, S> {
772     fn clone(&self) -> Self {
773         Intersection { iter: self.iter.clone(), ..*self }
774     }
777 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
778     where T: fmt::Debug + Eq + Hash,
779           S: BuildHasher,
781     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
782         f.debug_list().entries(self.clone()).finish()
783     }
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>
799     where T: Eq + Hash,
800           S1: BuildHasher,
801           S2: BuildHasher,
803     type Item = &'a T;
805     fn next(&mut self) -> Option<Self::Item> {
806         self.iter.next()
807     }
809     fn size_hint(&self) -> (usize, Option<usize>) {
810         self.iter.size_hint()
811     }
813     fn fold<B, F>(self, init: B, f: F) -> B
814         where F: FnMut(B, Self::Item) -> B
815     {
816         self.iter.fold(init, f)
817     }
820 impl<'a, T, S1, S2> DoubleEndedIterator for SymmetricDifference<'a, T, S1, S2>
821     where T: Eq + Hash,
822           S1: BuildHasher,
823           S2: BuildHasher,
825     fn next_back(&mut self) -> Option<Self::Item> {
826         self.iter.next_back()
827     }
830 impl<'a, T, S1, S2> Clone for SymmetricDifference<'a, T, S1, S2> {
831     fn clone(&self) -> Self {
832         SymmetricDifference { iter: self.iter.clone() }
833     }
836 impl<'a, T, S1, S2> fmt::Debug for SymmetricDifference<'a, T, S1, S2>
837     where T: fmt::Debug + Eq + Hash,
838           S1: BuildHasher,
839           S2: BuildHasher,
841     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842         f.debug_list().entries(self.clone()).finish()
843     }
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>
859     where T: Eq + Hash,
860           S: BuildHasher,
862     type Item = &'a T;
864     fn next(&mut self) -> Option<Self::Item> {
865         self.iter.next()
866     }
868     fn size_hint(&self) -> (usize, Option<usize>) {
869         self.iter.size_hint()
870     }
872     fn fold<B, F>(self, init: B, f: F) -> B
873         where F: FnMut(B, Self::Item) -> B
874     {
875         self.iter.fold(init, f)
876     }
879 impl<'a, T, S> DoubleEndedIterator for Union<'a, T, S>
880     where T: Eq + Hash,
881           S: BuildHasher,
883     fn next_back(&mut self) -> Option<Self::Item> {
884         self.iter.next_back()
885     }
888 impl<'a, T, S> Clone for Union<'a, T, S> {
889     fn clone(&self) -> Self {
890         Union { iter: self.iter.clone() }
891     }
894 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
895     where T: fmt::Debug + Eq + Hash,
896           S: BuildHasher,
898     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
899         f.debug_list().entries(self.clone()).finish()
900     }
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,
907           S2: BuildHasher,
909     type Output = IndexSet<T, S1>;
911     /// Returns the set intersection, cloned into a new set.
912     ///
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()
916     }
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,
922           S2: BuildHasher,
924     type Output = IndexSet<T, S1>;
926     /// Returns the set union, cloned into a new set.
927     ///
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()
932     }
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,
938           S2: BuildHasher,
940     type Output = IndexSet<T, S1>;
942     /// Returns the set symmetric-difference, cloned into a new set.
943     ///
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()
948     }
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,
954           S2: BuildHasher,
956     type Output = IndexSet<T, S1>;
958     /// Returns the set difference, cloned into a new set.
959     ///
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()
963     }
967 #[cfg(test)]
968 mod tests {
969     use super::*;
970     use util::enumerate;
972     #[test]
973     fn it_works() {
974         let mut set = IndexSet::new();
975         assert_eq!(set.is_empty(), true);
976         set.insert(1);
977         set.insert(1);
978         assert_eq!(set.len(), 1);
979         assert!(set.get(&1).is_some());
980         assert_eq!(set.is_empty(), false);
981     }
983     #[test]
984     fn new() {
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);
990     }
992     #[test]
993     fn insert() {
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);
1000             set.insert(elt);
1001             assert_eq!(set.len(), i + 1);
1002             assert_eq!(set.get(&elt), Some(&elt));
1003         }
1004         println!("{:?}", set);
1006         for &elt in &not_present {
1007             assert!(set.get(&elt).is_none());
1008         }
1009     }
1011     #[test]
1012     fn insert_full() {
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);
1020             assert!(success);
1021             assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1022             assert_eq!(set.len(), i + 1);
1023         }
1025         let len = set.len();
1026         for &elt in &present {
1027             let (index, success) = set.insert_full(elt);
1028             assert!(!success);
1029             assert_eq!(Some(index), set.get_full(&elt).map(|x| x.0));
1030             assert_eq!(set.len(), len);
1031         }
1032     }
1034     #[test]
1035     fn insert_2() {
1036         let mut set = IndexSet::with_capacity(16);
1038         let mut values = vec![];
1039         values.extend(0..16);
1040         values.extend(128..267);
1042         for &i in &values {
1043             let old_set = set.clone();
1044             set.insert(i);
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);
1050                 }
1051             }
1052         }
1054         for &i in &values {
1055             assert!(set.get(&i).is_some(), "did not find {}", i);
1056         }
1057     }
1059     #[test]
1060     fn insert_dup() {
1061         let mut elements = vec![0, 2, 4, 6, 8];
1062         let mut set: IndexSet<u8> = elements.drain(..).collect();
1063         {
1064             let (i, v) = set.get_full(&0).unwrap();
1065             assert_eq!(set.len(), 5);
1066             assert_eq!(i, 0);
1067             assert_eq!(*v, 0);
1068         }
1069         {
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);
1074             assert_eq!(i, 0);
1075             assert_eq!(*v, 0);
1076         }
1077     }
1079     #[test]
1080     fn insert_order() {
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 {
1085             set.insert(elt);
1086         }
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()) {
1091             assert_eq!(a, b);
1092         }
1093         for (i, v) in (0..insert.len()).zip(set.iter()) {
1094             assert_eq!(set.get_index(i).unwrap(), v);
1095         }
1096     }
1098     #[test]
1099     fn grow() {
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);
1107             set.insert(elt);
1108             assert_eq!(set.len(), i + 1);
1109             assert_eq!(set.get(&elt), Some(&elt));
1110         }
1112         println!("{:?}", set);
1113         for &elt in &insert {
1114             set.insert(elt * 10);
1115         }
1116         for &elt in &insert {
1117             set.insert(elt * 100);
1118         }
1119         for (i, &elt) in insert.iter().cycle().enumerate().take(100) {
1120             set.insert(elt * 100 + i as i32);
1121         }
1122         println!("{:?}", set);
1123         for &elt in &not_present {
1124             assert!(set.get(&elt).is_none());
1125         }
1126     }
1128     #[test]
1129     fn remove() {
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 {
1134             set.insert(elt);
1135         }
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()) {
1140             assert_eq!(a, b);
1141         }
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());
1148         }
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)));
1154         }
1155         println!("{:?}", set);
1157         for value in &insert {
1158             assert_eq!(set.get(value).is_some(), !remove.contains(value));
1159         }
1160         assert_eq!(set.len(), insert.len() - remove.len());
1161         assert_eq!(set.iter().count(), insert.len() - remove.len());
1162     }
1164     #[test]
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 {
1170             set.insert(elt);
1171         }
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);
1182         }
1183         assert_eq!(vector.len(), set.len());
1184         for (a, b) in vector.iter().zip(set.iter()) {
1185             assert_eq!(a, b);
1186         }
1187     }
1189     #[test]
1190     fn partial_eq_and_eq() {
1191         let mut set_a = IndexSet::new();
1192         set_a.insert(1);
1193         set_a.insert(2);
1194         let mut set_b = set_a.clone();
1195         assert_eq!(set_a, set_b);
1196         set_b.remove(&1);
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);
1202     }
1204     #[test]
1205     fn extend() {
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]);
1210     }
1212     #[test]
1213     fn comparisons() {
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));
1243     }
1245     #[test]
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>,
1252         {
1253             assert!(iter1.cloned().eq(iter2));
1254         }
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));
1292     }
1294     #[test]
1295     fn ops() {
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);
1333     }