stable_map/
map.rs

1#[cfg(test)]
2mod tests;
3
4use {
5    crate::{
6        drain::Drain,
7        entry::{Entry, EntryRef, OccupiedEntry, VacantEntry, VacantEntryRef},
8        into_iter::IntoIter,
9        into_keys::IntoKeys,
10        into_values::IntoValues,
11        iter::Iter,
12        iter_mut::IterMut,
13        keys::Keys,
14        linear_storage::LinearStorage,
15        occupied_error::OccupiedError,
16        pos_vec::pos::{InUse, Pos},
17        values::Values,
18        values_mut::ValuesMut,
19    },
20    core::{
21        cmp::min,
22        hash::{BuildHasher, Hash},
23        iter::FusedIterator,
24        marker::PhantomData,
25        mem::{self},
26    },
27    hashbrown::{hash_map, DefaultHashBuilder, Equivalent, HashMap},
28};
29
30/// A hash map with temporarily-stable indices.
31///
32/// This is a small wrapper around a [HashMap<K, V>] that splits the map into two parts:
33///
34/// - `HashMap<K, usize>`
35/// - `Vec<V>`
36///
37/// The index of for each key stays the same unless the key is removed from the map or the
38/// map is explicitly compacted.
39///
40/// # Example
41///
42/// Consider a service that allows clients to register callbacks:
43///
44/// ```
45/// use {
46///     parking_lot::Mutex,
47///     stable_map::StableMap,
48///     std::sync::{
49///         atomic::{AtomicUsize, Ordering::Relaxed},
50///         Arc,
51///     },
52/// };
53///
54/// pub struct Service {
55///     next_callback_id: AtomicUsize,
56///     callbacks: Mutex<StableMap<CallbackId, Arc<dyn Callback>>>,
57/// }
58///
59/// pub trait Callback {
60///     fn run(&self);
61/// }
62///
63/// #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
64/// pub struct CallbackId(usize);
65///
66/// impl Service {
67///     pub fn register_callback(&self, callback: Arc<dyn Callback>) -> CallbackId {
68///         let id = CallbackId(self.next_callback_id.fetch_add(1, Relaxed));
69///         self.callbacks.lock().insert(id, callback);
70///         id
71///     }
72///
73///     pub fn unregister_callback(&self, id: CallbackId) {
74///         self.callbacks.lock().remove(&id);
75///     }
76///
77///     fn execute_callbacks(&self) {
78///         let mut callbacks = self.callbacks.lock();
79///         for i in 0..callbacks.index_len() {
80///             if let Some(callback) = callbacks.get_by_index(i).cloned() {
81///                 // Drop the mutex so that the callback can itself call
82///                 // register_callback or unregister_callback.
83///                 drop(callbacks);
84///                 // Run the callback.
85///                 callback.run();
86///                 // Re-acquire the mutex.
87///                 callbacks = self.callbacks.lock();
88///             }
89///         }
90///         // Compact the map so that index_len does not grow much larger than the actual
91///         // size of the map.
92///         callbacks.compact();
93///     }
94/// }
95/// ```
96//
97// This type upholds the following invariants:
98//
99// - key_to_pos contains only valid Pos<InUse> returned by storage.
100//
101// SAFETY:
102// - LinearStorage::clear invalidates existing Pos<InUse> without consuming them.
103// - Code calling LinearStorage::clear must explain how it upholds the invariant.
104pub struct StableMap<K, V, S = DefaultHashBuilder> {
105    key_to_pos: HashMap<K, Pos<InUse>, S>,
106    storage: LinearStorage<V>,
107}
108
109#[cfg(feature = "default-hasher")]
110impl<K, V> StableMap<K, V, DefaultHashBuilder> {
111    /// Creates an empty `StableMap`.
112    ///
113    /// The map is initially created with a capacity of 0, so it will not allocate until it
114    /// is first inserted into.
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// use stable_map::StableMap;
120    /// let mut map: StableMap<&str, i32> = StableMap::new();
121    /// assert_eq!(map.len(), 0);
122    /// assert_eq!(map.capacity(), 0);
123    /// ```
124    #[cfg_attr(feature = "inline-more", inline)]
125    pub fn new() -> Self {
126        Self {
127            key_to_pos: HashMap::new(),
128            storage: LinearStorage::with_capacity(0),
129        }
130    }
131
132    /// Creates an empty `StableMap` with the specified capacity.
133    ///
134    /// The map will be able to hold at least `capacity` elements without
135    /// reallocating. If `capacity` is 0, the map will not allocate.
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use stable_map::StableMap;
141    /// let mut map: StableMap<&str, i32> = StableMap::with_capacity(10);
142    /// assert_eq!(map.len(), 0);
143    /// assert!(map.capacity() >= 10);
144    /// ```
145    #[cfg_attr(feature = "inline-more", inline)]
146    pub fn with_capacity(capacity: usize) -> Self {
147        Self {
148            key_to_pos: HashMap::with_capacity(capacity),
149            storage: LinearStorage::with_capacity(capacity),
150        }
151    }
152}
153
154impl<K, V, S> StableMap<K, V, S> {
155    /// Returns the number of elements the map can hold without reallocating.
156    ///
157    /// This number is a lower bound; the `StableMap<K, V>` might be able to hold
158    /// more, but is guaranteed to be able to hold at least this many.
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use stable_map::StableMap;
164    /// let map: StableMap<i32, i32> = StableMap::with_capacity(100);
165    /// assert_eq!(map.len(), 0);
166    /// assert!(map.capacity() >= 100);
167    /// ```
168    #[cfg_attr(feature = "inline-more", inline)]
169    pub fn capacity(&self) -> usize {
170        min(self.key_to_pos.capacity(), self.storage.capacity())
171    }
172
173    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
174    /// for reuse.
175    ///
176    /// # Examples
177    ///
178    /// ```
179    /// use stable_map::StableMap;
180    ///
181    /// let mut a = StableMap::new();
182    /// a.insert(1, "a");
183    /// let capacity_before_clear = a.capacity();
184    ///
185    /// a.clear();
186    ///
187    /// // Map is empty.
188    /// assert!(a.is_empty());
189    /// // But map capacity is equal to old one.
190    /// assert_eq!(a.capacity(), capacity_before_clear);
191    /// ```
192    #[cfg_attr(feature = "inline-more", inline)]
193    pub fn clear(&mut self) {
194        self.key_to_pos.clear();
195        self.storage.clear();
196        // SAFETY(invariants):
197        // - We have cleared key_to_pos.
198    }
199
200    /// Returns `true` if the map contains a value for the specified key.
201    ///
202    /// The key may be any borrowed form of the map's key type, but
203    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
204    /// the key type.
205    ///
206    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
207    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
208    ///
209    /// # Examples
210    ///
211    /// ```
212    /// use stable_map::StableMap;
213    ///
214    /// let mut map = StableMap::new();
215    /// map.insert(1, "a");
216    /// assert_eq!(map.contains_key(&1), true);
217    /// assert_eq!(map.contains_key(&2), false);
218    /// ```
219    #[cfg_attr(feature = "inline-more", inline)]
220    pub fn contains_key<Q>(&self, key: &Q) -> bool
221    where
222        K: Eq + Hash,
223        Q: Hash + Equivalent<K> + ?Sized,
224        S: BuildHasher,
225    {
226        self.key_to_pos.contains_key(key)
227    }
228
229    /// Clears the map, returning all key-value pairs as an iterator. Keeps the
230    /// allocated memory for reuse.
231    ///
232    /// If the returned iterator is dropped before being fully consumed, it
233    /// drops the remaining key-value pairs. The returned iterator keeps a
234    /// mutable borrow on the vector to optimize its implementation.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use stable_map::StableMap;
240    ///
241    /// let mut a = StableMap::new();
242    /// a.insert(1, "a");
243    /// a.insert(2, "b");
244    /// let capacity_before_drain = a.capacity();
245    ///
246    /// for (k, v) in a.drain().take(1) {
247    ///     assert!(k == 1 || k == 2);
248    ///     assert!(v == "a" || v == "b");
249    /// }
250    ///
251    /// // As we can see, the map is empty and contains no element.
252    /// assert!(a.is_empty() && a.len() == 0);
253    /// // But map capacity is equal to old one.
254    /// assert_eq!(a.capacity(), capacity_before_drain);
255    ///
256    /// let mut a = StableMap::new();
257    /// a.insert(1, "a");
258    /// a.insert(2, "b");
259    ///
260    /// {   // Iterator is dropped without being consumed.
261    ///     let d = a.drain();
262    /// }
263    ///
264    /// // But the map is empty even if we do not use Drain iterator.
265    /// assert!(a.is_empty());
266    /// ```
267    #[cfg_attr(feature = "inline-more", inline)]
268    pub fn drain(&mut self) -> Drain<'_, K, V> {
269        Drain {
270            drain: self.key_to_pos.drain(),
271            entries: &mut self.storage,
272        }
273    }
274
275    /// Gets the given key's corresponding entry in the map for in-place manipulation.
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// use stable_map::StableMap;
281    ///
282    /// let mut letters = StableMap::new();
283    ///
284    /// for ch in "a short treatise on fungi".chars() {
285    ///     let counter = letters.entry(ch).or_insert(0);
286    ///     *counter += 1;
287    /// }
288    ///
289    /// assert_eq!(letters[&'s'], 2);
290    /// assert_eq!(letters[&'t'], 3);
291    /// assert_eq!(letters[&'u'], 1);
292    /// assert_eq!(letters.get(&'y'), None);
293    /// ```
294    #[cfg_attr(feature = "inline-more", inline)]
295    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S>
296    where
297        K: Eq + Hash,
298        S: BuildHasher,
299    {
300        match self.key_to_pos.entry(key) {
301            hash_map::Entry::Occupied(v) => Entry::Occupied(OccupiedEntry {
302                entry: v,
303                entries: &mut self.storage,
304            }),
305            hash_map::Entry::Vacant(v) => Entry::Vacant(VacantEntry {
306                entry: v,
307                entries: &mut self.storage,
308            }),
309        }
310    }
311
312    /// Gets the given key's corresponding entry by reference in the map for in-place manipulation.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use stable_map::StableMap;
318    ///
319    /// let mut words: StableMap<String, usize> = StableMap::new();
320    /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
321    /// for (i, &s) in source.iter().enumerate() {
322    ///     let counter = words.entry_ref(s).or_insert(0);
323    ///     *counter += 1;
324    /// }
325    ///
326    /// assert_eq!(words["poneyland"], 3);
327    /// assert_eq!(words["horseyland"], 1);
328    /// ```
329    #[cfg_attr(feature = "inline-more", inline)]
330    pub fn entry_ref<'b, Q>(&mut self, key: &'b Q) -> EntryRef<'_, 'b, K, Q, V, S>
331    where
332        K: Eq + Hash,
333        Q: Hash + Equivalent<K> + ?Sized,
334        S: BuildHasher,
335    {
336        match self.key_to_pos.entry_ref(key) {
337            hash_map::EntryRef::Occupied(v) => EntryRef::Occupied(OccupiedEntry {
338                entry: v,
339                entries: &mut self.storage,
340            }),
341            hash_map::EntryRef::Vacant(v) => EntryRef::Vacant(VacantEntryRef {
342                entry: v,
343                entries: &mut self.storage,
344            }),
345        }
346    }
347
348    /// Drains elements which are true under the given predicate,
349    /// and returns an iterator over the removed items.
350    ///
351    /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out
352    /// into another iterator.
353    ///
354    /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
355    /// whether you choose to keep or remove it.
356    ///
357    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
358    /// or the iteration short-circuits, then the remaining elements will be retained.
359    /// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
360    ///
361    /// Keeps the allocated memory for reuse.
362    ///
363    /// [`retain()`]: StableMap::retain
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// use stable_map::StableMap;
369    ///
370    /// let mut map: StableMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
371    ///
372    /// let drained: StableMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
373    ///
374    /// let mut evens = drained.keys().cloned().collect::<Vec<_>>();
375    /// let mut odds = map.keys().cloned().collect::<Vec<_>>();
376    /// evens.sort();
377    /// odds.sort();
378    ///
379    /// assert_eq!(evens, vec![0, 2, 4, 6]);
380    /// assert_eq!(odds, vec![1, 3, 5, 7]);
381    ///
382    /// let mut map: StableMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
383    ///
384    /// {   // Iterator is dropped without being consumed.
385    ///     let d = map.extract_if(|k, _v| k % 2 != 0);
386    /// }
387    ///
388    /// // ExtractIf was not exhausted, therefore no elements were drained.
389    /// assert_eq!(map.len(), 8);
390    /// ```
391    #[cfg_attr(feature = "inline-more", inline)]
392    pub fn extract_if<F>(
393        &mut self,
394        mut f: F,
395    ) -> impl FusedIterator<Item = (K, V)> + use<'_, K, V, F, S>
396    where
397        F: FnMut(&K, &mut V) -> bool,
398    {
399        // SAFETY: (applies to all dereferences of storage below)
400        // - storage points to self.storage which remains valid since the
401        //   return value borrows self
402        // - all references to self.storage by the return value are created through
403        //   this pointer, therefore it is sufficient to show that we don't create more
404        //   than one reference at a time.
405        // - the first dereference is live only for the lifetime of the particular closure
406        //   invocation. this is a FnMut closure, therefore it cannot run concurrently
407        //   with itself.
408        // - the second dereference is live only during the next method call and strictly
409        //   after the nested next call.
410        // - the first dereference is only invoked through the nested next call.
411        // - the user-defined callback cannot invoke the outer next function since that
412        //   would create multiple multiple references to the iterator.
413        let storage = &raw mut self.storage;
414        let iter = self.key_to_pos.extract_if(move |k, pos| {
415            let storage = unsafe {
416                // SAFETY: see comment at the top
417                &mut *storage
418            };
419            let v = unsafe {
420                // SAFETY: By the invariants, pos is valid
421                storage.get_unchecked_mut(pos)
422            };
423            f(k, v)
424        });
425        struct Iter<'a, K, V, I> {
426            iter: I,
427            storage: *mut LinearStorage<V>,
428            _phantom1: PhantomData<fn() -> K>,
429            _phantom2: PhantomData<&'a mut LinearStorage<V>>,
430        }
431        impl<K, V, I> Iterator for Iter<'_, K, V, I>
432        where
433            I: Iterator<Item = (K, Pos<InUse>)>,
434        {
435            type Item = (K, V);
436
437            fn next(&mut self) -> Option<Self::Item> {
438                let (k, pos) = self.iter.next()?;
439                let storage = unsafe {
440                    // SAFETY: see comment at the top
441                    &mut *self.storage
442                };
443                let value = unsafe {
444                    // SAFETY: By the invariants, pos is valid
445                    storage.take_unchecked(pos)
446                };
447                Some((k, value))
448            }
449        }
450        impl<K, V, I> FusedIterator for Iter<'_, K, V, I> where I: FusedIterator<Item = (K, Pos<InUse>)> {}
451        Iter::<'_, K, V, _> {
452            iter,
453            storage,
454            _phantom1: PhantomData,
455            _phantom2: PhantomData,
456        }
457    }
458
459    /// Returns a reference to the value corresponding to the key.
460    ///
461    /// The key may be any borrowed form of the map's key type, but
462    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
463    /// the key type.
464    ///
465    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
466    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
467    ///
468    /// # Examples
469    ///
470    /// ```
471    /// use stable_map::StableMap;
472    ///
473    /// let mut map = StableMap::new();
474    /// map.insert(1, "a");
475    /// assert_eq!(map.get(&1), Some(&"a"));
476    /// assert_eq!(map.get(&2), None);
477    /// ```
478    #[inline]
479    pub fn get<Q>(&self, key: &Q) -> Option<&V>
480    where
481        K: Eq + Hash,
482        Q: Hash + Equivalent<K> + ?Sized,
483        S: BuildHasher,
484    {
485        let pos = self.key_to_pos.get(key)?;
486        let v = unsafe {
487            // SAFETY:
488            // - By the invariants, pos is valid
489            self.storage.get_unchecked(pos)
490        };
491        Some(v)
492    }
493
494    /// Returns the key-value pair corresponding to the supplied key.
495    ///
496    /// The supplied key may be any borrowed form of the map's key type, but
497    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
498    /// the key type.
499    ///
500    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
501    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
502    ///
503    /// # Examples
504    ///
505    /// ```
506    /// use stable_map::StableMap;
507    ///
508    /// let mut map = StableMap::new();
509    /// map.insert(1, "a");
510    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
511    /// assert_eq!(map.get_key_value(&2), None);
512    /// ```
513    #[inline]
514    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
515    where
516        K: Eq + Hash,
517        Q: Hash + Equivalent<K> + ?Sized,
518        S: BuildHasher,
519    {
520        let (k, pos) = self.key_to_pos.get_key_value(key)?;
521        let v = unsafe {
522            // SAFETY:
523            // - By the invariants, pos is valid
524            self.storage.get_unchecked(pos)
525        };
526        Some((k, v))
527    }
528
529    /// Returns the key-value pair corresponding to the supplied key.
530    ///
531    /// The supplied key may be any borrowed form of the map's key type, but
532    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
533    /// the key type.
534    ///
535    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
536    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
537    ///
538    /// # Examples
539    ///
540    /// ```
541    /// use stable_map::StableMap;
542    ///
543    /// let mut map = StableMap::new();
544    /// map.insert(1, "a");
545    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
546    /// assert_eq!(map.get_key_value(&2), None);
547    /// ```
548    #[inline]
549    pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
550    where
551        K: Eq + Hash,
552        Q: Hash + Equivalent<K> + ?Sized,
553        S: BuildHasher,
554    {
555        let (k, pos) = self.key_to_pos.get_key_value(key)?;
556        let value = unsafe {
557            // SAFETY:
558            // - By the invariants, pos is valid
559            self.storage.get_unchecked_mut(pos)
560        };
561        Some((k, value))
562    }
563
564    /// Attempts to get mutable references to `N` values in the map at once, with immutable
565    /// references to the corresponding keys.
566    ///
567    /// Returns an array of length `N` with the results of each query. For soundness, at most one
568    /// mutable reference will be returned to any value. `None` will be used if the key is missing.
569    ///
570    /// # Panics
571    ///
572    /// Panics if any keys are overlapping.
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// use stable_map::StableMap;
578    ///
579    /// let mut libraries = StableMap::new();
580    /// libraries.insert("Bodleian Library".to_string(), 1602);
581    /// libraries.insert("Athenæum".to_string(), 1807);
582    /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
583    /// libraries.insert("Library of Congress".to_string(), 1800);
584    ///
585    /// let got = libraries.get_many_key_value_mut([
586    ///     "Bodleian Library",
587    ///     "Herzogin-Anna-Amalia-Bibliothek",
588    /// ]);
589    /// assert_eq!(
590    ///     got,
591    ///     [
592    ///         Some((&"Bodleian Library".to_string(), &mut 1602)),
593    ///         Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
594    ///     ],
595    /// );
596    /// // Missing keys result in None
597    /// let got = libraries.get_many_key_value_mut([
598    ///     "Bodleian Library",
599    ///     "Gewandhaus",
600    /// ]);
601    /// assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
602    /// ```
603    ///
604    /// ```should_panic
605    /// use stable_map::StableMap;
606    ///
607    /// let mut libraries = StableMap::new();
608    /// libraries.insert("Bodleian Library".to_string(), 1602);
609    /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
610    ///
611    /// // Duplicate keys result in panic!
612    /// let got = libraries.get_many_key_value_mut([
613    ///     "Bodleian Library",
614    ///     "Herzogin-Anna-Amalia-Bibliothek",
615    ///     "Herzogin-Anna-Amalia-Bibliothek",
616    /// ]);
617    /// ```
618    pub fn get_many_key_value_mut<Q, const N: usize>(
619        &mut self,
620        ks: [&Q; N],
621    ) -> [Option<(&K, &mut V)>; N]
622    where
623        K: Eq + Hash,
624        Q: Hash + Equivalent<K> + ?Sized,
625        S: BuildHasher,
626    {
627        let ps = self.key_to_pos.get_many_key_value_mut::<Q, N>(ks);
628        unsafe {
629            // SAFETY:
630            // - By the invariants, all pos are valid
631            self.storage
632                .get_many_unchecked_mut(ps, |p| p.1, |(k, _), v| (k, v))
633        }
634    }
635
636    /// Attempts to get mutable references to `N` values in the map at once, with immutable
637    /// references to the corresponding keys, without validating that the values are unique.
638    ///
639    /// Returns an array of length `N` with the results of each query. `None` will be returned if
640    /// any of the keys are missing.
641    ///
642    /// For a safe alternative see [`get_many_key_value_mut`](`StableMap::get_many_key_value_mut`).
643    ///
644    /// # Safety
645    ///
646    /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
647    /// references are not used.
648    ///
649    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
650    ///
651    /// # Examples
652    ///
653    /// ```
654    /// use stable_map::StableMap;
655    ///
656    /// let mut libraries = StableMap::new();
657    /// libraries.insert("Bodleian Library".to_string(), 1602);
658    /// libraries.insert("Athenæum".to_string(), 1807);
659    /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
660    /// libraries.insert("Library of Congress".to_string(), 1800);
661    ///
662    /// let got = libraries.get_many_key_value_mut([
663    ///     "Bodleian Library",
664    ///     "Herzogin-Anna-Amalia-Bibliothek",
665    /// ]);
666    /// assert_eq!(
667    ///     got,
668    ///     [
669    ///         Some((&"Bodleian Library".to_string(), &mut 1602)),
670    ///         Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
671    ///     ],
672    /// );
673    /// // Missing keys result in None
674    /// let got = libraries.get_many_key_value_mut([
675    ///     "Bodleian Library",
676    ///     "Gewandhaus",
677    /// ]);
678    /// assert_eq!(
679    ///     got,
680    ///     [
681    ///         Some((&"Bodleian Library".to_string(), &mut 1602)),
682    ///         None,
683    ///     ],
684    /// );
685    /// ```
686    pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(
687        &mut self,
688        ks: [&Q; N],
689    ) -> [Option<(&K, &mut V)>; N]
690    where
691        K: Eq + Hash,
692        Q: Hash + Equivalent<K> + ?Sized,
693        S: BuildHasher,
694    {
695        let ps = unsafe {
696            // SAFETY: The requirements are forwarded to the caller.
697            self.key_to_pos.get_many_key_value_unchecked_mut::<Q, N>(ks)
698        };
699        unsafe {
700            // SAFETY:
701            // - By the invariants, all pos are valid
702            self.storage
703                .get_many_unchecked_mut(ps, |p| p.1, |(k, _), v| (k, v))
704        }
705    }
706
707    /// Attempts to get mutable references to `N` values in the map at once.
708    ///
709    /// Returns an array of length `N` with the results of each query. For soundness, at most one
710    /// mutable reference will be returned to any value. `None` will be used if the key is missing.
711    ///
712    /// # Panics
713    ///
714    /// Panics if any keys are overlapping.
715    ///
716    /// # Examples
717    ///
718    /// ```
719    /// use stable_map::StableMap;
720    ///
721    /// let mut libraries = StableMap::new();
722    /// libraries.insert("Bodleian Library".to_string(), 1602);
723    /// libraries.insert("Athenæum".to_string(), 1807);
724    /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
725    /// libraries.insert("Library of Congress".to_string(), 1800);
726    ///
727    /// // Get Athenæum and Bodleian Library
728    /// let [Some(a), Some(b)] = libraries.get_many_mut([
729    ///     "Athenæum",
730    ///     "Bodleian Library",
731    /// ]) else { panic!() };
732    ///
733    /// // Assert values of Athenæum and Library of Congress
734    /// let got = libraries.get_many_mut([
735    ///     "Athenæum",
736    ///     "Library of Congress",
737    /// ]);
738    /// assert_eq!(
739    ///     got,
740    ///     [
741    ///         Some(&mut 1807),
742    ///         Some(&mut 1800),
743    ///     ],
744    /// );
745    ///
746    /// // Missing keys result in None
747    /// let got = libraries.get_many_mut([
748    ///     "Athenæum",
749    ///     "New York Public Library",
750    /// ]);
751    /// assert_eq!(
752    ///     got,
753    ///     [
754    ///         Some(&mut 1807),
755    ///         None
756    ///     ]
757    /// );
758    /// ```
759    ///
760    /// ```should_panic
761    /// use stable_map::StableMap;
762    ///
763    /// let mut libraries = StableMap::new();
764    /// libraries.insert("Athenæum".to_string(), 1807);
765    ///
766    /// // Duplicate keys panic!
767    /// let got = libraries.get_many_mut([
768    ///     "Athenæum",
769    ///     "Athenæum",
770    /// ]);
771    /// ```
772    pub fn get_many_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N]
773    where
774        K: Eq + Hash,
775        Q: Hash + Equivalent<K> + ?Sized,
776        S: BuildHasher,
777    {
778        let ps = self.key_to_pos.get_many_mut::<Q, N>(ks);
779        unsafe {
780            // SAFETY:
781            // - By the invariants, all pos are valid
782            self.storage.get_many_unchecked_mut(ps, |p| p, |_, v| v)
783        }
784    }
785
786    /// Attempts to get mutable references to `N` values in the map at once, without validating that
787    /// the values are unique.
788    ///
789    /// Returns an array of length `N` with the results of each query. `None` will be used if
790    /// the key is missing.
791    ///
792    /// For a safe alternative see [`get_many_mut`](`StableMap::get_many_mut`).
793    ///
794    /// # Safety
795    ///
796    /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
797    /// references are not used.
798    ///
799    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
800    ///
801    /// # Examples
802    ///
803    /// ```
804    /// use stable_map::StableMap;
805    ///
806    /// let mut libraries = StableMap::new();
807    /// libraries.insert("Bodleian Library".to_string(), 1602);
808    /// libraries.insert("Athenæum".to_string(), 1807);
809    /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
810    /// libraries.insert("Library of Congress".to_string(), 1800);
811    ///
812    /// // SAFETY: The keys do not overlap.
813    /// let [Some(a), Some(b)] = (unsafe { libraries.get_many_unchecked_mut([
814    ///     "Athenæum",
815    ///     "Bodleian Library",
816    /// ]) }) else { panic!() };
817    ///
818    /// // SAFETY: The keys do not overlap.
819    /// let got = unsafe { libraries.get_many_unchecked_mut([
820    ///     "Athenæum",
821    ///     "Library of Congress",
822    /// ]) };
823    /// assert_eq!(
824    ///     got,
825    ///     [
826    ///         Some(&mut 1807),
827    ///         Some(&mut 1800),
828    ///     ],
829    /// );
830    ///
831    /// // SAFETY: The keys do not overlap.
832    /// let got = unsafe { libraries.get_many_unchecked_mut([
833    ///     "Athenæum",
834    ///     "New York Public Library",
835    /// ]) };
836    /// // Missing keys result in None
837    /// assert_eq!(got, [Some(&mut 1807), None]);
838    /// ```
839    pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
840        &mut self,
841        ks: [&Q; N],
842    ) -> [Option<&mut V>; N]
843    where
844        K: Eq + Hash,
845        Q: Hash + Equivalent<K> + ?Sized,
846        S: BuildHasher,
847    {
848        let ps = unsafe {
849            // SAFETY: The requirements are forwarded to the caller.
850            self.key_to_pos.get_many_unchecked_mut::<Q, N>(ks)
851        };
852        unsafe {
853            // SAFETY:
854            // - By the invariants, all pos are valid
855            self.storage.get_many_unchecked_mut(ps, |p| p, |_, v| v)
856        }
857    }
858
859    /// Returns a mutable reference to the value corresponding to the key.
860    ///
861    /// The key may be any borrowed form of the map's key type, but
862    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
863    /// the key type.
864    ///
865    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
866    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
867    ///
868    /// # Examples
869    ///
870    /// ```
871    /// use stable_map::StableMap;
872    ///
873    /// let mut map = StableMap::new();
874    /// map.insert(1, "a");
875    /// if let Some(x) = map.get_mut(&1) {
876    ///     *x = "b";
877    /// }
878    /// assert_eq!(map[&1], "b");
879    ///
880    /// assert_eq!(map.get_mut(&2), None);
881    /// ```
882    #[cfg_attr(feature = "inline-more", inline)]
883    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
884    where
885        K: Eq + Hash,
886        Q: Hash + Equivalent<K> + ?Sized,
887        S: BuildHasher,
888    {
889        let pos = self.key_to_pos.get_mut(key)?;
890        let value = unsafe {
891            // SAFETY:
892            // - By the invariants, pos is valid
893            self.storage.get_unchecked_mut(pos)
894        };
895        Some(value)
896    }
897
898    /// Returns a reference to the map's [`BuildHasher`].
899    ///
900    /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// use hashbrown::DefaultHashBuilder;
906    /// use stable_map::StableMap;
907    ///
908    /// let hasher = DefaultHashBuilder::default();
909    /// let map: StableMap<i32, i32> = StableMap::with_hasher(hasher);
910    /// let hasher: &DefaultHashBuilder = map.hasher();
911    /// ```
912    #[cfg_attr(feature = "inline-more", inline)]
913    pub fn hasher(&self) -> &S {
914        self.key_to_pos.hasher()
915    }
916
917    /// Inserts a key-value pair into the map.
918    ///
919    /// If the map did not have this key present, [`None`] is returned.
920    ///
921    /// If the map did have this key present, the value is updated, and the old
922    /// value is returned. The key is not updated, though; this matters for
923    /// types that can be `==` without being identical. See the [`std::collections`]
924    /// [module-level documentation] for more.
925    ///
926    /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
927    /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html
928    /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
929    ///
930    /// # Examples
931    ///
932    /// ```
933    /// use stable_map::StableMap;
934    ///
935    /// let mut map = StableMap::new();
936    /// assert_eq!(map.insert(37, "a"), None);
937    /// assert_eq!(map.is_empty(), false);
938    ///
939    /// map.insert(37, "b");
940    /// assert_eq!(map.insert(37, "c"), Some("b"));
941    /// assert_eq!(map[&37], "c");
942    /// ```
943    #[cfg_attr(feature = "inline-more", inline)]
944    pub fn insert(&mut self, key: K, value: V) -> Option<V>
945    where
946        K: Eq + Hash,
947        S: BuildHasher,
948    {
949        match self.key_to_pos.entry(key) {
950            hash_map::Entry::Occupied(occupied) => {
951                let prev = unsafe {
952                    // SAFETY:
953                    // - By the invariants, occupied.get() is valid
954                    self.storage.get_unchecked_mut(occupied.get())
955                };
956                Some(mem::replace(prev, value))
957            }
958            hash_map::Entry::Vacant(vacant) => {
959                let pos = self.storage.insert(value);
960                vacant.insert(pos);
961                None
962            }
963        }
964    }
965
966    /// Insert a key-value pair into the map without checking
967    /// if the key already exists in the map.
968    ///
969    /// This operation is faster than regular insert, because it does not perform
970    /// lookup before insertion.
971    ///
972    /// This operation is useful during initial population of the map.
973    /// For example, when constructing a map from another map, we know
974    /// that keys are unique.
975    ///
976    /// Returns a reference to the key and value just inserted.
977    ///
978    /// # Safety
979    ///
980    /// This operation is safe if a key does not exist in the map.
981    ///
982    /// However, if a key exists in the map already, the behavior is unspecified:
983    /// this operation may panic, loop forever, or any following operation with the map
984    /// may panic, loop forever or return arbitrary result.
985    ///
986    /// That said, this operation (and following operations) are guaranteed to
987    /// not violate memory safety.
988    ///
989    /// However this operation is still unsafe because the resulting `StableMap`
990    /// may be passed to unsafe code which does expect the map to behave
991    /// correctly, and would cause unsoundness as a result.
992    ///
993    /// # Examples
994    ///
995    /// ```
996    /// use stable_map::StableMap;
997    ///
998    /// let mut map1 = StableMap::new();
999    /// assert_eq!(map1.insert(1, "a"), None);
1000    /// assert_eq!(map1.insert(2, "b"), None);
1001    /// assert_eq!(map1.insert(3, "c"), None);
1002    /// assert_eq!(map1.len(), 3);
1003    ///
1004    /// let mut map2 = StableMap::new();
1005    ///
1006    /// for (key, value) in map1.into_iter() {
1007    ///     unsafe {
1008    ///         map2.insert_unique_unchecked(key, value);
1009    ///     }
1010    /// }
1011    ///
1012    /// let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
1013    /// assert_eq!(key, &4);
1014    /// assert_eq!(value, &mut "d");
1015    /// *value = "e";
1016    ///
1017    /// assert_eq!(map2[&1], "a");
1018    /// assert_eq!(map2[&2], "b");
1019    /// assert_eq!(map2[&3], "c");
1020    /// assert_eq!(map2[&4], "e");
1021    /// assert_eq!(map2.len(), 4);
1022    /// ```
1023    #[cfg_attr(feature = "inline-more", inline)]
1024    pub unsafe fn insert_unique_unchecked(&mut self, key: K, value: V) -> (&K, &mut V)
1025    where
1026        K: Eq + Hash,
1027        S: BuildHasher,
1028    {
1029        let pos = self.storage.insert(value);
1030        let (key, pos) = unsafe {
1031            // SAFETY:
1032            // - The requirement is forwarded to the caller.
1033            self.key_to_pos.insert_unique_unchecked(key, pos)
1034        };
1035        let value = unsafe {
1036            // SAFETY:
1037            // - We just retrieved this position.
1038            self.storage.get_unchecked_mut(pos)
1039        };
1040        (key, value)
1041    }
1042
1043    /// Creates a consuming iterator visiting all the keys in arbitrary order.
1044    /// The map cannot be used after calling this.
1045    /// The iterator element type is `K`.
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```
1050    /// use stable_map::StableMap;
1051    ///
1052    /// let mut map = StableMap::new();
1053    /// map.insert("a", 1);
1054    /// map.insert("b", 2);
1055    /// map.insert("c", 3);
1056    ///
1057    /// let mut vec: Vec<&str> = map.into_keys().collect();
1058    ///
1059    /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
1060    /// // keys must be sorted to test them against a sorted array.
1061    /// vec.sort_unstable();
1062    /// assert_eq!(vec, ["a", "b", "c"]);
1063    /// ```
1064    #[inline]
1065    pub fn into_keys(self) -> IntoKeys<K> {
1066        IntoKeys {
1067            iter: self.key_to_pos.into_keys(),
1068        }
1069    }
1070
1071    /// Creates a consuming iterator visiting all the values in arbitrary order.
1072    /// The map cannot be used after calling this.
1073    /// The iterator element type is `V`.
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```
1078    /// use stable_map::StableMap;
1079    ///
1080    /// let mut map = StableMap::new();
1081    /// map.insert("a", 1);
1082    /// map.insert("b", 2);
1083    /// map.insert("c", 3);
1084    ///
1085    /// let mut vec: Vec<i32> = map.into_values().collect();
1086    ///
1087    /// // The `IntoValues` iterator produces values in arbitrary order, so
1088    /// // the values must be sorted to test them against a sorted array.
1089    /// vec.sort_unstable();
1090    /// assert_eq!(vec, [1, 2, 3]);
1091    /// ```
1092    #[inline]
1093    pub fn into_values(self) -> IntoValues<K, V> {
1094        IntoValues {
1095            iter: self.key_to_pos.into_values(),
1096            storage: self.storage,
1097        }
1098    }
1099
1100    /// Returns `true` if the map contains no elements.
1101    ///
1102    /// # Examples
1103    ///
1104    /// ```
1105    /// use stable_map::StableMap;
1106    ///
1107    /// let mut a = StableMap::new();
1108    /// assert!(a.is_empty());
1109    /// a.insert(1, "a");
1110    /// assert!(!a.is_empty());
1111    /// ```
1112    #[cfg_attr(feature = "inline-more", inline)]
1113    pub fn is_empty(&self) -> bool {
1114        self.key_to_pos.is_empty()
1115    }
1116
1117    /// Returns `true` if the map contains elements.
1118    ///
1119    /// # Examples
1120    ///
1121    /// ```
1122    /// use stable_map::StableMap;
1123    ///
1124    /// let mut a = StableMap::new();
1125    /// assert!(!a.is_not_empty());
1126    /// a.insert(1, "a");
1127    /// assert!(a.is_not_empty());
1128    /// ```
1129    pub fn is_not_empty(&self) -> bool {
1130        !self.is_empty()
1131    }
1132
1133    /// An iterator visiting all key-value pairs in arbitrary order.
1134    /// The iterator element type is `(&'a K, &'a V)`.
1135    ///
1136    /// # Examples
1137    ///
1138    /// ```
1139    /// use stable_map::StableMap;
1140    ///
1141    /// let mut map = StableMap::new();
1142    /// map.insert("a", 1);
1143    /// map.insert("b", 2);
1144    /// map.insert("c", 3);
1145    /// assert_eq!(map.len(), 3);
1146    /// let mut vec: Vec<(&str, i32)> = Vec::new();
1147    ///
1148    /// for (key, val) in map.iter() {
1149    ///     println!("key: {} val: {}", key, val);
1150    ///     vec.push((*key, *val));
1151    /// }
1152    ///
1153    /// // The `Iter` iterator produces items in arbitrary order, so the
1154    /// // items must be sorted to test them against a sorted array.
1155    /// vec.sort_unstable();
1156    /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
1157    ///
1158    /// assert_eq!(map.len(), 3);
1159    /// ```
1160    #[cfg_attr(feature = "inline-more", inline)]
1161    pub fn iter(&self) -> Iter<'_, K, V> {
1162        Iter {
1163            iter: self.key_to_pos.iter(),
1164            entries: &self.storage,
1165        }
1166    }
1167
1168    /// An iterator visiting all key-value pairs in arbitrary order,
1169    /// with mutable references to the values.
1170    /// The iterator element type is `(&'a K, &'a mut V)`.
1171    ///
1172    /// # Examples
1173    ///
1174    /// ```
1175    /// use stable_map::StableMap;
1176    ///
1177    /// let mut map = StableMap::new();
1178    /// map.insert("a", 1);
1179    /// map.insert("b", 2);
1180    /// map.insert("c", 3);
1181    ///
1182    /// // Update all values
1183    /// for (_, val) in map.iter_mut() {
1184    ///     *val *= 2;
1185    /// }
1186    ///
1187    /// assert_eq!(map.len(), 3);
1188    /// let mut vec: Vec<(&str, i32)> = Vec::new();
1189    ///
1190    /// for (key, val) in &map {
1191    ///     println!("key: {} val: {}", key, val);
1192    ///     vec.push((*key, *val));
1193    /// }
1194    ///
1195    /// // The `Iter` iterator produces items in arbitrary order, so the
1196    /// // items must be sorted to test them against a sorted array.
1197    /// vec.sort_unstable();
1198    /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
1199    ///
1200    /// assert_eq!(map.len(), 3);
1201    /// ```
1202    #[cfg_attr(feature = "inline-more", inline)]
1203    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
1204        IterMut {
1205            iter: self.key_to_pos.iter_mut(),
1206            entries: self.storage.raw_access(),
1207        }
1208    }
1209
1210    /// An iterator visiting all keys in arbitrary order.
1211    /// The iterator element type is `&'a K`.
1212    ///
1213    /// # Examples
1214    ///
1215    /// ```
1216    /// use stable_map::StableMap;
1217    ///
1218    /// let mut map = StableMap::new();
1219    /// map.insert("a", 1);
1220    /// map.insert("b", 2);
1221    /// map.insert("c", 3);
1222    /// assert_eq!(map.len(), 3);
1223    /// let mut vec: Vec<&str> = Vec::new();
1224    ///
1225    /// for key in map.keys() {
1226    ///     println!("{}", key);
1227    ///     vec.push(*key);
1228    /// }
1229    ///
1230    /// // The `Keys` iterator produces keys in arbitrary order, so the
1231    /// // keys must be sorted to test them against a sorted array.
1232    /// vec.sort_unstable();
1233    /// assert_eq!(vec, ["a", "b", "c"]);
1234    ///
1235    /// assert_eq!(map.len(), 3);
1236    /// ```
1237    #[cfg_attr(feature = "inline-more", inline)]
1238    pub fn keys(&self) -> Keys<'_, K> {
1239        Keys {
1240            iter: self.key_to_pos.keys(),
1241        }
1242    }
1243
1244    /// Returns the number of elements in the map.
1245    ///
1246    /// # Examples
1247    ///
1248    /// ```
1249    /// use stable_map::StableMap;
1250    ///
1251    /// let mut a = StableMap::new();
1252    /// assert_eq!(a.len(), 0);
1253    /// a.insert(1, "a");
1254    /// assert_eq!(a.len(), 1);
1255    /// ```
1256    #[cfg_attr(feature = "inline-more", inline)]
1257    pub fn len(&self) -> usize {
1258        self.key_to_pos.len()
1259    }
1260
1261    /// Removes a key from the map, returning the value at the key if the key
1262    /// was previously in the map. Keeps the allocated memory for reuse.
1263    ///
1264    /// The key may be any borrowed form of the map's key type, but
1265    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1266    /// the key type.
1267    ///
1268    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1269    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1270    ///
1271    /// # Examples
1272    ///
1273    /// ```
1274    /// use stable_map::StableMap;
1275    ///
1276    /// let mut map = StableMap::new();
1277    /// // The map is empty
1278    /// assert!(map.is_empty() && map.capacity() == 0);
1279    ///
1280    /// map.insert(1, "a");
1281    ///
1282    /// assert_eq!(map.remove(&1), Some("a"));
1283    /// assert_eq!(map.remove(&1), None);
1284    ///
1285    /// // Now map holds none elements
1286    /// assert!(map.is_empty());
1287    /// ```
1288    #[cfg_attr(feature = "inline-more", inline)]
1289    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
1290    where
1291        K: Eq + Hash,
1292        Q: Hash + Equivalent<K> + ?Sized,
1293        S: BuildHasher,
1294    {
1295        let pos = self.key_to_pos.remove(key)?;
1296        let value = unsafe {
1297            // SAFETY:
1298            // - By the invariants, pos is valid
1299            self.storage.take_unchecked(pos)
1300        };
1301        Some(value)
1302    }
1303
1304    /// Removes a key from the map, returning the stored key and value if the
1305    /// key was previously in the map. Keeps the allocated memory for reuse.
1306    ///
1307    /// The key may be any borrowed form of the map's key type, but
1308    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1309    /// the key type.
1310    ///
1311    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1312    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1313    ///
1314    /// # Examples
1315    ///
1316    /// ```
1317    /// use stable_map::StableMap;
1318    ///
1319    /// let mut map = StableMap::new();
1320    /// // The map is empty
1321    /// assert!(map.is_empty() && map.capacity() == 0);
1322    ///
1323    /// map.insert(1, "a");
1324    ///
1325    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1326    /// assert_eq!(map.remove(&1), None);
1327    ///
1328    /// // Now map hold none elements
1329    /// assert!(map.is_empty());
1330    /// ```
1331    #[cfg_attr(feature = "inline-more", inline)]
1332    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1333    where
1334        K: Eq + Hash,
1335        Q: Hash + Equivalent<K> + ?Sized,
1336        S: BuildHasher,
1337    {
1338        let (k, pos) = self.key_to_pos.remove_entry(key)?;
1339        let value = unsafe {
1340            // SAFETY:
1341            // - By the invariants, pos is valid
1342            self.storage.take_unchecked(pos)
1343        };
1344        Some((k, value))
1345    }
1346
1347    /// Reserves capacity for at least `additional` more elements to be inserted
1348    /// in the `StableMap`. The collection may reserve more space to avoid
1349    /// frequent reallocations.
1350    ///
1351    /// # Panics
1352    ///
1353    /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
1354    /// in case of allocation error.
1355    ///
1356    /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html
1357    /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html
1358    ///
1359    /// # Examples
1360    ///
1361    /// ```
1362    /// use stable_map::StableMap;
1363    /// let mut map: StableMap<&str, i32> = StableMap::new();
1364    /// // Map is empty and doesn't allocate memory
1365    /// assert_eq!(map.capacity(), 0);
1366    ///
1367    /// map.reserve(10);
1368    ///
1369    /// // And now map can hold at least 10 elements
1370    /// assert!(map.capacity() >= 10);
1371    /// ```
1372    #[cfg_attr(feature = "inline-more", inline)]
1373    pub fn reserve(&mut self, additional: usize)
1374    where
1375        K: Eq + Hash,
1376        S: BuildHasher,
1377    {
1378        self.key_to_pos.reserve(additional);
1379        self.storage.reserve(additional);
1380    }
1381
1382    /// Retains only the elements specified by the predicate. Keeps the
1383    /// allocated memory for reuse.
1384    ///
1385    /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
1386    /// The elements are visited in unsorted (and unspecified) order.
1387    ///
1388    /// # Examples
1389    ///
1390    /// ```
1391    /// use stable_map::StableMap;
1392    ///
1393    /// let mut map: StableMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1394    /// assert_eq!(map.len(), 8);
1395    ///
1396    /// map.retain(|&k, _| k % 2 == 0);
1397    ///
1398    /// // We can see, that the number of elements inside map is changed.
1399    /// assert_eq!(map.len(), 4);
1400    ///
1401    /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
1402    /// vec.sort_unstable();
1403    /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
1404    /// ```
1405    pub fn retain<F>(&mut self, mut f: F)
1406    where
1407        F: FnMut(&K, &mut V) -> bool,
1408    {
1409        let storage = &raw mut self.storage;
1410        let iter = self.key_to_pos.extract_if(move |k, pos| {
1411            let storage = unsafe {
1412                // SAFETY: See the documentation in extract_if
1413                &mut *storage
1414            };
1415            let value = unsafe {
1416                // SAFETY: By the invariants, pos is valid
1417                storage.get_unchecked_mut(pos)
1418            };
1419            let retain = f(k, value);
1420            !retain
1421        });
1422        for (_, pos) in iter {
1423            let storage = unsafe {
1424                // SAFETY: See the documentation in extract_if
1425                &mut *storage
1426            };
1427            unsafe {
1428                // SAFETY: By the invariants, pos is valid
1429                storage.take_unchecked(pos);
1430            }
1431        }
1432    }
1433
1434    /// Shrinks the capacity of the map as much as possible. It will drop
1435    /// down as much as possible while maintaining the internal rules
1436    /// and possibly leaving some space in accordance with the resize policy.
1437    ///
1438    /// # Examples
1439    ///
1440    /// ```
1441    /// use stable_map::StableMap;
1442    ///
1443    /// let mut map: StableMap<i32, i32> = StableMap::with_capacity(100);
1444    /// map.insert(1, 2);
1445    /// map.insert(3, 4);
1446    /// assert!(map.capacity() >= 100);
1447    /// map.shrink_to_fit();
1448    /// assert!(map.capacity() >= 2);
1449    /// ```
1450    #[cfg_attr(feature = "inline-more", inline)]
1451    pub fn shrink_to_fit(&mut self)
1452    where
1453        K: Eq + Hash,
1454        S: BuildHasher,
1455    {
1456        self.key_to_pos.shrink_to_fit();
1457        self.storage.shrink_to_fit();
1458    }
1459
1460    /// Tries to insert a key-value pair into the map, and returns
1461    /// a mutable reference to the value in the entry.
1462    ///
1463    /// # Errors
1464    ///
1465    /// If the map already had this key present, nothing is updated, and
1466    /// an error containing the occupied entry and the value is returned.
1467    ///
1468    /// # Examples
1469    ///
1470    /// Basic usage:
1471    ///
1472    /// ```
1473    /// use stable_map::{OccupiedError, StableMap};
1474    ///
1475    /// let mut map = StableMap::new();
1476    /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1477    ///
1478    /// match map.try_insert(37, "b") {
1479    ///     Err(OccupiedError { entry, value }) => {
1480    ///         assert_eq!(entry.key(), &37);
1481    ///         assert_eq!(entry.get(), &"a");
1482    ///         assert_eq!(value, "b");
1483    ///     }
1484    ///     _ => panic!()
1485    /// }
1486    /// ```
1487    #[cfg_attr(feature = "inline-more", inline)]
1488    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, S>>
1489    where
1490        K: Eq + Hash,
1491        S: BuildHasher,
1492    {
1493        match self.entry(key) {
1494            Entry::Occupied(o) => Err(OccupiedError { entry: o, value }),
1495            Entry::Vacant(v) => Ok(v.insert(value)),
1496        }
1497    }
1498
1499    /// An iterator visiting all values in arbitrary order.
1500    /// The iterator element type is `&'a V`.
1501    ///
1502    /// # Examples
1503    ///
1504    /// ```
1505    /// use stable_map::StableMap;
1506    ///
1507    /// let mut map = StableMap::new();
1508    /// map.insert("a", 1);
1509    /// map.insert("b", 2);
1510    /// map.insert("c", 3);
1511    /// assert_eq!(map.len(), 3);
1512    /// let mut vec: Vec<i32> = Vec::new();
1513    ///
1514    /// for val in map.values() {
1515    ///     println!("{}", val);
1516    ///     vec.push(*val);
1517    /// }
1518    ///
1519    /// // The `Values` iterator produces values in arbitrary order, so the
1520    /// // values must be sorted to test them against a sorted array.
1521    /// vec.sort_unstable();
1522    /// assert_eq!(vec, [1, 2, 3]);
1523    ///
1524    /// assert_eq!(map.len(), 3);
1525    /// ```
1526    #[cfg_attr(feature = "inline-more", inline)]
1527    pub fn values(&self) -> Values<'_, K, V> {
1528        Values {
1529            iter: self.key_to_pos.values(),
1530            storage: &self.storage,
1531        }
1532    }
1533
1534    /// An iterator visiting all values mutably in arbitrary order.
1535    /// The iterator element type is `&'a mut V`.
1536    ///
1537    /// # Examples
1538    ///
1539    /// ```
1540    /// use stable_map::StableMap;
1541    ///
1542    /// let mut map = StableMap::new();
1543    ///
1544    /// map.insert("a", 1);
1545    /// map.insert("b", 2);
1546    /// map.insert("c", 3);
1547    ///
1548    /// for val in map.values_mut() {
1549    ///     *val = *val + 10;
1550    /// }
1551    ///
1552    /// assert_eq!(map.len(), 3);
1553    /// let mut vec: Vec<i32> = Vec::new();
1554    ///
1555    /// for val in map.values() {
1556    ///     println!("{}", val);
1557    ///     vec.push(*val);
1558    /// }
1559    ///
1560    /// // The `Values` iterator produces values in arbitrary order, so the
1561    /// // values must be sorted to test them against a sorted array.
1562    /// vec.sort_unstable();
1563    /// assert_eq!(vec, [11, 12, 13]);
1564    ///
1565    /// assert_eq!(map.len(), 3);
1566    /// ```
1567    #[cfg_attr(feature = "inline-more", inline)]
1568    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
1569        ValuesMut {
1570            iter: self.key_to_pos.values_mut(),
1571            storage: self.storage.raw_access(),
1572        }
1573    }
1574
1575    /// Creates an empty `StableMap` with the specified capacity, using `hash_builder`
1576    /// to hash the keys.
1577    ///
1578    /// The hash map will be able to hold at least `capacity` elements without
1579    /// reallocating. If `capacity` is 0, the hash map will not allocate.
1580    ///
1581    /// # Examples
1582    ///
1583    /// ```
1584    /// use hashbrown::DefaultHashBuilder;
1585    /// use stable_map::StableMap;
1586    ///
1587    /// let s = DefaultHashBuilder::default();
1588    /// let mut map = StableMap::with_capacity_and_hasher(10, s);
1589    /// assert_eq!(map.len(), 0);
1590    /// assert!(map.capacity() >= 10);
1591    ///
1592    /// map.insert(1, 2);
1593    /// ```
1594    #[cfg_attr(feature = "inline-more", inline)]
1595    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
1596        Self {
1597            key_to_pos: HashMap::with_capacity_and_hasher(capacity, hash_builder),
1598            storage: LinearStorage::with_capacity(capacity),
1599        }
1600    }
1601
1602    /// Creates an empty `StableMap` which will use the given hash builder to hash
1603    /// keys.
1604    ///
1605    /// The hash map is initially created with a capacity of 0, so it will not
1606    /// allocate until it is first inserted into.
1607    ///
1608    /// # Examples
1609    ///
1610    /// ```
1611    /// use hashbrown::DefaultHashBuilder;
1612    /// use stable_map::StableMap;
1613    ///
1614    /// let s = DefaultHashBuilder::default();
1615    /// let mut map = StableMap::with_hasher(s);
1616    /// assert_eq!(map.len(), 0);
1617    /// assert_eq!(map.capacity(), 0);
1618    ///
1619    /// map.insert(1, 2);
1620    /// ```
1621    #[cfg_attr(feature = "inline-more", inline)]
1622    pub fn with_hasher(hash_builder: S) -> Self {
1623        Self {
1624            key_to_pos: HashMap::with_hasher(hash_builder),
1625            storage: LinearStorage::with_capacity(0),
1626        }
1627    }
1628
1629    /// Returns one more than the highest possible index of this map.
1630    ///
1631    /// Using [get_by_index](Self::get_by_index) with higher indices will always return
1632    /// `None`.
1633    ///
1634    /// # Examples
1635    ///
1636    /// ```
1637    /// use stable_map::StableMap;
1638    ///
1639    /// let mut a = StableMap::new();
1640    /// assert_eq!(a.index_len(), 0);
1641    /// a.insert(1, "a");
1642    /// a.insert(2, "b");
1643    /// a.remove(&2);
1644    /// assert_eq!(a.len(), 1);
1645    /// assert_eq!(a.index_len(), 2);
1646    /// ```
1647    #[cfg_attr(feature = "inline-more", inline)]
1648    pub fn index_len(&self) -> usize {
1649        self.storage.len()
1650    }
1651
1652    /// Returns the index that the key maps to.
1653    ///
1654    /// This function returns `Some` if and only if the key is contained in the map.
1655    ///
1656    /// As long as the key is not removed from the map, and unless
1657    /// [compact](Self::compact) or [force_compact](Self::force_compact) is called, this
1658    /// function will always return the same value.
1659    ///
1660    /// The returned value can be used to retrieve the value by using
1661    /// [get_by_index](Self::get_by_index) or [get_by_index_mut](Self::get_by_index_mut).
1662    ///
1663    /// # Examples
1664    ///
1665    /// ```
1666    /// use stable_map::StableMap;
1667    ///
1668    /// let mut a = StableMap::new();
1669    /// assert_eq!(a.index_len(), 0);
1670    /// a.insert(1, "a");
1671    /// assert_eq!(a.get_by_index(a.get_index(&1).unwrap()).unwrap(), &"a");
1672    /// ```
1673    #[cfg_attr(feature = "inline-more", inline)]
1674    pub fn get_index<Q>(&self, q: &Q) -> Option<usize>
1675    where
1676        S: BuildHasher,
1677        K: Eq + Hash,
1678        Q: Hash + Equivalent<K> + ?Sized,
1679    {
1680        self.key_to_pos.get(q).map(|v| unsafe {
1681            // SAFETY:
1682            // - By the invariants, v is valid
1683            v.get_unchecked()
1684        })
1685    }
1686
1687    /// Returns a reference to the value corresponding to the index.
1688    ///
1689    /// This function returns `Some` if and only if there is a key, `key`, for which
1690    /// [get_index](Self::get_index) returns this index. In this case, it returns the same
1691    /// value that would be returned by calling [get](Self::get).
1692    ///
1693    /// # Examples
1694    ///
1695    /// ```
1696    /// use stable_map::StableMap;
1697    ///
1698    /// let mut a = StableMap::new();
1699    /// assert_eq!(a.index_len(), 0);
1700    /// a.insert(1, "a");
1701    /// assert_eq!(a.get_by_index(a.get_index(&1).unwrap()).unwrap(), &"a");
1702    /// ```
1703    #[inline]
1704    pub fn get_by_index(&self, index: usize) -> Option<&V> {
1705        self.storage.get(index)
1706    }
1707
1708    /// Returns a mutable reference to the value corresponding to the index.
1709    ///
1710    /// This function returns `Some` if and only if there is a key, `key`, for which
1711    /// [get_index](Self::get_index) returns this index. In this case, it returns the same
1712    /// value that would be returned by calling [get_mut](Self::get_mut).
1713    ///
1714    /// # Examples
1715    ///
1716    /// ```
1717    /// use stable_map::StableMap;
1718    ///
1719    /// let mut a = StableMap::new();
1720    /// assert_eq!(a.index_len(), 0);
1721    /// a.insert(1, "a");
1722    /// assert_eq!(a.get_by_index_mut(a.get_index(&1).unwrap()).unwrap(), &"a");
1723    /// ```
1724    #[inline]
1725    pub fn get_by_index_mut(&mut self, index: usize) -> Option<&mut V> {
1726        self.storage.get_mut(index)
1727    }
1728
1729    /// Returns a reference to the value corresponding to the index, without
1730    /// validating that the index is valid.
1731    ///
1732    /// This function returns the same value that would be returned by
1733    /// [get_by_index](Self::get_by_index).
1734    ///
1735    /// # Safety
1736    ///
1737    /// There must be some `key` for which `self.get_index(k)` would return this index.
1738    ///
1739    /// # Examples
1740    ///
1741    /// ```
1742    /// use stable_map::StableMap;
1743    ///
1744    /// let mut a = StableMap::new();
1745    /// assert_eq!(a.index_len(), 0);
1746    /// a.insert(1, "a");
1747    /// unsafe {
1748    ///     assert_eq!(a.get_by_index_unchecked(a.get_index(&1).unwrap()), &"a");
1749    /// }
1750    /// ```
1751    #[inline]
1752    pub unsafe fn get_by_index_unchecked(&self, index: usize) -> &V {
1753        unsafe {
1754            // SAFETY:
1755            // - By the requirements of this function, there is an element of key_to_pos
1756            //   with this index.
1757            // - By the invariants, that element could be used to call get_unchecked.
1758            self.storage.get_unchecked_raw(index)
1759        }
1760    }
1761
1762    /// Returns a mutable reference to the value corresponding to the index, without
1763    /// validating that the index is valid.
1764    ///
1765    /// This function returns the same value that would be returned by
1766    /// [get_by_index_mut](Self::get_by_index_mut).
1767    ///
1768    /// # Safety
1769    ///
1770    /// There must be some `key` for which `self.get_index(k)` would return this index.
1771    ///
1772    /// # Examples
1773    ///
1774    /// ```
1775    /// use stable_map::StableMap;
1776    ///
1777    /// let mut a = StableMap::new();
1778    /// assert_eq!(a.index_len(), 0);
1779    /// a.insert(1, "a");
1780    /// unsafe {
1781    ///     assert_eq!(a.get_by_index_unchecked_mut(a.get_index(&1).unwrap()), &"a");
1782    /// }
1783    /// ```
1784    #[inline]
1785    pub unsafe fn get_by_index_unchecked_mut(&mut self, index: usize) -> &mut V {
1786        unsafe {
1787            // SAFETY:
1788            // - By the requirements of this function, there is an element of key_to_pos
1789            //   with this index.
1790            // - By the invariants, that element could be used to call get_unchecked_mut.
1791            self.storage.get_unchecked_raw_mut(index)
1792        }
1793    }
1794
1795    /// Maybe compacts the map, removing indices for which `get_by_index` would return
1796    /// `None`.
1797    ///
1798    /// This function does nothing if there are no more than 8 indices for which
1799    /// [get_by_index](Self::get_by_index) returns `None` or if at least half of the
1800    /// indices are in use.
1801    ///
1802    /// # Examples
1803    ///
1804    /// ```
1805    /// use stable_map::StableMap;
1806    ///
1807    /// let mut map = StableMap::new();
1808    /// for i in 0..32 {
1809    ///     map.insert(i, i);
1810    /// }
1811    /// for i in 0..16 {
1812    ///     map.remove(&i);
1813    /// }
1814    /// assert_eq!(map.index_len(), 32);
1815    /// map.compact();
1816    /// assert_eq!(map.index_len(), 32);
1817    /// map.remove(&16);
1818    /// map.compact();
1819    /// assert_eq!(map.index_len(), 15);
1820    /// ```
1821    #[cfg_attr(feature = "inline-more", inline)]
1822    pub fn compact(&mut self) {
1823        self.storage.compact();
1824    }
1825
1826    /// Compacts the map, removing indices for which `get_by_index` would return `None`.
1827    ///
1828    /// After this function returns, [index_len](Self::index_len) will be the same as
1829    /// [len](Self::len).
1830    ///
1831    /// # Examples
1832    ///
1833    /// ```
1834    /// use stable_map::StableMap;
1835    ///
1836    /// let mut map = StableMap::new();
1837    /// map.insert(1, 1);
1838    /// map.remove(&1);
1839    /// assert_eq!(map.index_len(), 1);
1840    /// map.force_compact();
1841    /// assert_eq!(map.index_len(), 0);
1842    /// ```
1843    #[cfg_attr(feature = "inline-more", inline)]
1844    pub fn force_compact(&mut self) {
1845        self.storage.force_compact();
1846    }
1847}
1848
1849impl<K, V, S> IntoIterator for StableMap<K, V, S> {
1850    type Item = (K, V);
1851    type IntoIter = IntoIter<K, V>;
1852
1853    fn into_iter(self) -> Self::IntoIter {
1854        IntoIter {
1855            iter: self.key_to_pos.into_iter(),
1856            storage: self.storage,
1857        }
1858    }
1859}