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