ringmap/
map.rs

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