blob: e842cd2cc9b8c22177d08bba6cb2cedc134c0e2b [file] [log] [blame]
Joel Galenson2370d122020-10-12 16:02:26 -07001//! A hash map where the keys and values are both held by weak pointers, and keys are compared by
2//! pointer.
3
4use std::collections::hash_map::RandomState;
5use std::fmt::{self, Debug};
6use std::hash::BuildHasher;
7use std::iter::FromIterator;
8use std::ops::Deref;
9
10use super::by_ptr::*;
11use super::traits::*;
12use super::weak_weak_hash_map as base;
13
14pub use super::PtrWeakWeakHashMap;
15pub use super::weak_weak_hash_map::{Entry, Iter, Keys, Values, Drain, IntoIter};
16
17impl <K: WeakElement, V: WeakElement> PtrWeakWeakHashMap<K, V, RandomState>
18 where K::Strong: Deref
19{
20 /// Creates an empty `PtrWeakWeakHashMap`.
21 pub fn new() -> Self {
22 PtrWeakWeakHashMap(base::WeakWeakHashMap::new())
23 }
24
25 /// Creates an empty `PtrWeakWeakHashMap` with the given capacity.
26 pub fn with_capacity(capacity: usize) -> Self {
27 PtrWeakWeakHashMap(base::WeakWeakHashMap::with_capacity(capacity))
28 }
29}
30
31impl <K: WeakElement, V: WeakElement, S: BuildHasher> PtrWeakWeakHashMap<K, V, S>
32 where K::Strong: Deref
33{
34 /// Creates an empty `PtrWeakWeakHashMap` with the given capacity and hasher.
35 pub fn with_hasher(hash_builder: S) -> Self {
36 PtrWeakWeakHashMap(base::WeakWeakHashMap::with_hasher(hash_builder))
37 }
38
39 /// Creates an empty `PtrWeakWeakHashMap` with the given capacity and hasher.
40 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
41 PtrWeakWeakHashMap(base::WeakWeakHashMap::with_capacity_and_hasher(capacity, hash_builder))
42 }
43
44 /// Returns a reference to the map's `BuildHasher`.
45 pub fn hasher(&self) -> &S {
46 self.0.hasher()
47 }
48
49 /// Returns the number of elements the map can hold without reallocating.
50 pub fn capacity(&self) -> usize {
51 self.0.capacity()
52 }
53
54 /// Removes all mappings whose keys have expired.
55 pub fn remove_expired(&mut self) {
56 self.0.remove_expired()
57 }
58
59 /// Reserves room for additional elements.
60 pub fn reserve(&mut self, additional_capacity: usize) {
61 self.0.reserve(additional_capacity)
62 }
63
64 /// Shrinks the capacity to the minimum allowed to hold the current number of elements.
65 pub fn shrink_to_fit(&mut self) {
66 self.0.shrink_to_fit()
67 }
68
69 /// Returns an over-approximation of the number of elements.
70 pub fn len(&self) -> usize {
71 self.0.len()
72 }
73
74 /// Is the map empty?
75 ///
76 /// Note that this may return false even if all keys in the map have
77 /// expired, if they haven't been collected yet.
78 pub fn is_empty(&self) -> bool {
79 self.0.is_empty()
80 }
81
82 /// The proportion of buckets that are used.
83 ///
84 /// This is an over-approximation because of expired keys.
85 pub fn load_factor(&self) -> f32 {
86 self.0.load_factor()
87 }
88
89 /// Gets the requested entry.
90 pub fn entry(&mut self, key: K::Strong) -> Entry<ByPtr<K>, V> {
91 self.0.entry(key)
92 }
93
94 /// Removes all associations from the map.
95 pub fn clear(&mut self) {
96 self.0.clear()
97 }
98
99 /// Returns a reference to the value corresponding to the key.
100 pub fn get(&self, key: &K::Strong) -> Option<V::Strong> {
101 self.0.get(&(key.deref() as *const _))
102 }
103
104 /// Returns true if the map contains the specified key.
105 pub fn contains_key(&self, key: &K::Strong) -> bool {
106 self.0.contains_key(&(key.deref() as *const _))
107 }
108
109 /// Unconditionally inserts the value, returning the old value if already present. Does not
110 /// replace the key.
111 pub fn insert(&mut self, key: K::Strong, value: V::Strong) -> Option<V::Strong> {
112 self.0.insert(key, value)
113 }
114
115 /// Removes the entry with the given key, if it exists, and returns the value.
116 pub fn remove(&mut self, key: &K::Strong) -> Option<V::Strong> {
117 self.0.remove(&(key.deref() as *const _))
118 }
119
120 /// Removes all mappings not satisfying the given predicate.
121 ///
122 /// Also removes any expired mappings.
123 pub fn retain<F>(&mut self, f: F)
124 where F: FnMut(K::Strong, V::Strong) -> bool
125 {
126 self.0.retain(f)
127 }
128
129 /// Is this map a submap of the other, using the given value comparison.
130 ///
131 /// In particular, all the keys of self must be in other and the values must compare true with
132 /// value_equal.
133 pub fn submap_with<F, S1, V1>(&self, other: &PtrWeakWeakHashMap<K, V1, S1>, value_equal: F) -> bool
134 where F: FnMut(V::Strong, V1::Strong) -> bool,
135 V1: WeakElement,
136 S1: BuildHasher
137 {
138 self.0.is_submap_with(&other.0, value_equal)
139 }
140
141 /// Is self a submap of other?
142 pub fn is_submap<V1, S1>(&self, other: &PtrWeakWeakHashMap<K, V1, S1>) -> bool
143 where V1: WeakElement,
144 V::Strong: PartialEq<V1::Strong>,
145 S1: BuildHasher
146 {
147 self.0.is_submap(&other.0)
148 }
149
150 /// Are the keys of self a subset of the keys of other?
151 pub fn domain_is_subset<V1, S1>(&self, other: &PtrWeakWeakHashMap<K, V1, S1>) -> bool
152 where V1: WeakElement,
153 S1: BuildHasher
154 {
155 self.0.domain_is_subset(&other.0)
156 }
157}
158
159impl<K: WeakElement, V: WeakElement, S> PtrWeakWeakHashMap<K, V, S>
160 where K::Strong: Deref
161{
162 /// Gets an iterator over the keys and values.
163 pub fn iter(&self) -> Iter<ByPtr<K>, V> {
164 self.0.iter()
165 }
166
167 /// Gets an iterator over the keys.
168 pub fn keys(&self) -> Keys<ByPtr<K>, V> {
169 self.0.keys()
170 }
171
172 /// Gets an iterator over the values.
173 pub fn values(&self) -> Values<ByPtr<K>, V> {
174 self.0.values()
175 }
176
177 /// Gets a draining iterator, which removes all the values but retains the storage.
178 pub fn drain(&mut self) -> Drain<ByPtr<K>, V> {
179 self.0.drain()
180 }
181}
182
183impl<K, V, V1, S, S1> PartialEq<PtrWeakWeakHashMap<K, V1, S1>>
184 for PtrWeakWeakHashMap<K, V, S>
185 where K: WeakElement,
186 K::Strong: Deref,
187 V: WeakElement,
188 V1: WeakElement,
189 V::Strong: PartialEq<V1::Strong>,
190 S: BuildHasher,
191 S1: BuildHasher
192{
193 fn eq(&self, other: &PtrWeakWeakHashMap<K, V1, S1>) -> bool {
194 self.0 == other.0
195 }
196}
197
198impl<K: WeakElement, V: WeakElement, S: BuildHasher> Eq for PtrWeakWeakHashMap<K, V, S>
199 where K::Strong: Deref,
200 V::Strong: Eq
201{ }
202
203impl<K: WeakElement, V: WeakElement, S: BuildHasher + Default> Default for PtrWeakWeakHashMap<K, V, S>
204 where K::Strong: Deref
205{
206 fn default() -> Self {
207 PtrWeakWeakHashMap(base::WeakWeakHashMap::<ByPtr<K>, V, S>::default())
208 }
209}
210
211impl<K, V, S> FromIterator<(K::Strong, V::Strong)> for PtrWeakWeakHashMap<K, V, S>
212 where K: WeakElement,
213 K::Strong: Deref,
214 V: WeakElement,
215 S: BuildHasher + Default
216{
217 fn from_iter<T: IntoIterator<Item=(K::Strong, V::Strong)>>(iter: T) -> Self {
218 PtrWeakWeakHashMap(base::WeakWeakHashMap::<ByPtr<K>, V, S>::from_iter(iter))
219 }
220}
221
222impl<K, V, S> Extend<(K::Strong, V::Strong)> for PtrWeakWeakHashMap<K, V, S>
223 where K: WeakElement,
224 K::Strong: Deref,
225 V: WeakElement,
226 S: BuildHasher
227{
228 fn extend<T: IntoIterator<Item=(K::Strong, V::Strong)>>(&mut self, iter: T) {
229 self.0.extend(iter)
230 }
231}
232
233impl<K, V, S> Debug for PtrWeakWeakHashMap<K, V, S>
234 where K: WeakElement,
235 K::Strong: Debug,
236 V: WeakElement,
237 V::Strong: Debug
238{
239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240 self.0.fmt(f)
241 }
242}
243
244impl<K: WeakElement, V: WeakElement, S> IntoIterator for PtrWeakWeakHashMap<K, V, S> {
245 type Item = (K::Strong, V::Strong);
246 type IntoIter = IntoIter<ByPtr<K>, V>;
247
248 fn into_iter(self) -> Self::IntoIter {
249 self.0.into_iter()
250 }
251}
252
253impl<'a, K: WeakElement, V: WeakElement, S> IntoIterator for &'a PtrWeakWeakHashMap<K, V, S> {
254 type Item = (K::Strong, V::Strong);
255 type IntoIter = Iter<'a, ByPtr<K>, V>;
256
257 fn into_iter(self) -> Self::IntoIter {
258 (&self.0).into_iter()
259 }
260}
261
262#[cfg(test)]
263mod test
264{
265 use crate::PtrWeakWeakHashMap;
266 use crate::weak_weak_hash_map::Entry;
267 use std::rc::{Rc, Weak};
268
269// fn show_me(weakmap: &PtrWeakWeakHashMap<Weak<u32>, Weak<f32>>) {
270// for (key, _) in weakmap {
271// eprint!(" {:2}", *key);
272// }
273// eprintln!();
274// }
275
276 // From https://github.com/tov/weak-table-rs/issues/1#issuecomment-461858060
277 #[test]
278 fn insert_and_check() {
279 let mut rcs: Vec<(Rc<u32>, Rc<f32>)> = Vec::new();
280
281 for i in 0 .. 200 {
282 rcs.push((Rc::new(i), Rc::new(i as f32 + 0.1)));
283 }
284
285 let mut weakmap: PtrWeakWeakHashMap<Weak<u32>, Weak<f32>> = PtrWeakWeakHashMap::new();
286
287 for (key, value) in rcs.iter().cloned() {
288 weakmap.insert(key, value);
289// show_me(&weakmap);
290 }
291
292 let mut count = 0;
293
294 for (key, value) in &rcs {
295 assert!(weakmap.contains_key(key));
296
297 match weakmap.entry(Rc::clone(key)) {
298 Entry::Occupied(occ) => {
299 assert_eq!( occ.get(), value );
300 count += 1;
301 }
302 Entry::Vacant(_) => {
303 eprintln!("PointerWeakWeakHashMap: missing: {}", *key);
304 }
305 }
306 }
307
308 assert_eq!( count, rcs.len() );
309 }
310}
311
312