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