ordermap/
mutable_keys.rs

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