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