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