indexmap_amortized/
mutable_keys.rs

1use core::hash::{BuildHasher, Hash};
2
3use super::{Equivalent, IndexMap};
4
5pub struct PrivateMarker {}
6
7/// Opt-in mutable access to keys.
8///
9/// These methods expose `&mut K`, mutable references to the key as it is stored
10/// in the map.
11/// You are allowed to modify the keys in the hashmap **if the modifcation
12/// does not change the key’s hash and equality**.
13///
14/// If keys are modified erronously, you can no longer look them up.
15/// This is sound (memory safe) but a logical error hazard (just like
16/// implementing PartialEq, Eq, or Hash incorrectly would be).
17///
18/// `use` this trait to enable its methods for `IndexMap`.
19pub trait MutableKeys {
20    type Key;
21    type Value;
22
23    /// Return item index, mutable reference to key and value
24    fn get_full_mut2<Q: ?Sized>(
25        &mut self,
26        key: &Q,
27    ) -> Option<(usize, &mut Self::Key, &mut Self::Value)>
28    where
29        Q: Hash + Equivalent<Self::Key>;
30
31    /// Scan through each key-value pair in the map and keep those where the
32    /// closure `keep` returns `true`.
33    ///
34    /// The elements are visited in order, and remaining elements keep their
35    /// order.
36    ///
37    /// Computes in **O(n)** time (average).
38    fn retain2<F>(&mut self, keep: F)
39    where
40        F: FnMut(&mut Self::Key, &mut Self::Value) -> bool;
41
42    /// This method is not useful in itself – it is there to “seal” the trait
43    /// for external implementation, so that we can add methods without
44    /// causing breaking changes.
45    fn __private_marker(&self) -> PrivateMarker;
46}
47
48/// Opt-in mutable access to keys.
49///
50/// See [`MutableKeys`](trait.MutableKeys.html) for more information.
51impl<K, V, S> MutableKeys for IndexMap<K, V, S>
52where
53    K: Eq + Hash,
54    S: BuildHasher,
55{
56    type Key = K;
57    type Value = V;
58    fn get_full_mut2<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, &mut K, &mut V)>
59    where
60        Q: Hash + Equivalent<K>,
61    {
62        self.get_full_mut2_impl(key)
63    }
64
65    fn retain2<F>(&mut self, keep: F)
66    where
67        F: FnMut(&mut K, &mut V) -> bool,
68    {
69        self.retain_mut(keep)
70    }
71
72    fn __private_marker(&self) -> PrivateMarker {
73        PrivateMarker {}
74    }
75}