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