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