Joel Galenson | 2370d12 | 2020-10-12 16:02:26 -0700 | [diff] [blame] | 1 | //! A hash map where the keys and values are both held by weak pointers, and keys are compared by |
| 2 | //! value. |
| 3 | |
| 4 | use std::borrow::Borrow; |
| 5 | use std::cmp::max; |
| 6 | use std::collections::hash_map::RandomState; |
| 7 | use std::hash::{BuildHasher, Hash, Hasher}; |
| 8 | use std::fmt::{self, Debug, Formatter}; |
| 9 | use std::mem; |
| 10 | |
| 11 | use super::*; |
| 12 | use super::size_policy::*; |
| 13 | use super::traits::*; |
| 14 | use super::util::*; |
| 15 | |
| 16 | pub use super::WeakWeakHashMap; |
| 17 | |
| 18 | /// Represents an entry in the table which may be occupied or vacant. |
| 19 | pub enum Entry<'a, K: 'a + WeakKey, V: 'a + WeakElement> { |
| 20 | Occupied(OccupiedEntry<'a, K, V>), |
| 21 | Vacant(VacantEntry<'a, K, V>), |
| 22 | } |
| 23 | |
| 24 | /// An occupied entry, which can be removed or viewed. |
| 25 | pub struct OccupiedEntry<'a, K: 'a + WeakKey, V: 'a + WeakElement> { |
| 26 | inner: InnerEntry<'a, K, V>, |
| 27 | value: V::Strong, |
| 28 | } |
| 29 | |
| 30 | /// A vacant entry, which can be inserted in or viewed. |
| 31 | pub struct VacantEntry<'a, K: 'a + WeakKey, V: 'a + WeakElement> { |
| 32 | inner: InnerEntry<'a, K, V>, |
| 33 | } |
| 34 | |
| 35 | struct InnerEntry<'a, K: 'a + WeakKey, V: 'a> { |
| 36 | map: &'a mut WeakWeakInnerMap<K, V>, |
| 37 | pos: usize, |
| 38 | key: K::Strong, |
| 39 | hash_code: HashCode, |
| 40 | } |
| 41 | |
| 42 | /// An iterator over the keys and values of the weak hash map. |
| 43 | #[derive(Clone, Debug)] |
| 44 | pub struct Iter<'a, K: 'a, V: 'a> { |
| 45 | base: ::std::slice::Iter<'a, Bucket<K, V>>, |
| 46 | size: usize, |
| 47 | } |
| 48 | |
| 49 | impl<'a, K: WeakElement, V: WeakElement> Iterator for Iter<'a, K, V> { |
| 50 | type Item = (K::Strong, V::Strong); |
| 51 | |
| 52 | fn next(&mut self) -> Option<Self::Item> { |
| 53 | while let Some(bucket) = self.base.next() { |
| 54 | if let Some((ref weak_key, ref weak_value, _)) = *bucket { |
| 55 | self.size -= 1; |
| 56 | if let (Some(key), Some(value)) = (weak_key.view(), weak_value.view()) { |
| 57 | return Some((key, value)); |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | None |
| 63 | } |
| 64 | |
| 65 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 66 | (0, Some(self.size)) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// An iterator over the keys of the weak hash map. |
| 71 | #[derive(Clone, Debug)] |
| 72 | pub struct Keys<'a, K: 'a, V: 'a>(Iter<'a, K, V>); |
| 73 | |
| 74 | impl<'a, K: WeakElement, V: WeakElement> Iterator for Keys<'a, K, V> { |
| 75 | type Item = K::Strong; |
| 76 | |
| 77 | fn next(&mut self) -> Option<Self::Item> { |
| 78 | self.0.next().map(|(k, _)| k) |
| 79 | } |
| 80 | |
| 81 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 82 | self.0.size_hint() |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// An iterator over the values of the weak hash map. |
| 87 | #[derive(Clone, Debug)] |
| 88 | pub struct Values<'a, K: 'a, V: 'a>(Iter<'a, K, V>); |
| 89 | |
| 90 | impl<'a, K: WeakElement, V: WeakElement> Iterator for Values<'a, K, V> { |
| 91 | type Item = V::Strong; |
| 92 | |
| 93 | fn next(&mut self) -> Option<Self::Item> { |
| 94 | self.0.next().map(|(_, v)| v) |
| 95 | } |
| 96 | |
| 97 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 98 | self.0.size_hint() |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug)] |
| 103 | /// An iterator that consumes the values of a weak hash map, leaving it empty. |
| 104 | pub struct Drain<'a, K: 'a, V: 'a> { |
| 105 | base: ::std::slice::IterMut<'a, Bucket<K, V>>, |
| 106 | size: usize, |
| 107 | } |
| 108 | |
| 109 | impl<'a, K: WeakElement, V: WeakElement> Iterator for Drain<'a, K, V> { |
| 110 | type Item = (K::Strong, V::Strong); |
| 111 | |
| 112 | fn next(&mut self) -> Option<Self::Item> { |
| 113 | while let Some(bucket) = self.base.next() { |
| 114 | if let Some((weak_key, weak_value, _)) = bucket.take() { |
| 115 | self.size -= 1; |
| 116 | if let (Some(key), Some(value)) = (weak_key.view(), weak_value.view()) { |
| 117 | return Some((key, value)); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | None |
| 123 | } |
| 124 | |
| 125 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 126 | (0, Some(self.size)) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | impl<'a, K, V> Drop for Drain<'a, K, V> { |
| 131 | fn drop(&mut self) { |
| 132 | while let Some(option) = self.base.next() { |
| 133 | *option = None; |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// An iterator that consumes the values of a weak hash map, leaving it empty. |
| 139 | pub struct IntoIter<K, V> { |
| 140 | base: ::std::vec::IntoIter<Bucket<K, V>>, |
| 141 | size: usize, |
| 142 | } |
| 143 | |
| 144 | impl<K: WeakElement, V: WeakElement> Iterator for IntoIter<K, V> { |
| 145 | type Item = (K::Strong, V::Strong); |
| 146 | |
| 147 | fn next(&mut self) -> Option<Self::Item> { |
| 148 | while let Some(bucket) = self.base.next() { |
| 149 | if let Some((weak_key, weak_value, _)) = bucket { |
| 150 | self.size -= 1; |
| 151 | if let (Some(key), Some(value)) = (weak_key.view(), weak_value.view()) { |
| 152 | return Some((key, value)); |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | None |
| 158 | } |
| 159 | |
| 160 | fn size_hint(&self) -> (usize, Option<usize>) { |
| 161 | (0, Some(self.size)) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | impl<K: WeakKey, V: WeakElement> WeakWeakHashMap<K, V, RandomState> |
| 166 | { |
| 167 | /// Creates an empty `WeakWeakHashMap`. |
| 168 | pub fn new() -> Self { |
| 169 | Self::with_capacity(DEFAULT_INITIAL_CAPACITY) |
| 170 | } |
| 171 | |
| 172 | /// Creates an empty `WeakWeakHashMap` with the given capacity. |
| 173 | pub fn with_capacity(capacity: usize) -> Self { |
| 174 | Self::with_capacity_and_hasher(capacity, Default::default()) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | impl<K: WeakKey, V: WeakElement, S: BuildHasher> WeakWeakHashMap<K, V, S> { |
| 179 | /// Creates an empty `WeakWeakHashMap` with the given capacity and hasher. |
| 180 | pub fn with_hasher(hash_builder: S) -> Self { |
| 181 | Self::with_capacity_and_hasher(DEFAULT_INITIAL_CAPACITY, hash_builder) |
| 182 | } |
| 183 | |
| 184 | /// Creates an empty `WeakWeakHashMap` with the given capacity and hasher. |
| 185 | pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { |
| 186 | WeakWeakHashMap { |
| 187 | hash_builder, |
| 188 | inner: WeakWeakInnerMap { |
| 189 | buckets: new_boxed_option_slice(capacity), |
| 190 | len: 0, |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// Returns a reference to the map's `BuildHasher`. |
| 196 | pub fn hasher(&self) -> &S { |
| 197 | &self.hash_builder |
| 198 | } |
| 199 | |
| 200 | /// Returns the number of elements the map can hold without reallocating. |
| 201 | pub fn capacity(&self) -> usize { |
| 202 | self.inner.capacity() |
| 203 | } |
| 204 | |
| 205 | /// This has some preconditions. |
| 206 | fn resize(&mut self, capacity: usize) { |
| 207 | let old_buckets = mem::replace(&mut self.inner.buckets, |
| 208 | new_boxed_option_slice(capacity)); |
| 209 | |
| 210 | let iter = IntoIter { |
| 211 | base: old_buckets.into_vec().into_iter(), |
| 212 | size: self.inner.len, |
| 213 | }; |
| 214 | |
| 215 | self.inner.len = 0; |
| 216 | |
| 217 | for (key, value) in iter { |
| 218 | self.entry_no_grow(key).or_insert(value); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /// Removes all mappings whose keys have expired. |
| 223 | pub fn remove_expired(&mut self) { |
| 224 | self.retain(|_, _| true) |
| 225 | } |
| 226 | |
| 227 | /// Reserves room for additional elements. |
| 228 | pub fn reserve(&mut self, additional_capacity: usize) { |
| 229 | let new_capacity = additional_capacity + self.capacity(); |
| 230 | self.resize(new_capacity); |
| 231 | } |
| 232 | |
| 233 | /// Shrinks the capacity to the minimum allowed to hold the current number of elements. |
| 234 | pub fn shrink_to_fit(&mut self) { |
| 235 | self.remove_expired(); |
| 236 | let new_capacity = (self.len() as f32 / COLLECT_LOAD_FACTOR).ceil() as usize; |
| 237 | self.resize(new_capacity); |
| 238 | } |
| 239 | |
| 240 | /// Returns an over-approximation of the number of elements. |
| 241 | pub fn len(&self) -> usize { |
| 242 | self.inner.len |
| 243 | } |
| 244 | |
| 245 | /// Is the map empty? |
| 246 | /// |
| 247 | /// Note that this may return false even if all keys in the map have |
| 248 | /// expired, if they haven't been collected yet. |
| 249 | pub fn is_empty(&self) -> bool { |
| 250 | self.len() == 0 |
| 251 | } |
| 252 | |
| 253 | /// The proportion of buckets that are used. |
| 254 | /// |
| 255 | /// This is an over-approximation because of expired keys. |
| 256 | pub fn load_factor(&self) -> f32 { |
| 257 | (self.len() as f32 + 1.0) / self.capacity() as f32 |
| 258 | } |
| 259 | |
| 260 | fn maybe_adjust_size(&mut self) { |
| 261 | if self.load_factor() > COLLECT_LOAD_FACTOR { |
| 262 | self.remove_expired(); |
| 263 | |
| 264 | let load_factor = self.load_factor(); |
| 265 | let capacity = self.capacity(); |
| 266 | if load_factor > GROW_LOAD_FACTOR { |
| 267 | self.resize(max(1, capacity * 2)); |
| 268 | } else if load_factor < SHRINK_LOAD_FACTOR && capacity > DEFAULT_INITIAL_CAPACITY { |
| 269 | self.resize(max(1, capacity / 2)); |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /// Gets the requested entry. |
| 275 | pub fn entry(&mut self, key: K::Strong) -> Entry<K, V> { |
| 276 | self.maybe_adjust_size(); |
| 277 | self.entry_no_grow(key) |
| 278 | } |
| 279 | |
| 280 | fn entry_no_grow(&mut self, key: K::Strong) -> Entry<K, V> { |
| 281 | let mut inner = { |
| 282 | let hash_code = K::with_key(&key, |k| self.hash(k)); |
| 283 | InnerEntry { |
| 284 | pos: self.which_bucket(hash_code), |
| 285 | map: &mut self.inner, |
| 286 | hash_code, |
| 287 | key, |
| 288 | } |
| 289 | }; |
| 290 | |
| 291 | for dist in 0 .. inner.capacity() { |
| 292 | match inner.bucket_status() { |
| 293 | BucketStatus::Unoccupied => |
| 294 | return Entry::Vacant(VacantEntry {inner}), |
| 295 | BucketStatus::MatchesKey(value) => |
| 296 | return Entry::Occupied(OccupiedEntry {value, inner}), |
| 297 | BucketStatus::ProbeDistance(bucket_distance) => { |
| 298 | if bucket_distance < dist { |
| 299 | return Entry::Vacant(VacantEntry {inner}) |
| 300 | } else { |
| 301 | inner.pos = inner.next_bucket(inner.pos); |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | panic!("WeakKeyHashTable::entry: out of space"); |
| 308 | } |
| 309 | |
| 310 | /// Removes all associations from the map. |
| 311 | pub fn clear(&mut self) { |
| 312 | self.drain(); |
| 313 | } |
| 314 | |
| 315 | fn find_bucket<Q>(&self, key: &Q) -> Option<(usize, K::Strong, V::Strong)> |
| 316 | where Q: ?Sized + Hash + Eq, |
| 317 | K::Key: Borrow<Q> |
| 318 | { |
| 319 | if self.capacity() == 0 { return None; } |
| 320 | |
| 321 | let hash_code = self.hash(key); |
| 322 | let mut pos = self.which_bucket(hash_code); |
| 323 | |
| 324 | for dist in 0 .. self.capacity() { |
| 325 | if let Some((ref w_key, ref w_value, b_hash_code)) = self.inner.buckets[pos] { |
| 326 | if b_hash_code == hash_code { |
| 327 | if let (Some(b_key), Some(b_value)) = (w_key.view(), w_value.view()) { |
| 328 | if K::with_key(&b_key, |k| k.borrow() == key) { |
| 329 | return Some((pos, b_key, b_value)); |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | let bucket_dist = |
| 335 | self.probe_distance(pos, self.which_bucket(hash_code)); |
| 336 | if bucket_dist < dist { |
| 337 | return None; |
| 338 | } |
| 339 | } else { |
| 340 | return None; |
| 341 | } |
| 342 | |
| 343 | pos = self.next_bucket(pos); |
| 344 | } |
| 345 | |
| 346 | None |
| 347 | } |
| 348 | |
| 349 | /// Returns a reference to the value corresponding to the key. |
| 350 | pub fn get<Q>(&self, key: &Q) -> Option<V::Strong> |
| 351 | where Q: ?Sized + Hash + Eq, |
| 352 | K::Key: Borrow<Q> |
| 353 | { |
| 354 | self.find_bucket(key).map(|tup| tup.2) |
| 355 | } |
| 356 | |
| 357 | /// Returns the strong reference to the key, if present. |
| 358 | pub fn get_key<Q>(&self, key: &Q) -> Option<K::Strong> |
| 359 | where Q: ?Sized + Hash + Eq, |
| 360 | K::Key: Borrow<Q> |
| 361 | { |
| 362 | self.find_bucket(key).map(|tup| tup.1) |
| 363 | } |
| 364 | |
| 365 | /// Returns strong references to both the key and the value, if present. |
| 366 | pub fn get_both<Q>(&self, key: &Q) -> Option<(K::Strong, V::Strong)> |
| 367 | where Q: ?Sized + Hash + Eq, |
| 368 | K::Key: Borrow<Q> |
| 369 | { |
| 370 | self.find_bucket(key).map(|tup| (tup.1, tup.2)) |
| 371 | } |
| 372 | |
| 373 | /// Returns true if the map contains the specified key. |
| 374 | pub fn contains_key<Q>(&self, key: &Q) -> bool |
| 375 | where Q: ?Sized + Hash + Eq, |
| 376 | K::Key: Borrow<Q> |
| 377 | { |
| 378 | self.find_bucket(key).is_some() |
| 379 | } |
| 380 | |
| 381 | /// Unconditionally inserts the value, returning the old value if already present. |
| 382 | /// |
| 383 | /// Unlike `std::collections::HashMap`, this replaces the key even if occupied. |
| 384 | pub fn insert(&mut self, key: K::Strong, value: V::Strong) -> Option<V::Strong> { |
| 385 | match self.entry(key) { |
| 386 | Entry::Occupied(mut occupied) => { |
| 387 | Some(occupied.insert(value)) |
| 388 | }, |
| 389 | Entry::Vacant(vacant) => { |
| 390 | vacant.insert(value); |
| 391 | None |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | /// Removes the entry with the given key, if it exists, and returns the value. |
| 397 | pub fn remove<Q>(&mut self, key: &Q) -> Option<V::Strong> |
| 398 | where Q: ?Sized + Hash + Eq, |
| 399 | K::Key: Borrow<Q> |
| 400 | { |
| 401 | if let Some((pos, _, value)) = self.find_bucket(key) { |
| 402 | self.inner.remove_index(pos); |
| 403 | Some(value) |
| 404 | } else { |
| 405 | None |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | /// Removes all mappings not satisfying the given predicate. |
| 410 | /// |
| 411 | /// Also removes any expired mappings. |
| 412 | pub fn retain<F>(&mut self, mut f: F) |
| 413 | where F: FnMut(K::Strong, V::Strong) -> bool |
| 414 | { |
| 415 | for i in 0 .. self.capacity() { |
| 416 | let remove = match self.inner.buckets[i] { |
| 417 | None => false, |
| 418 | Some(ref bucket) => |
| 419 | match (bucket.0.view(), bucket.1.view()) { |
| 420 | (Some(key), Some(value)) => !f(key, value), |
| 421 | _ => true, |
| 422 | } |
| 423 | }; |
| 424 | |
| 425 | if remove { |
| 426 | self.inner.remove_index(i); |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | /// Is this map a submap of the other, using the given value comparison. |
| 432 | /// |
| 433 | /// In particular, all the keys of `self` must be in `other` and the values must compare |
| 434 | /// `true` with `value_equal`. |
| 435 | pub fn is_submap_with<F, S1, V1>(&self, other: &WeakWeakHashMap<K, V1, S1>, |
| 436 | mut value_equal: F) -> bool |
| 437 | where V1: WeakElement, |
| 438 | F: FnMut(V::Strong, V1::Strong) -> bool, |
| 439 | S1: BuildHasher |
| 440 | { |
| 441 | for (key, value1) in self { |
| 442 | if let Some(value2) = K::with_key(&key, |k| other.get(k)) { |
| 443 | if !value_equal(value1, value2) { |
| 444 | return false; |
| 445 | } |
| 446 | } else { |
| 447 | return false; |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | true |
| 452 | } |
| 453 | |
| 454 | /// Is `self` a submap of `other`? |
| 455 | pub fn is_submap<V1, S1>(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool |
| 456 | where V1: WeakElement, |
| 457 | V::Strong: PartialEq<V1::Strong>, |
| 458 | S1: BuildHasher |
| 459 | { |
| 460 | self.is_submap_with(other, |v, v1| v == v1) |
| 461 | } |
| 462 | |
| 463 | /// Are the keys of `self` a subset of the keys of `other`? |
| 464 | pub fn domain_is_subset<V1, S1>(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool |
| 465 | where V1: WeakElement, |
| 466 | S1: BuildHasher |
| 467 | { |
| 468 | self.is_submap_with(other, |_, _| true) |
| 469 | } |
| 470 | |
| 471 | fn hash<Q>(&self, key: &Q) -> HashCode |
| 472 | where Q: ?Sized + Hash, |
| 473 | K::Key: Borrow<Q> |
| 474 | { |
| 475 | let mut hasher = self.hash_builder.build_hasher(); |
| 476 | key.hash(&mut hasher); |
| 477 | HashCode(hasher.finish()) |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | impl<K, V, V1, S, S1> PartialEq<WeakWeakHashMap<K, V1, S1>> for WeakWeakHashMap<K, V, S> |
| 482 | where K: WeakKey, |
| 483 | V: WeakElement, |
| 484 | V1: WeakElement, |
| 485 | V::Strong: PartialEq<V1::Strong>, |
| 486 | S: BuildHasher, |
| 487 | S1: BuildHasher |
| 488 | { |
| 489 | fn eq(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool { |
| 490 | self.is_submap(other) && other.domain_is_subset(self) |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | impl<K: WeakKey, V: WeakElement, S: BuildHasher> Eq for WeakWeakHashMap<K, V, S> |
| 495 | where V::Strong: Eq |
| 496 | { } |
| 497 | |
| 498 | impl<K: WeakKey, V: WeakElement, S: BuildHasher + Default> Default for WeakWeakHashMap<K, V, S> { |
| 499 | fn default() -> Self { |
| 500 | WeakWeakHashMap::with_hasher(Default::default()) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | impl<K, V, S> ::std::iter::FromIterator<(K::Strong, V::Strong)> for WeakWeakHashMap<K, V, S> |
| 505 | where K: WeakKey, |
| 506 | V: WeakElement, |
| 507 | S: BuildHasher + Default |
| 508 | { |
| 509 | fn from_iter<T: IntoIterator<Item=(K::Strong, V::Strong)>>(iter: T) -> Self { |
| 510 | let mut result = WeakWeakHashMap::with_hasher(Default::default()); |
| 511 | result.extend(iter); |
| 512 | result |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | impl<K, V, S> Extend<(K::Strong, V::Strong)> for WeakWeakHashMap<K, V, S> |
| 517 | where K: WeakKey, |
| 518 | V: WeakElement, |
| 519 | S: BuildHasher |
| 520 | { |
| 521 | fn extend<T: IntoIterator<Item=(K::Strong, V::Strong)>>(&mut self, iter: T) { |
| 522 | for (key, value) in iter { |
| 523 | self.insert(key, value); |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | enum BucketStatus<V: WeakElement> { |
| 529 | Unoccupied, |
| 530 | MatchesKey(V::Strong), |
| 531 | ProbeDistance(usize), |
| 532 | } |
| 533 | |
| 534 | impl<'a, K: WeakKey, V: WeakElement> InnerEntry<'a, K, V> { |
| 535 | // Gets the status of the current bucket. |
| 536 | fn bucket_status(&self) -> BucketStatus<V> { |
| 537 | match &self.map.buckets[self.pos] { |
| 538 | Some(bucket) => { |
| 539 | if bucket.2 == self.hash_code { |
| 540 | if let (Some(key), Some(value)) = (bucket.0.view(), bucket.1.view()) { |
| 541 | if K::with_key(&self.key, |k1| K::with_key(&key, |k2| k1 == k2)) { |
| 542 | return BucketStatus::MatchesKey(value); |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | let dist = self.probe_distance(self.pos, |
| 548 | self.which_bucket(bucket.2)); |
| 549 | BucketStatus::ProbeDistance(dist) |
| 550 | }, |
| 551 | None => BucketStatus::Unoccupied, |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | impl<'a, K: WeakKey, V: WeakElement> Entry<'a, K, V> { |
| 557 | /// Ensures a value is in the entry by inserting a default value |
| 558 | /// if empty, and returns a mutable reference to the value in the |
| 559 | /// entry. |
| 560 | pub fn or_insert(self, default: V::Strong) -> V::Strong { |
| 561 | self.or_insert_with(|| default) |
| 562 | } |
| 563 | |
| 564 | /// Ensures a value is in the entry by inserting the result of the |
| 565 | /// default function if empty, and returns a mutable reference to |
| 566 | /// the value in the entry. |
| 567 | pub fn or_insert_with<F: FnOnce() -> V::Strong>(self, default: F) -> V::Strong { |
| 568 | match self { |
| 569 | Entry::Occupied(occupied) => occupied.get_strong(), |
| 570 | Entry::Vacant(vacant) => vacant.insert(default()), |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | /// Returns a reference to this entry's key. |
| 575 | pub fn key(&self) -> &K::Strong { |
| 576 | match *self { |
| 577 | Entry::Occupied(ref occupied) => occupied.key(), |
| 578 | Entry::Vacant(ref vacant) => vacant.key(), |
| 579 | } |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | impl<'a, K: WeakKey, V: WeakElement> OccupiedEntry<'a, K, V> { |
| 584 | /// Gets a reference to the key held by the entry. |
| 585 | pub fn key(&self) -> &K::Strong { |
| 586 | &self.inner.key |
| 587 | } |
| 588 | |
| 589 | /// Takes ownership of the key and value from the map. |
| 590 | pub fn remove_entry(self) -> (K::Strong, V::Strong) { |
| 591 | let (_, w_value, _) = self.inner.map.buckets[self.inner.pos].take().unwrap(); |
| 592 | let value = w_value.view().unwrap(); |
| 593 | self.inner.map.remove_index(self.inner.pos); |
| 594 | (self.inner.key, value) |
| 595 | } |
| 596 | |
| 597 | /// Gets a reference to the value in the entry. |
| 598 | pub fn get(&self) -> &V::Strong { |
| 599 | &self.value |
| 600 | } |
| 601 | |
| 602 | /// Gets a clone of the reference to the value in the entry. |
| 603 | pub fn get_strong(&self) -> V::Strong { |
| 604 | V::clone(&self.value) |
| 605 | } |
| 606 | |
| 607 | /// Replaces the value in the entry with the given value. |
| 608 | pub fn insert(&mut self, value: V::Strong) -> V::Strong { |
| 609 | self.inner.map.buckets[self.inner.pos].as_mut().unwrap().1 = V::new(&value); |
| 610 | mem::replace(&mut self.value, value) |
| 611 | } |
| 612 | |
| 613 | /// Removes the entry, returning the value. |
| 614 | pub fn remove(self) -> V::Strong { |
| 615 | self.remove_entry().1 |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | impl<'a, K: WeakKey, V: WeakElement> VacantEntry<'a, K, V> { |
| 620 | /// Gets a reference to the key that would be used when inserting a |
| 621 | /// value through the `VacantEntry`. |
| 622 | pub fn key(&self) -> &K::Strong { |
| 623 | &self.inner.key |
| 624 | } |
| 625 | |
| 626 | /// Returns ownership of the key. |
| 627 | pub fn into_key(self) -> K::Strong { |
| 628 | self.inner.key |
| 629 | } |
| 630 | |
| 631 | /// Inserts the key and value into the map, returning the same value. |
| 632 | pub fn insert(self, value: V::Strong) -> V::Strong { |
| 633 | let old_bucket = mem::replace( |
| 634 | &mut self.inner.map.buckets[self.inner.pos], |
| 635 | Some((K::new(&self.inner.key), V::new(&value), self.inner.hash_code))); |
| 636 | |
| 637 | if let Some(full_bucket) = old_bucket { |
| 638 | let next_bucket = self.next_bucket(self.inner.pos); |
| 639 | self.inner.map.steal(next_bucket, full_bucket); |
| 640 | } |
| 641 | |
| 642 | self.inner.map.len += 1; |
| 643 | |
| 644 | value |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | impl<K: WeakKey, V: WeakElement> WeakWeakInnerMap<K, V> { |
| 649 | // Steals buckets starting at `pos`, replacing them with `bucket`. |
| 650 | fn steal(&mut self, mut pos: usize, mut bucket: FullBucket<K, V>) { |
| 651 | let mut my_dist = self.probe_distance(pos, self.which_bucket(bucket.2)); |
| 652 | |
| 653 | while let Some(hash_code) = self.buckets[pos].as_ref().and_then( |
| 654 | |bucket| if bucket.0.is_expired() || bucket.1.is_expired() { |
| 655 | None |
| 656 | } else { |
| 657 | Some(bucket.2) |
| 658 | }) { |
| 659 | |
| 660 | let victim_dist = self.probe_distance(pos, self.which_bucket(hash_code)); |
| 661 | |
| 662 | if my_dist > victim_dist { |
| 663 | mem::swap(self.buckets[pos].as_mut().unwrap(), &mut bucket); |
| 664 | my_dist = victim_dist; |
| 665 | } |
| 666 | |
| 667 | pos = self.next_bucket(pos); |
| 668 | my_dist += 1; |
| 669 | } |
| 670 | |
| 671 | self.buckets[pos] = Some(bucket); |
| 672 | } |
| 673 | |
| 674 | /// Removes the element at `dst`, shifting if necessary to preserve invariants. |
| 675 | fn remove_index(&mut self, mut dst: usize) { |
| 676 | let mut src = self.next_bucket(dst); |
| 677 | |
| 678 | // We are going to remove the buckets in the range [dst, src) |
| 679 | |
| 680 | loop { |
| 681 | let hash_code_option = self.buckets[src].as_ref().map(|tup| tup.2); |
| 682 | |
| 683 | if let Some(hash_code) = hash_code_option { |
| 684 | let goal_pos = self.which_bucket(hash_code); |
| 685 | let dist = self.probe_distance(src, goal_pos); |
| 686 | if dist == 0 { break; } |
| 687 | |
| 688 | let expired = { |
| 689 | let bucket = self.buckets[src].as_ref().unwrap(); |
| 690 | bucket.0.is_expired() || bucket.1.is_expired() |
| 691 | }; |
| 692 | |
| 693 | if !expired { |
| 694 | if in_interval(dst, goal_pos, src) { |
| 695 | self.erase_range(dst, goal_pos); |
| 696 | self.buckets[goal_pos] = self.buckets[src].take(); |
| 697 | dst = self.next_bucket(goal_pos); |
| 698 | } else { |
| 699 | self.buckets[dst] = self.buckets[src].take(); |
| 700 | dst = self.next_bucket(dst); |
| 701 | } |
| 702 | } |
| 703 | } else { |
| 704 | break; |
| 705 | } |
| 706 | |
| 707 | src = self.next_bucket(src); |
| 708 | } |
| 709 | |
| 710 | self.erase_range(dst, src); |
| 711 | } |
| 712 | |
| 713 | /// Erases the (presumably expired, but not empty) elements in [start, limit). |
| 714 | fn erase_range(&mut self, mut start: usize, limit: usize) |
| 715 | { |
| 716 | while start != limit { |
| 717 | self.buckets[start] = None; |
| 718 | self.len -= 1; |
| 719 | start = self.next_bucket(start); |
| 720 | } |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | // Is value in [start, limit) modulo capacity? |
| 725 | fn in_interval(start: usize, value: usize, limit: usize) -> bool |
| 726 | { |
| 727 | if start <= limit { |
| 728 | start <= value && value < limit |
| 729 | } else { |
| 730 | start <= value || value < limit |
| 731 | } |
| 732 | } |
| 733 | |
| 734 | // Helper trait for computing with indices modulo capacity. |
| 735 | trait ModuloCapacity { |
| 736 | fn capacity(&self) -> usize; |
| 737 | |
| 738 | fn probe_distance(&self, actual: usize, ideal: usize) -> usize { |
| 739 | if actual >= ideal { |
| 740 | actual - ideal |
| 741 | } else { |
| 742 | actual + self.capacity() - ideal |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | fn next_bucket(&self, pos: usize) -> usize { |
| 747 | assert_ne!( self.capacity(), 0 ); |
| 748 | (pos + 1) % self.capacity() |
| 749 | } |
| 750 | |
| 751 | fn which_bucket(&self, hash_code: HashCode) -> usize { |
| 752 | assert_ne!( self.capacity(), 0 ); |
| 753 | (hash_code.0 as usize) % self.capacity() |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | impl<K, V> ModuloCapacity for WeakWeakInnerMap<K, V> { |
| 758 | fn capacity(&self) -> usize { |
| 759 | self.buckets.len() |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | impl<K, V, S> ModuloCapacity for WeakWeakHashMap<K, V, S> { |
| 764 | fn capacity(&self) -> usize { |
| 765 | self.inner.capacity() |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | impl<'a, K: WeakKey, V: WeakElement> ModuloCapacity for InnerEntry<'a, K, V> { |
| 770 | fn capacity(&self) -> usize { |
| 771 | self.map.capacity() |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | impl<'a, K: WeakKey, V: WeakElement> ModuloCapacity for OccupiedEntry<'a, K, V> { |
| 776 | fn capacity(&self) -> usize { |
| 777 | self.inner.capacity() |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | impl<'a, K: WeakKey, V: WeakElement> ModuloCapacity for VacantEntry<'a, K, V> { |
| 782 | fn capacity(&self) -> usize { |
| 783 | self.inner.capacity() |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | impl<K, V> Debug for WeakWeakInnerMap<K, V> |
| 788 | where K: WeakElement, |
| 789 | K::Strong: Debug, |
| 790 | V: WeakElement, |
| 791 | V::Strong: Debug |
| 792 | { |
| 793 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 794 | write!(f, "{{ ")?; |
| 795 | for (i, bucket) in self.buckets.iter().enumerate() { |
| 796 | if let Some((k, v, _)) = bucket { |
| 797 | write!(f, "[{}] {:?} => {:?}, ", i, k.view(), v.view())?; |
| 798 | } |
| 799 | } |
| 800 | write!(f, "}}") |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | impl<K: WeakElement, V: WeakElement, S> Debug for WeakWeakHashMap<K, V, S> |
| 805 | where K::Strong: Debug, |
| 806 | V::Strong: Debug |
| 807 | { |
| 808 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 809 | self.inner.fmt(f) |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | impl<'a, K: WeakKey, V: WeakElement> Debug for Entry<'a, K, V> |
| 814 | where K::Strong: Debug, |
| 815 | V::Strong: Debug |
| 816 | { |
| 817 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 818 | match *self { |
| 819 | Entry::Occupied(ref e) => e.fmt(f), |
| 820 | Entry::Vacant(ref e) => e.fmt(f), |
| 821 | } |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | impl<'a, K: WeakKey, V: WeakElement> Debug for OccupiedEntry<'a, K, V> |
| 826 | where K::Strong: Debug, |
| 827 | V::Strong: Debug |
| 828 | { |
| 829 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 830 | self.inner.fmt(f) |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | impl<'a, K: WeakKey, V: WeakElement> Debug for VacantEntry<'a, K, V> |
| 835 | where K::Strong: Debug, |
| 836 | V::Strong: Debug |
| 837 | { |
| 838 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 839 | self.inner.fmt(f) |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | impl<'a, K: WeakKey, V: WeakElement> Debug for InnerEntry<'a, K, V> |
| 844 | where K::Strong: Debug, |
| 845 | V::Strong: Debug |
| 846 | { |
| 847 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 848 | write!(f, "InnerEntry {{ pos = {}, buckets = {:?} }}", self.pos, self.map) |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | impl<K: WeakElement, V: WeakElement, S> IntoIterator for WeakWeakHashMap<K, V, S> { |
| 853 | type Item = (K::Strong, V::Strong); |
| 854 | type IntoIter = IntoIter<K, V>; |
| 855 | |
| 856 | fn into_iter(self) -> Self::IntoIter { |
| 857 | IntoIter { |
| 858 | size: self.inner.len, |
| 859 | base: self.inner.buckets.into_vec().into_iter(), |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | impl<'a, K: WeakElement, V: WeakElement, S> IntoIterator for &'a WeakWeakHashMap<K, V, S> { |
| 865 | type Item = (K::Strong, V::Strong); |
| 866 | type IntoIter = Iter<'a, K, V>; |
| 867 | |
| 868 | fn into_iter(self) -> Self::IntoIter { |
| 869 | Iter { |
| 870 | base: self.inner.buckets.iter(), |
| 871 | size: self.inner.len, |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | impl<K: WeakElement, V: WeakElement, S> WeakWeakHashMap<K, V, S> { |
| 877 | /// Gets an iterator over the keys and values. |
| 878 | pub fn iter(&self) -> Iter<K, V> { |
| 879 | self.into_iter() |
| 880 | } |
| 881 | |
| 882 | /// Gets an iterator over the keys. |
| 883 | pub fn keys(&self) -> Keys<K, V> { |
| 884 | Keys(self.iter()) |
| 885 | } |
| 886 | |
| 887 | /// Gets an iterator over the values. |
| 888 | pub fn values(&self) -> Values<K, V> { |
| 889 | Values(self.iter()) |
| 890 | } |
| 891 | |
| 892 | /// Gets a draining iterator, which removes all the values but retains the storage. |
| 893 | pub fn drain(&mut self) -> Drain<K, V> { |
| 894 | let old_len = self.inner.len; |
| 895 | self.inner.len = 0; |
| 896 | Drain { |
| 897 | base: self.inner.buckets.iter_mut(), |
| 898 | size: old_len, |
| 899 | } |
| 900 | } |
| 901 | } |
| 902 | |