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