vecmap/set.rs
1//! `VecSet` is a vector-based set implementation which retains the order of inserted elements.
2
3mod impls;
4mod iter;
5#[cfg(feature = "serde")]
6mod serde;
7
8use super::{Entries, TryReserveError, keyed::KeyedVecSet};
9use alloc::vec::Vec;
10use core::borrow::Borrow;
11use core::cmp::Ordering;
12use core::ops::RangeBounds;
13
14pub use self::iter::*;
15
16/// A vector-based set implementation which retains the order of inserted elements.
17///
18/// Internally it is represented as a `Vec<T>` to support keys that are neither `Hash` nor `Ord`.
19#[derive(Clone, Debug)]
20pub struct VecSet<T> {
21 base: KeyedVecSet<T, T>,
22}
23
24impl<T> VecSet<T> {
25 /// Create a new set. (Does not allocate.)
26 ///
27 /// # Examples
28 ///
29 /// ```
30 /// use vecmap::VecSet;
31 ///
32 /// let mut set: VecSet<&str> = VecSet::new();
33 /// ```
34 pub const fn new() -> Self {
35 VecSet {
36 base: KeyedVecSet::new(),
37 }
38 }
39
40 /// Create a new set with capacity for `capacity` key-value pairs. (Does not allocate if
41 /// `capacity` is zero.)
42 ///
43 /// # Examples
44 ///
45 /// ```
46 /// use vecmap::VecSet;
47 ///
48 /// let mut set: VecSet<&str> = VecSet::with_capacity(10);
49 /// assert_eq!(set.len(), 0);
50 /// assert!(set.capacity() >= 10);
51 /// ```
52 pub fn with_capacity(capacity: usize) -> Self {
53 VecSet {
54 base: KeyedVecSet::with_capacity(capacity),
55 }
56 }
57
58 /// Returns the number of elements the set can hold without reallocating.
59 ///
60 /// # Examples
61 ///
62 /// ```
63 /// use vecmap::VecSet;
64 ///
65 /// let mut set: VecSet<&str> = VecSet::with_capacity(10);
66 /// assert_eq!(set.capacity(), 10);
67 /// ```
68 pub fn capacity(&self) -> usize {
69 self.base.capacity()
70 }
71
72 /// Returns the number of elements in the set, also referred to as its 'length'.
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// use vecmap::VecSet;
78 ///
79 /// let mut a = VecSet::new();
80 /// assert_eq!(a.len(), 0);
81 /// a.insert(1);
82 /// assert_eq!(a.len(), 1);
83 /// ```
84 pub fn len(&self) -> usize {
85 self.base.len()
86 }
87
88 /// Returns `true` if the set contains no elements.
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// use vecmap::VecSet;
94 ///
95 /// let mut a = VecSet::new();
96 /// assert!(a.is_empty());
97 /// a.insert(1);
98 /// assert!(!a.is_empty());
99 /// ```
100 pub fn is_empty(&self) -> bool {
101 self.base.is_empty()
102 }
103
104 /// Clears the set, removing all elements.
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// use vecmap::VecSet;
110 ///
111 /// let mut a = VecSet::new();
112 /// a.insert(1);
113 /// a.clear();
114 /// assert!(a.is_empty());
115 /// ```
116 pub fn clear(&mut self) {
117 self.base.clear();
118 }
119
120 /// Shortens the set, keeping the first `len` elements and dropping the rest.
121 ///
122 /// If `len` is greater than the set's current length, this has no effect.
123 ///
124 /// # Examples
125 ///
126 /// Truncating a four element set to two elements:
127 ///
128 /// ```
129 /// use vecmap::VecSet;
130 ///
131 /// let mut set = VecSet::from(["a", "b", "c", "d"]);
132 /// set.truncate(2);
133 /// assert_eq!(set, VecSet::from(["a", "b"]));
134 /// ```
135 ///
136 /// No truncation occurs when `len` is greater than the set's current length:
137 ///
138 /// ```
139 /// use vecmap::VecSet;
140 ///
141 /// let mut set = VecSet::from(["a", "b", "c", "d"]);
142 /// set.truncate(8);
143 /// assert_eq!(set, VecSet::from(["a", "b", "c", "d"]));
144 /// ```
145 pub fn truncate(&mut self, len: usize) {
146 self.base.truncate(len);
147 }
148
149 /// Reverses the order of entries in the set, in place.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use vecmap::VecSet;
155 ///
156 /// let mut set = VecSet::from_iter(["a", "b", "c"]);
157 /// set.reverse();
158 /// assert_eq!(set, VecSet::from_iter(["c", "b", "a"]));
159 /// ```
160 pub fn reverse(&mut self) {
161 self.base.reverse();
162 }
163
164 /// Reserves capacity for at least `additional` more elements to be inserted in the given
165 /// `VecSet<T>`. The collection may reserve more space to speculatively avoid frequent
166 /// reallocations. After calling `reserve`, capacity will be greater than or equal to
167 /// `self.len() + additional`. Does nothing if capacity is already sufficient.
168 ///
169 /// # Panics
170 ///
171 /// Panics if the new capacity exceeds `isize::MAX` bytes.
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use vecmap::VecSet;
177 ///
178 /// let mut set = VecSet::from_iter(["a"]);
179 /// set.reserve(10);
180 /// assert!(set.capacity() >= 11);
181 /// ```
182 pub fn reserve(&mut self, additional: usize) {
183 self.base.reserve(additional);
184 }
185
186 /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
187 /// given `VecSet<T>`. Unlike [`reserve`], this will not deliberately over-allocate to
188 /// speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be
189 /// greater than or equal to `self.len() + additional`. Does nothing if the capacity is already
190 /// sufficient.
191 ///
192 /// Note that the allocator may give the collection more space than it requests. Therefore,
193 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
194 /// insertions are expected.
195 ///
196 /// [`reserve`]: VecSet::reserve
197 ///
198 /// # Panics
199 ///
200 /// Panics if the new capacity exceeds `isize::MAX` bytes.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// use vecmap::VecSet;
206 ///
207 /// let mut set = VecSet::from_iter(["a"]);
208 /// set.reserve(10);
209 /// assert!(set.capacity() >= 11);
210 /// ```
211 pub fn reserve_exact(&mut self, additional: usize) {
212 self.base.reserve_exact(additional);
213 }
214
215 /// Tries to reserve capacity for at least `additional` more elements to be inserted in the
216 /// given `VecSet<T>`. The collection may reserve more space to speculatively avoid frequent
217 /// reallocations. After calling `try_reserve`, capacity will be greater than or equal to
218 /// `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already
219 /// sufficient. This method preserves the contents even if an error occurs.
220 ///
221 /// # Errors
222 ///
223 /// If the capacity overflows, or the allocator reports a failure, then an error
224 /// is returned.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// use vecmap::{TryReserveError, VecSet};
230 ///
231 /// fn process_data(data: &[u32]) -> Result<VecSet<u32>, TryReserveError> {
232 /// let mut output = VecSet::new();
233 ///
234 /// // Pre-reserve the memory, exiting if we can't
235 /// output.try_reserve(data.len())?;
236 ///
237 /// // Now we know this can't OOM in the middle of our complex work
238 /// output.extend(data.iter().map(|&v| {
239 /// v * 2 + 5 // very complicated
240 /// }));
241 ///
242 /// Ok(output)
243 /// }
244 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing?");
245 /// ```
246 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
247 self.base.try_reserve(additional)
248 }
249
250 /// Tries to reserve the minimum capacity for at least `additional` elements to be inserted in
251 /// the given `VecSet<T>`. Unlike [`try_reserve`], this will not deliberately over-allocate
252 /// to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity
253 /// will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does
254 /// nothing if the capacity is already sufficient.
255 ///
256 /// Note that the allocator may give the collection more space than it requests. Therefore,
257 /// capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`] if future
258 /// insertions are expected.
259 ///
260 /// [`try_reserve`]: VecSet::try_reserve
261 ///
262 /// # Errors
263 ///
264 /// If the capacity overflows, or the allocator reports a failure, then an error is returned.
265 ///
266 /// # Examples
267 ///
268 /// ```
269 /// use vecmap::{TryReserveError, VecSet};
270 ///
271 /// fn process_data(data: &[u32]) -> Result<VecSet<u32>, TryReserveError> {
272 /// let mut output = VecSet::new();
273 ///
274 /// // Pre-reserve the memory, exiting if we can't
275 /// output.try_reserve_exact(data.len())?;
276 ///
277 /// // Now we know this can't OOM in the middle of our complex work
278 /// output.extend(data.iter().map(|&v| {
279 /// v * 2 + 5 // very complicated
280 /// }));
281 ///
282 /// Ok(output)
283 /// }
284 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing?");
285 /// ```
286 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
287 self.base.try_reserve_exact(additional)
288 }
289
290 /// Retains only the elements specified by the predicate.
291 ///
292 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use vecmap::VecSet;
298 ///
299 /// let mut set: VecSet<i32> = VecSet::from([0, 1, 2, 3, 4, 5, 6, 7]);
300 /// set.retain(|&e| e % 2 == 0);
301 /// assert_eq!(set.len(), 4);
302 /// ```
303 pub fn retain<F>(&mut self, f: F)
304 where
305 F: FnMut(&T) -> bool,
306 {
307 self.base.retain(f);
308 }
309
310 /// Shrinks the capacity of the set as much as possible. It will drop down as much as possible
311 /// while maintaining the internal rules and possibly leaving some space in accordance with the
312 /// resize policy.
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use vecmap::VecSet;
318 ///
319 /// let mut set: VecSet<i32> = VecSet::with_capacity(100);
320 /// set.insert(1);
321 /// set.insert(2);
322 /// assert!(set.capacity() >= 100);
323 /// set.shrink_to_fit();
324 /// assert!(set.capacity() >= 2);
325 /// ```
326 pub fn shrink_to_fit(&mut self) {
327 self.base.shrink_to_fit();
328 }
329
330 /// Shrinks the capacity of the set with a lower limit. It will drop down no lower than the
331 /// supplied limit while maintaining the internal rules and possibly leaving some space in
332 /// accordance with the resize policy.
333 ///
334 /// If the current capacity is less than the lower limit, this is a no-op.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use vecmap::VecSet;
340 ///
341 /// let mut set: VecSet<i32> = VecSet::with_capacity(100);
342 /// set.insert(1);
343 /// set.insert(2);
344 /// assert!(set.capacity() >= 100);
345 /// set.shrink_to(10);
346 /// assert!(set.capacity() >= 10);
347 /// set.shrink_to(0);
348 /// assert!(set.capacity() >= 2);
349 /// ```
350 pub fn shrink_to(&mut self, min_capacity: usize) {
351 self.base.shrink_to(min_capacity);
352 }
353
354 /// Splits the set into two at the given index.
355 ///
356 /// Returns a newly allocated set containing the elements in the range `[at, len)`. After the
357 /// call, the original set will be left containing the elements `[0, at)` with its previous
358 /// capacity unchanged.
359 ///
360 /// # Panics
361 ///
362 /// Panics if `at > len`.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use vecmap::VecSet;
368 ///
369 /// let mut set = VecSet::from(["a", "b", "c"]);
370 /// let set2 = set.split_off(1);
371 /// assert_eq!(set, VecSet::from(["a"]));
372 /// assert_eq!(set2, VecSet::from(["b", "c"]));
373 /// ```
374 pub fn split_off(&mut self, at: usize) -> VecSet<T> {
375 VecSet {
376 base: self.base.split_off(at),
377 }
378 }
379
380 /// Search over a sorted set for a value.
381 ///
382 /// Returns the position where that key is present, or the position where it can be inserted to
383 /// maintain the sort. See [`slice::binary_search`] for more details.
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// use vecmap::VecSet;
389 ///
390 /// let set = VecSet::from(["a", "b", "d"]);
391 /// assert_eq!(set.binary_search(&"b"), Ok(1));
392 /// assert_eq!(set.binary_search(&"c"), Err(2));
393 /// assert_eq!(set.binary_search(&"z"), Err(3));
394 /// ```
395 pub fn binary_search(&self, value: &T) -> Result<usize, usize>
396 where
397 T: Ord,
398 {
399 self.binary_search_by(|v| v.cmp(value))
400 }
401
402 /// Search over a sorted set with a comparator function.
403 ///
404 /// Returns the position where that value is present, or the position where it can be inserted
405 /// to maintain the sort. See [`slice::binary_search_by`] for more details.
406 ///
407 /// # Examples
408 ///
409 /// ```
410 /// use vecmap::VecSet;
411 ///
412 /// let set = VecSet::from(["a", "b", "d"]);
413 ///
414 /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"b")), Ok(1));
415 /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"c")), Err(2));
416 /// assert_eq!(set.binary_search_by(|probe| probe.cmp(&"z")), Err(3));
417 /// ```
418 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
419 where
420 F: FnMut(&'a T) -> Ordering,
421 {
422 self.as_slice().binary_search_by(f)
423 }
424
425 /// Search over a sorted set with an extraction function.
426 ///
427 /// Returns the position where that value is present, or the position where it can be inserted
428 /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
429 ///
430 /// # Examples
431 ///
432 /// ```
433 /// use vecmap::VecSet;
434 ///
435 /// let map = VecSet::from([("a", 1), ("b", 2), ("d", 4)]);
436 /// assert_eq!(map.binary_search_by_key(&"b", |&(k, _)| k), Ok(1));
437 /// assert_eq!(map.binary_search_by_key(&"c", |&(k, _)| k), Err(2));
438 /// assert_eq!(map.binary_search_by_key(&"z", |&(k, _)| k), Err(3));
439 /// assert_eq!(map.binary_search_by_key(&4, |&(_, v)| v), Ok(2));
440 /// ```
441 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
442 where
443 F: FnMut(&'a T) -> B,
444 B: Ord,
445 {
446 self.as_slice().binary_search_by_key(b, f)
447 }
448
449 /// Returns the index of the partition point of a sorted set according to the given predicate
450 /// (the index of the first element of the second partition).
451 ///
452 /// See [`slice::partition_point`] for more details.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// use vecmap::VecSet;
458 ///
459 /// let map = VecSet::from([1, 2, 4]);
460 /// assert_eq!(map.partition_point(|&v| v < 2), 1);
461 /// assert_eq!(map.partition_point(|&v| v > 100), 0);
462 /// assert_eq!(map.partition_point(|&v| v < 100), 3);
463 /// ```
464 pub fn partition_point<P>(&self, pred: P) -> usize
465 where
466 P: FnMut(&T) -> bool,
467 {
468 self.as_slice().partition_point(pred)
469 }
470
471 /// Removes the specified range from the vector in bulk, returning all removed elements as an
472 /// iterator. If the iterator is dropped before being fully consumed, it drops the remaining
473 /// removed elements.
474 ///
475 /// The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
476 ///
477 /// # Panics
478 ///
479 /// Panics if the starting point is greater than the end point or if the end point is greater
480 /// than the length of the vector.
481 ///
482 /// # Examples
483 ///
484 /// ```
485 /// use vecmap::VecSet;
486 ///
487 /// let mut v = VecSet::from([1, 2, 3]);
488 /// let u: VecSet<_> = v.drain(1..).collect();
489 /// assert_eq!(v, VecSet::from([1]));
490 /// assert_eq!(u, VecSet::from([2, 3]));
491 ///
492 /// // A full range clears the vector, like `clear()` does
493 /// v.drain(..);
494 /// assert_eq!(v, VecSet::new());
495 /// ```
496 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
497 where
498 R: RangeBounds<usize>,
499 {
500 Drain::new(self, range)
501 }
502
503 /// An iterator visiting all elements in insertion order. The iterator element type is
504 /// `&'a T`.
505 ///
506 /// # Examples
507 ///
508 /// ```
509 /// use vecmap::VecSet;
510 ///
511 /// let set = VecSet::from(["a", "b", "c"]);
512 ///
513 /// for elem in set.iter() {
514 /// println!("elem: {elem}");
515 /// }
516 /// ```
517 pub fn iter(&self) -> Iter<'_, T> {
518 Iter::new(self.as_entries())
519 }
520
521 /// Sorts the set.
522 ///
523 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
524 /// worst-case.
525 ///
526 /// When applicable, unstable sorting is preferred because it is generally faster than stable
527 /// sorting and it doesn't allocate auxiliary memory. See
528 /// [`sort_unstable`](VecSet::sort_unstable).
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// use vecmap::VecSet;
534 ///
535 /// let mut set = VecSet::from(["b", "a", "c"]);
536 ///
537 /// set.sort();
538 /// let vec: Vec<_> = set.into_iter().collect();
539 /// assert_eq!(vec, ["a", "b", "c"]);
540 /// ```
541 pub fn sort(&mut self)
542 where
543 T: Ord,
544 {
545 self.base.sort_by(core::cmp::Ord::cmp);
546 }
547
548 /// Sorts the set.
549 ///
550 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
551 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
552 ///
553 /// # Examples
554 ///
555 /// ```
556 /// use vecmap::VecSet;
557 ///
558 /// let mut set = VecSet::from(["b", "a", "c"]);
559 ///
560 /// set.sort_unstable();
561 /// let vec: Vec<_> = set.into_iter().collect();
562 /// assert_eq!(vec, ["a", "b", "c"]);
563 /// ```
564 pub fn sort_unstable(&mut self)
565 where
566 T: Ord,
567 {
568 self.base.sort_unstable_by(core::cmp::Ord::cmp);
569 }
570
571 /// Sorts the set with a comparator function.
572 ///
573 /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
574 /// worst-case.
575 ///
576 /// # Examples
577 ///
578 /// ```
579 /// use vecmap::VecSet;
580 ///
581 /// let mut set = VecSet::from(["b", "a", "c"]);
582 ///
583 /// set.sort_by(|a, b| b.cmp(&a));
584 /// let vec: Vec<_> = set.into_iter().collect();
585 /// assert_eq!(vec, ["c", "b", "a"]);
586 /// ```
587 pub fn sort_by<F>(&mut self, compare: F)
588 where
589 F: FnMut(&T, &T) -> Ordering,
590 {
591 self.base.sort_by(compare);
592 }
593
594 /// Sorts the set with a comparator function.
595 ///
596 /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
597 /// allocate), and *O*(*n* \* log(*n*)) worst-case.
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use vecmap::VecSet;
603 ///
604 /// let mut set = VecSet::from(["b", "a", "c"]);
605 ///
606 /// set.sort_unstable_by(|a, b| b.cmp(&a));
607 /// let vec: Vec<_> = set.into_iter().collect();
608 /// assert_eq!(vec, ["c", "b", "a"]);
609 /// ```
610 pub fn sort_unstable_by<F>(&mut self, compare: F)
611 where
612 F: FnMut(&T, &T) -> Ordering,
613 {
614 self.base.sort_unstable_by(compare);
615 }
616
617 /// Sort the set’s values in place using a key extraction function.
618 ///
619 /// During sorting, the function is called at most once per entry, by using temporary storage
620 /// to remember the results of its evaluation. The order of calls to the function is
621 /// unspecified and may change between versions of `vecmap-rs` or the standard library.
622 ///
623 /// See [`slice::sort_by_cached_key`] for more details.
624 ///
625 /// # Examples
626 ///
627 /// ```
628 /// use vecmap::VecSet;
629 ///
630 /// let mut set = VecSet::from(["b", "a", "c"]);
631 ///
632 /// set.sort_by_cached_key(|k| k.to_string());
633 /// assert_eq!(set.as_slice(), ["a", "b", "c"]);
634 /// ```
635 pub fn sort_by_cached_key<K, F>(&mut self, sort_key: F)
636 where
637 K: Ord,
638 F: FnMut(&T) -> K,
639 {
640 self.base.sort_by_cached_key(sort_key);
641 }
642
643 /// Extracts a slice containing the set elements.
644 ///
645 /// ```
646 /// use vecmap::VecSet;
647 ///
648 /// let set = VecSet::from(["b", "a", "c"]);
649 /// let slice = set.as_slice();
650 /// assert_eq!(slice, ["b", "a", "c"]);
651 /// ```
652 pub fn as_slice(&self) -> &[T] {
653 self.base.as_slice()
654 }
655
656 /// Copies the set elements into a new `Vec<T>`.
657 ///
658 /// ```
659 /// use vecmap::VecSet;
660 ///
661 /// let set = VecSet::from(["b", "a", "c"]);
662 /// let vec = set.to_vec();
663 /// assert_eq!(vec, ["b", "a", "c"]);
664 /// // Here, `set` and `vec` can be modified independently.
665 /// ```
666 pub fn to_vec(&self) -> Vec<T>
667 where
668 T: Clone,
669 {
670 self.base.to_vec()
671 }
672
673 /// Takes ownership of the set and returns its elements as a `Vec<T>`.
674 ///
675 /// ```
676 /// use vecmap::VecSet;
677 ///
678 /// let set = VecSet::from(["b", "a", "c"]);
679 /// let vec = set.into_vec();
680 /// assert_eq!(vec, ["b", "a", "c"]);
681 /// ```
682 pub fn into_vec(self) -> Vec<T> {
683 self.base.into_vec()
684 }
685
686 /// Takes ownership of provided vector and converts it into `VecSet`.
687 ///
688 /// # Safety
689 ///
690 /// The vector must have no duplicate elements. One way to guarantee it is to sort the vector
691 /// (e.g. by using [`[T]::sort`][slice-sort]) and then drop duplicate elements (e.g. by using
692 /// [`Vec::dedup`]).
693 ///
694 /// # Example
695 ///
696 /// ```
697 /// use vecmap::VecSet;
698 ///
699 /// let mut vec = vec!["b", "a", "c", "b"];
700 /// vec.sort();
701 /// vec.dedup();
702 /// // SAFETY: We've just deduplicated the vector.
703 /// let set = unsafe { VecSet::from_vec_unchecked(vec) };
704 ///
705 /// assert_eq!(set, VecSet::from(["b", "a", "c"]));
706 /// ```
707 ///
708 /// [slice-sort]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort
709 pub unsafe fn from_vec_unchecked(vec: Vec<T>) -> Self {
710 VecSet {
711 base: unsafe { KeyedVecSet::from_vec_unchecked(vec) },
712 }
713 }
714}
715
716// Lookup operations.
717impl<T> VecSet<T> {
718 /// Return `true` if an equivalent to `key` exists in the set.
719 ///
720 /// # Examples
721 ///
722 /// ```
723 /// use vecmap::VecSet;
724 ///
725 /// let mut set = VecSet::new();
726 /// set.insert(1);
727 /// assert_eq!(set.contains(&1), true);
728 /// assert_eq!(set.contains(&2), false);
729 /// ```
730 pub fn contains<Q>(&self, value: &Q) -> bool
731 where
732 T: Borrow<Q>,
733 Q: Eq + ?Sized,
734 {
735 self.base.contains_key(value)
736 }
737
738 /// Get the first element.
739 ///
740 /// ```
741 /// use vecmap::VecSet;
742 ///
743 /// let mut set = VecSet::from_iter(["a", "b"]);
744 /// assert_eq!(set.first(), Some(&"a"));
745 /// ```
746 pub fn first(&self) -> Option<&T> {
747 self.base.first()
748 }
749
750 /// Get the last element.
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// use vecmap::VecSet;
756 ///
757 /// let mut set = VecSet::from_iter(["a", "b"]);
758 /// assert_eq!(set.last(), Some(&"b"));
759 /// set.pop();
760 /// set.pop();
761 /// assert_eq!(set.last(), None);
762 /// ```
763 pub fn last(&self) -> Option<&T> {
764 self.base.last()
765 }
766
767 /// Returns a reference to the value in the set, if any, that is equal to the given value.
768 ///
769 /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
770 /// *must* match those for the value type.
771 ///
772 /// # Examples
773 ///
774 /// ```
775 /// use vecmap::VecSet;
776 ///
777 /// let set = VecSet::from([1, 2, 3]);
778 /// assert_eq!(set.get(&2), Some(&2));
779 /// assert_eq!(set.get(&4), None);
780 /// ```
781 pub fn get<Q>(&self, value: &Q) -> Option<&T>
782 where
783 T: Borrow<Q>,
784 Q: ?Sized + Eq,
785 {
786 self.base.get(value)
787 }
788
789 /// Return references to the element stored at `index`, if it is present, else `None`.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// use vecmap::VecSet;
795 ///
796 /// let mut set = VecSet::new();
797 /// set.insert(1);
798 /// assert_eq!(set.get_index(0), Some(&1));
799 /// assert_eq!(set.get_index(1), None);
800 /// ```
801 pub fn get_index(&self, index: usize) -> Option<&T> {
802 self.base.get_index(index)
803 }
804
805 /// Returns the index and a reference to the value in the set, if any, that is equal to the
806 /// given value.
807 ///
808 /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
809 /// *must* match those for the value type.
810 ///
811 /// # Examples
812 ///
813 /// ```
814 /// use vecmap::VecSet;
815 ///
816 /// let set = VecSet::from([1, 2, 3]);
817 /// assert_eq!(set.get_full(&2), Some((1, &2)));
818 /// assert_eq!(set.get_full(&4), None);
819 /// ```
820 pub fn get_full<Q>(&self, value: &Q) -> Option<(usize, &T)>
821 where
822 T: Borrow<Q>,
823 Q: ?Sized + Eq,
824 {
825 self.base.get_full(value)
826 }
827
828 /// Return item index, if it exists in the set.
829 ///
830 /// # Examples
831 ///
832 /// ```
833 /// use vecmap::VecSet;
834 ///
835 /// let mut set = VecSet::new();
836 /// set.insert("a");
837 /// set.insert("b");
838 /// assert_eq!(set.get_index_of("a"), Some(0));
839 /// assert_eq!(set.get_index_of("b"), Some(1));
840 /// assert_eq!(set.get_index_of("c"), None);
841 /// ```
842 pub fn get_index_of<Q>(&self, value: &Q) -> Option<usize>
843 where
844 T: Borrow<Q>,
845 Q: Eq + ?Sized,
846 {
847 self.base.get_index_of(value)
848 }
849}
850
851// Removal operations.
852impl<T> VecSet<T> {
853 /// Removes the last element from the set and returns it, or [`None`] if it is empty.
854 ///
855 /// # Examples
856 ///
857 /// ```
858 /// use vecmap::VecSet;
859 ///
860 /// let mut set = VecSet::from_iter(["a", "b"]);
861 /// assert_eq!(set.pop(), Some("b"));
862 /// assert_eq!(set.pop(), Some("a"));
863 /// assert!(set.is_empty());
864 /// assert_eq!(set.pop(), None);
865 /// ```
866 pub fn pop(&mut self) -> Option<T> {
867 self.base.pop()
868 }
869
870 /// Remove the element equivalent to `value`.
871 ///
872 /// Like `Vec::remove`, the element is removed by shifting all of the elements that follow it,
873 /// preserving their relative order. **This perturbs the index of all of those elements!**
874 ///
875 /// Returns `true` if `value` was found in the set.
876 ///
877 /// # Examples
878 ///
879 /// ```
880 /// use vecmap::VecSet;
881 ///
882 /// let mut set = VecSet::from_iter([1, 2, 3, 4]);
883 /// assert_eq!(set.remove(&2), true);
884 /// assert_eq!(set.remove(&2), false);
885 /// assert_eq!(set, VecSet::from_iter([1, 3, 4]));
886 /// ```
887 pub fn remove<Q>(&mut self, value: &Q) -> bool
888 where
889 T: Borrow<Q>,
890 Q: Eq + ?Sized,
891 {
892 self.base.remove(value).is_some()
893 }
894
895 /// Removes and returns the element at position `index` within the set, shifting all elements
896 /// after it to the left.
897 ///
898 /// If you don't need the order of elements to be preserved, use [`swap_remove`] instead.
899 ///
900 /// [`swap_remove`]: VecSet::swap_remove
901 ///
902 /// # Panics
903 ///
904 /// Panics if `index` is out of bounds.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use vecmap::VecSet;
910 ///
911 /// let mut v = VecSet::from(["a", "b", "c"]);
912 /// assert_eq!(v.remove_index(1), "b");
913 /// assert_eq!(v, VecSet::from(["a", "c"]));
914 /// ```
915 pub fn remove_index(&mut self, index: usize) -> T {
916 self.base.remove_index(index)
917 }
918
919 /// Remove the element equivalent to `value`.
920 ///
921 /// Like `Vec::swap_remove`, the element is removed by swapping it with the last element of the
922 /// map and popping it off. **This perturbs the position of what used to be the last element!**
923 ///
924 /// Returns `true` if `value` was found in the set.
925 ///
926 /// ```
927 /// use vecmap::VecSet;
928 ///
929 /// let mut set = VecSet::from_iter([1, 2, 3, 4]);
930 /// assert_eq!(set.swap_remove(&2), true);
931 /// assert_eq!(set.swap_remove(&2), false);
932 /// assert_eq!(set, VecSet::from_iter([1, 4, 3]));
933 /// ```
934 pub fn swap_remove<Q>(&mut self, value: &Q) -> bool
935 where
936 T: Borrow<Q>,
937 Q: Eq + ?Sized,
938 {
939 self.base.swap_remove(value).is_some()
940 }
941
942 /// Removes an element from the set and returns it.
943 ///
944 /// The removed element is replaced by the last element of the set.
945 ///
946 /// If you need to preserve the element order, use [`remove`] instead.
947 ///
948 /// [`remove`]: VecSet::remove
949 ///
950 /// # Panics
951 ///
952 /// Panics if `index` is out of bounds.
953 ///
954 /// # Examples
955 ///
956 /// ```
957 /// use vecmap::VecSet;
958 ///
959 /// let mut v = VecSet::from(["foo", "bar", "baz", "qux"]);
960 ///
961 /// assert_eq!(v.swap_remove_index(0), "foo");
962 /// assert_eq!(v, VecSet::from(["qux", "bar", "baz"]));
963 ///
964 /// assert_eq!(v.swap_remove_index(0), "qux");
965 /// assert_eq!(v, VecSet::from(["baz", "bar"]));
966 /// ```
967 pub fn swap_remove_index(&mut self, index: usize) -> T {
968 self.base.swap_remove_index(index)
969 }
970
971 /// Swaps the position of two elements in the set.
972 ///
973 /// # Arguments
974 ///
975 /// * a - The index of the first element
976 /// * b - The index of the second element
977 ///
978 /// # Panics
979 ///
980 /// Panics if `a` or `b` are out of bounds.
981 ///
982 /// # Examples
983 ///
984 /// ```
985 /// use vecmap::VecSet;
986 ///
987 /// let mut set = VecSet::from(["a", "b", "c", "d"]);
988 /// set.swap_indices(1, 3);
989 /// assert_eq!(set.to_vec(), ["a", "d", "c", "b"]);
990 /// ```
991 pub fn swap_indices(&mut self, a: usize, b: usize) {
992 self.base.swap_indices(a, b);
993 }
994
995 /// Removes and returns the value in the set, if any, that is equal to the given one.
996 ///
997 /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
998 /// *must* match those for the value type.
999 ///
1000 /// Like `Vec::remove`, the element is removed by shifting all of the elements that follow it,
1001 /// preserving their relative order. **This perturbs the index of all of those elements!**
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```
1006 /// use vecmap::VecSet;
1007 ///
1008 /// let mut set = VecSet::from([1, 2, 3]);
1009 /// assert_eq!(set.take(&2), Some(2));
1010 /// assert_eq!(set.take(&2), None);
1011 /// ```
1012 pub fn take<Q>(&mut self, value: &Q) -> Option<T>
1013 where
1014 T: Borrow<Q>,
1015 Q: ?Sized + Eq,
1016 {
1017 self.base.remove(value)
1018 }
1019
1020 /// Removes and returns the value in the set, if any, that is equal to the given one.
1021 ///
1022 /// The value may be any borrowed form of the set's value type, but [`Eq`] on the borrowed form
1023 /// *must* match those for the value type.
1024 ///
1025 /// Like `Vec::swap_remove`, the element is removed by swapping it with the last element of the
1026 /// map and popping it off. **This perturbs the position of what used to be the last element!**
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// use vecmap::VecSet;
1032 ///
1033 /// let mut set = VecSet::from([1, 2, 3]);
1034 /// assert_eq!(set.take(&2), Some(2));
1035 /// assert_eq!(set.take(&2), None);
1036 /// ```
1037 pub fn swap_take<Q>(&mut self, value: &Q) -> Option<T>
1038 where
1039 T: Borrow<Q>,
1040 Q: ?Sized + Eq,
1041 {
1042 self.base.swap_remove(value)
1043 }
1044}
1045
1046// Insertion operations.
1047impl<T> VecSet<T>
1048where
1049 T: Eq,
1050{
1051 /// Adds a value to the set.
1052 ///
1053 /// Returns whether the value was newly inserted. That is:
1054 ///
1055 /// - If the set did not previously contain this value, `true` is returned.
1056 /// - If the set already contained this value, `false` is returned.
1057 ///
1058 /// # Examples
1059 ///
1060 /// ```
1061 /// use vecmap::VecSet;
1062 ///
1063 /// let mut set = VecSet::new();
1064 ///
1065 /// assert_eq!(set.insert(2), true);
1066 /// assert_eq!(set.insert(2), false);
1067 /// assert_eq!(set.len(), 1);
1068 /// ```
1069 pub fn insert(&mut self, value: T) -> bool {
1070 self.base.insert(value).is_none()
1071 }
1072
1073 /// Moves all values from `other` into `self`, leaving `other` empty.
1074 ///
1075 /// This is equivalent to calling [`insert`][Self::insert] for each value from `other` in
1076 /// order, which means that values that already exist in `self` are unchanged in their current
1077 /// position.
1078 ///
1079 /// See also [`union`][Self::union] to iterate the combined values by reference, without
1080 /// modifying `self` or `other`.
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// use vecmap::VecSet;
1086 ///
1087 /// let mut a = VecSet::from([3, 2, 1]);
1088 /// let mut b = VecSet::from([3, 4, 5]);
1089 /// let old_capacity = b.capacity();
1090 ///
1091 /// a.append(&mut b);
1092 ///
1093 /// assert_eq!(a.len(), 5);
1094 /// assert_eq!(b.len(), 0);
1095 /// assert_eq!(b.capacity(), old_capacity);
1096 ///
1097 /// assert!(a.iter().eq(&[3, 2, 1, 4, 5]));
1098 /// ```
1099 pub fn append(&mut self, other: &mut VecSet<T>) {
1100 self.base.append(&mut other.base);
1101 }
1102}
1103
1104// Set operations.
1105impl<T> VecSet<T>
1106where
1107 T: Eq,
1108{
1109 /// Visits the values representing the difference, i.e., the values that are in `self` but not
1110 /// in `other`.
1111 ///
1112 /// # Examples
1113 ///
1114 /// ```
1115 /// use vecmap::VecSet;
1116 /// let a = VecSet::from([1, 2, 3]);
1117 /// let b = VecSet::from([4, 2, 3, 4]);
1118 ///
1119 /// // Can be seen as `a - b`.
1120 /// for x in a.difference(&b) {
1121 /// println!("{x}"); // Print 1
1122 /// }
1123 ///
1124 /// let diff: VecSet<_> = a.difference(&b).collect();
1125 /// assert_eq!(diff, [1].iter().collect());
1126 ///
1127 /// // Note that difference is not symmetric,
1128 /// // and `b - a` means something else:
1129 /// let diff: VecSet<_> = b.difference(&a).collect();
1130 /// assert_eq!(diff, [4].iter().collect());
1131 /// ```
1132 pub fn difference<'a>(&'a self, other: &'a VecSet<T>) -> Difference<'a, T> {
1133 Difference::new(self, other)
1134 }
1135
1136 /// Visits the values representing the intersection, i.e., the values that are both in `self`
1137 /// and `other`.
1138 ///
1139 /// When an equal element is present in `self` and `other` then the resulting `Intersection`
1140 /// may yield references to one or the other. This can be relevant if `T` contains fields which
1141 /// are not compared by its `Eq` implementation, and may hold different value between the two
1142 /// equal copies of `T` in the two sets.
1143 ///
1144 /// # Examples
1145 ///
1146 /// ```
1147 /// use vecmap::VecSet;
1148 /// let a = VecSet::from([1, 2, 3]);
1149 /// let b = VecSet::from([4, 2, 3, 4]);
1150 ///
1151 /// // Print 2, 3 in arbitrary order.
1152 /// for x in a.intersection(&b) {
1153 /// println!("{x}");
1154 /// }
1155 ///
1156 /// let intersection: VecSet<_> = a.intersection(&b).collect();
1157 /// assert_eq!(intersection, [2, 3].iter().collect());
1158 /// ```
1159 pub fn intersection<'a>(&'a self, other: &'a VecSet<T>) -> Intersection<'a, T> {
1160 if self.len() <= other.len() {
1161 Intersection::new(self, other)
1162 } else {
1163 Intersection::new(other, self)
1164 }
1165 }
1166
1167 /// Visits the values representing the symmetric difference, i.e., the values that are in
1168 /// `self` or in `other` but not in both.
1169 ///
1170 /// # Examples
1171 ///
1172 /// ```
1173 /// use vecmap::VecSet;
1174 /// let a = VecSet::from([1, 2, 3]);
1175 /// let b = VecSet::from([4, 2, 3, 4]);
1176 ///
1177 /// // Print 1, 4 in arbitrary order.
1178 /// for x in a.symmetric_difference(&b) {
1179 /// println!("{x}");
1180 /// }
1181 ///
1182 /// let diff1: VecSet<_> = a.symmetric_difference(&b).collect();
1183 /// let diff2: VecSet<_> = b.symmetric_difference(&a).collect();
1184 ///
1185 /// assert_eq!(diff1, diff2);
1186 /// assert_eq!(diff1, [1, 4].iter().collect());
1187 /// ```
1188 pub fn symmetric_difference<'a>(&'a self, other: &'a VecSet<T>) -> SymmetricDifference<'a, T> {
1189 SymmetricDifference::new(self, other)
1190 }
1191
1192 /// Visits the values representing the union, i.e., all the values in `self` or `other`,
1193 /// without duplicates.
1194 ///
1195 /// # Examples
1196 ///
1197 /// ```
1198 /// use vecmap::VecSet;
1199 /// let a = VecSet::from([1, 2, 3]);
1200 /// let b = VecSet::from([4, 2, 3, 4]);
1201 ///
1202 /// // Print 1, 2, 3, 4 in arbitrary order.
1203 /// for x in a.union(&b) {
1204 /// println!("{x}");
1205 /// }
1206 ///
1207 /// let union: VecSet<_> = a.union(&b).collect();
1208 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
1209 /// ```
1210 pub fn union<'a>(&'a self, other: &'a VecSet<T>) -> Union<'a, T> {
1211 if self.len() >= other.len() {
1212 Union::new(self, other)
1213 } else {
1214 Union::new(other, self)
1215 }
1216 }
1217
1218 /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
1219 /// checking for an empty intersection.
1220 ///
1221 /// # Examples
1222 ///
1223 /// ```
1224 /// use vecmap::VecSet;
1225 ///
1226 /// let a = VecSet::from([1, 2, 3]);
1227 /// let mut b = VecSet::new();
1228 ///
1229 /// assert_eq!(a.is_disjoint(&b), true);
1230 /// b.insert(4);
1231 /// assert_eq!(a.is_disjoint(&b), true);
1232 /// b.insert(1);
1233 /// assert_eq!(a.is_disjoint(&b), false);
1234 /// ```
1235 pub fn is_disjoint(&self, other: &VecSet<T>) -> bool {
1236 if self.len() <= other.len() {
1237 self.iter().all(|v| !other.contains(v))
1238 } else {
1239 other.iter().all(|v| !self.contains(v))
1240 }
1241 }
1242
1243 /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all the
1244 /// values in `self`.
1245 ///
1246 /// # Examples
1247 ///
1248 /// ```
1249 /// use vecmap::VecSet;
1250 ///
1251 /// let sup = VecSet::from([1, 2, 3]);
1252 /// let mut set = VecSet::new();
1253 ///
1254 /// assert_eq!(set.is_subset(&sup), true);
1255 /// set.insert(2);
1256 /// assert_eq!(set.is_subset(&sup), true);
1257 /// set.insert(4);
1258 /// assert_eq!(set.is_subset(&sup), false);
1259 /// ```
1260 pub fn is_subset(&self, other: &VecSet<T>) -> bool {
1261 if self.len() <= other.len() {
1262 self.iter().all(|v| other.contains(v))
1263 } else {
1264 false
1265 }
1266 }
1267
1268 /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
1269 /// values in `other`.
1270 ///
1271 /// # Examples
1272 ///
1273 /// ```
1274 /// use vecmap::VecSet;
1275 ///
1276 /// let sub = VecSet::from([1, 2]);
1277 /// let mut set = VecSet::new();
1278 ///
1279 /// assert_eq!(set.is_superset(&sub), false);
1280 ///
1281 /// set.insert(0);
1282 /// set.insert(1);
1283 /// assert_eq!(set.is_superset(&sub), false);
1284 ///
1285 /// set.insert(2);
1286 /// assert_eq!(set.is_superset(&sub), true);
1287 /// ```
1288 pub fn is_superset(&self, other: &VecSet<T>) -> bool {
1289 other.is_subset(self)
1290 }
1291}
1292
1293impl<T> Entries for VecSet<T> {
1294 type Entry = T;
1295
1296 fn as_entries(&self) -> &[Self::Entry] {
1297 self.base.as_slice()
1298 }
1299
1300 fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
1301 self.base.as_mut_slice()
1302 }
1303
1304 fn into_entries(self) -> Vec<Self::Entry> {
1305 self.base.into_vec()
1306 }
1307}