-
Notifications
You must be signed in to change notification settings - Fork 48
/
map.rs
2174 lines (1954 loc) · 90.3 KB
/
map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::iter::*;
use crate::node::*;
use crate::raw::*;
use crossbeam_epoch::{self as epoch, Atomic, Guard, Owned, Shared};
use std::borrow::Borrow;
use std::fmt::{self, Debug, Formatter};
use std::hash::{BuildHasher, Hash, Hasher};
use std::iter::FromIterator;
use std::sync::{
atomic::{AtomicIsize, AtomicUsize, Ordering},
Once,
};
const ISIZE_BITS: usize = core::mem::size_of::<isize>() * 8;
/// The largest possible table capacity. This value must be
/// exactly 1<<30 to stay within Java array allocation and indexing
/// bounds for power of two table sizes, and is further required
/// because the top two bits of 32bit hash fields are used for
/// control purposes.
const MAXIMUM_CAPACITY: usize = 1 << 30; // TODO: use ISIZE_BITS
/// The default initial table capacity. Must be a power of 2
/// (i.e., at least 1) and at most `MAXIMUM_CAPACITY`.
const DEFAULT_CAPACITY: usize = 16;
/// Minimum number of rebinnings per transfer step. Ranges are
/// subdivided to allow multiple resizer threads. This value
/// serves as a lower bound to avoid resizers encountering
/// excessive memory contention. The value should be at least
/// `DEFAULT_CAPACITY`.
const MIN_TRANSFER_STRIDE: isize = 16;
/// The number of bits used for generation stamp in `size_ctl`.
/// Must be at least 6 for 32bit arrays.
const RESIZE_STAMP_BITS: usize = ISIZE_BITS / 2;
/// The maximum number of threads that can help resize.
/// Must fit in `32 - RESIZE_STAMP_BITS` bits for 32 bit architectures
/// and `64 - RESIZE_STAMP_BITS` bits for 64 bit architectures
const MAX_RESIZERS: isize = (1 << (ISIZE_BITS - RESIZE_STAMP_BITS)) - 1;
/// The bit shift for recording size stamp in `size_ctl`.
const RESIZE_STAMP_SHIFT: usize = ISIZE_BITS - RESIZE_STAMP_BITS;
static NCPU_INITIALIZER: Once = Once::new();
static NCPU: AtomicUsize = AtomicUsize::new(0);
macro_rules! load_factor {
($n: expr) => {
// ¾ n = n - n/4 = n - (n >> 2)
$n - ($n >> 2)
};
}
/// A concurrent hash table.
///
/// See the [crate-level documentation](index.html) for details.
pub struct HashMap<K: 'static, V: 'static, S = crate::DefaultHashBuilder> {
/// The array of bins. Lazily initialized upon first insertion.
/// Size is always a power of two. Accessed directly by iterators.
table: Atomic<Table<K, V>>,
/// The next table to use; non-null only while resizing.
next_table: Atomic<Table<K, V>>,
/// The next table index (plus one) to split while resizing.
transfer_index: AtomicIsize,
count: AtomicUsize,
/// Table initialization and resizing control. When negative, the
/// table is being initialized or resized: -1 for initialization,
/// else -(1 + the number of active resizing threads). Otherwise,
/// when table is null, holds the initial table size to use upon
/// creation, or 0 for default. After initialization, holds the
/// next element count value upon which to resize the table.
size_ctl: AtomicIsize,
/// Collector that all `Guard` references used for operations on this map must be tied to. It
/// is important that they all assocate with the _same_ `Collector`, otherwise you end up with
/// unsoundness as described in https://github.com/jonhoo/flurry/issues/46. Specifically, a
/// user can do:
///
/// ```rust,ignore
/// # // this test should be should_panic, not ignore, but that makes ASAN crash..?
/// # use flurry::HashMap;
/// # use crossbeam_epoch;
/// let map: HashMap<_, _> = HashMap::default();
/// map.insert(42, String::from("hello"), &crossbeam_epoch::pin());
///
/// let evil = crossbeam_epoch::Collector::new();
/// let evil = evil.register();
/// let guard = evil.pin();
/// let oops = map.get(&42, &guard);
///
/// map.remove(&42, &crossbeam_epoch::pin());
/// // at this point, the default collector is allowed to free `"hello"`
/// // since no-one has the global epoch pinned as far as it is aware.
/// // `oops` is tied to the lifetime of a Guard that is not a part of
/// // the same epoch group, and so can now be dangling.
/// // but we can still access it!
/// assert_eq!(oops.unwrap(), "hello");
/// ```
///
/// We avoid that by checking that every external guard that is passed in is associated with
/// the `Collector` that was specified when the map was created (which may be the global
/// collector).
///
/// Note also that the fact that this can be a global collector is what necessitates the
/// `'static` bounds on `K` and `V`. Since deallocation can be deferred arbitrarily, it is not
/// okay for us to take a `K` or `V` with a limited lifetime, since we may drop it far after
/// that lifetime has passed.
///
/// One possibility is to never use the global allocator, and instead _always_ create and use
/// our own `Collector`. If we did that, then we could accept non-`'static` keys and values since
/// the destruction of the collector would ensure that that all deferred destructors are run.
/// It would, sadly, mean that we don't get to share a collector with other things that use
/// `crossbeam-epoch` though. For more on this (and a cool optimization), see:
/// https://github.com/crossbeam-rs/crossbeam/blob/ebecb82c740a1b3d9d10f235387848f7e3fa9c68/crossbeam-skiplist/src/base.rs#L308-L319
collector: epoch::Collector,
build_hasher: S,
}
#[cfg(test)]
#[test]
#[should_panic]
fn disallow_evil() {
let map: HashMap<_, _> = HashMap::default();
map.insert(42, String::from("hello"), &crossbeam_epoch::pin());
let evil = crossbeam_epoch::Collector::new();
let evil = evil.register();
let guard = evil.pin();
let oops = map.get(&42, &guard);
map.remove(&42, &crossbeam_epoch::pin());
// at this point, the default collector is allowed to free `"hello"`
// since no-one has the global epoch pinned as far as it is aware.
// `oops` is tied to the lifetime of a Guard that is not a part of
// the same epoch group, and so can now be dangling.
// but we can still access it!
assert_eq!(oops.unwrap(), "hello");
}
impl<K, V, S> Default for HashMap<K, V, S>
where
K: Sync + Send + Clone + Hash + Eq,
V: Sync + Send,
S: BuildHasher + Default,
{
fn default() -> Self {
Self::with_hasher(S::default())
}
}
impl<K, V> HashMap<K, V, crate::DefaultHashBuilder>
where
K: Sync + Send + Clone + Hash + Eq,
V: Sync + Send,
{
/// Creates a new, empty map with the default initial table size (16).
pub fn new() -> Self {
Self::default()
}
/// Creates a new, empty map with an initial table size accommodating the specified number of
/// elements without the need to dynamically resize.
pub fn with_capacity(n: usize) -> Self {
Self::with_capacity_and_hasher(n, crate::DefaultHashBuilder::default())
}
}
impl<K, V, S> HashMap<K, V, S>
where
K: Sync + Send + Clone + Hash + Eq,
V: Sync + Send,
S: BuildHasher,
{
/// Creates an empty map which will use `hash_builder` to hash keys.
///
/// The created map has the default initial capacity.
///
/// Warning: `hash_builder` is normally randomly generated, and is designed to
/// allow the map to be resistant to attacks that cause many collisions and
/// very poor performance. Setting it manually using this
/// function can expose a DoS attack vector.
pub fn with_hasher(hash_builder: S) -> Self {
Self {
table: Atomic::null(),
next_table: Atomic::null(),
transfer_index: AtomicIsize::new(0),
count: AtomicUsize::new(0),
size_ctl: AtomicIsize::new(0),
build_hasher: hash_builder,
collector: epoch::default_collector().clone(),
}
}
/*
NOTE: This method is intentionally left out atm as it is a potentially large foot-gun.
See https://github.com/jonhoo/flurry/pull/49#issuecomment-580514518.
*/
/*
/// Associate a custom [`epoch::Collector`] with this map.
///
/// By default, the global collector is used. With this method you can use a different
/// collector instead. This may be desireable if you want more control over when and how memory
/// reclamation happens.
///
/// Note that _all_ `Guard` references provided to access the returned map _must_ be
/// constructed using guards produced by `collector`. You can use [`HashMap::register`] to get
/// a thread-local handle to the collector that then lets you construct an [`epoch::Guard`].
pub fn with_collector(mut self, collector: epoch::Collector) -> Self {
self.collector = collector;
self
}
/// Allocate a thread-local handle to the [`epoch::Collector`] associated with this map.
///
/// You can use the returned handle to produce [`epoch::Guard`] references.
pub fn register(&self) -> epoch::LocalHandle {
self.collector.register()
}
*/
/// Pin a `Guard` for use with this map.
///
/// Keep in mind that for as long as you hold onto this `Guard`, you are preventing the
/// collection of garbage generated by the map.
pub fn guard(&self) -> epoch::Guard {
self.collector.register().pin()
}
#[inline]
fn check_guard(&self, guard: &Guard) {
// guard.collector() may be `None` if it is unprotected
if let Some(c) = guard.collector() {
assert_eq!(c, &self.collector);
}
}
/// Creates an empty map with the specified `capacity`, using `hash_builder` to hash the keys.
///
/// The map will be sized to accommodate `capacity` elements with a low chance of reallocating
/// (assuming uniformly distributed hashes). If `capacity` is 0, the call will not allocate,
/// and is equivalent to [`HashMap::new`].
///
/// Warning: `hash_builder` is normally randomly generated, and is designed to allow the map
/// to be resistant to attacks that cause many collisions and very poor performance.
/// Setting it manually using this function can expose a DoS attack vector.
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
if capacity == 0 {
return Self::with_hasher(hash_builder);
}
let map = Self::with_hasher(hash_builder);
// safety: we are creating this map, so no other thread can access it,
// while we are initializing it.
map.try_presize(capacity, unsafe { epoch::unprotected() });
map
}
}
impl<K, V, S> HashMap<K, V, S>
where
K: Sync + Send + Clone + Hash + Eq,
V: Sync + Send,
S: BuildHasher,
{
fn hash<Q: ?Sized + Hash>(&self, key: &Q) -> u64 {
let mut h = self.build_hasher.build_hasher();
key.hash(&mut h);
h.finish()
}
#[inline]
/// Tests if `key` is a key in this table.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form must match those for the key type.
pub fn contains_key<Q>(&self, key: &Q, guard: &Guard) -> bool
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.check_guard(guard);
self.get(key, &guard).is_some()
}
fn get_node<'g, Q>(&'g self, key: &Q, guard: &'g Guard) -> Option<&'g Node<K, V>>
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
let table = self.table.load(Ordering::SeqCst, guard);
if table.is_null() {
return None;
}
// safety: we loaded the table while epoch was pinned. table won't be deallocated until
// next epoch at the earliest.
let table = unsafe { table.deref() };
if table.is_empty() {
return None;
}
let h = self.hash(key);
let bini = table.bini(h);
let bin = table.bin(bini, guard);
if bin.is_null() {
return None;
}
// safety: bin is a valid pointer.
//
// there are two cases when a bin pointer is invalidated:
//
// 1. if the table was resized, bin is a move entry, and the resize has completed. in
// that case, the table (and all its heads) will be dropped in the next epoch
// following that.
// 2. if the table is being resized, bin may be swapped with a move entry. the old bin
// will then be dropped in the following epoch after that happens.
//
// in both cases, we held the guard when we got the reference to the bin. if any such
// swap happened, it must have happened _after_ we read. since we did the read while
// pinning the epoch, the drop must happen in the _next_ epoch (i.e., the one that we
// are holding up by holding on to our guard).
let node = unsafe { bin.deref() }.find(h, key, guard);
if node.is_null() {
return None;
}
// safety: we read the bin while pinning the epoch. a bin will never be dropped until the
// next epoch after it is removed. since it wasn't removed, and the epoch was pinned, that
// cannot be until after we drop our guard.
let node = unsafe { node.deref() };
Some(
node.as_node()
.expect("`BinEntry::find` should always return a Node"),
)
}
/// Returns the value to which `key` is mapped.
///
/// Returns `None` if this map contains no mapping for the key.
///
/// To obtain a `Guard`, use [`HashMap::guard`].
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form must match those for the key type.
// TODO: implement a guard API of our own
pub fn get<'g, Q>(&'g self, key: &Q, guard: &'g Guard) -> Option<&'g V>
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.check_guard(guard);
let node = self.get_node(key, guard)?;
let v = node.value.load(Ordering::SeqCst, guard);
assert!(!v.is_null());
// safety: the lifetime of the reference is bound to the guard
// supplied which means that the memory will not be modified
// until at least after the guard goes out of scope
unsafe { v.as_ref() }
}
#[inline]
/// Obtains the value to which `key` is mapped and passes it through the closure `then`.
///
/// Returns `None` if this map contains no mapping for `key`.
///
/// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed
/// form must match those for the key type.
pub fn get_and<Q, R, F>(&self, key: &Q, then: F, guard: &Guard) -> Option<R>
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
F: FnOnce(&V) -> R,
{
self.get(key, guard).map(then)
}
/// Returns the key-value pair corresponding to `key`.
///
/// Returns `None` if this map contains no mapping for `key`.
///
/// The supplied `key` may be any borrowed form of the
/// map's key type, but `Hash` and `Eq` on the borrowed form
/// must match those for the key type.
pub fn get_key_value<'g, Q>(&'g self, key: &Q, guard: &'g Guard) -> Option<(&'g K, &'g V)>
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
{
self.check_guard(guard);
let node = self.get_node(key, guard)?;
let v = node.value.load(Ordering::SeqCst, guard);
assert!(!v.is_null());
// safety: the lifetime of the reference is bound to the guard
// supplied which means that the memory will not be modified
// until at least after the guard goes out of scope
unsafe { v.as_ref() }.map(|v| (&node.key, v))
}
fn init_table<'g>(&'g self, guard: &'g Guard) -> Shared<'g, Table<K, V>> {
loop {
let table = self.table.load(Ordering::SeqCst, guard);
// safety: we loaded the table while epoch was pinned. table won't be deallocated until
// next epoch at the earliest.
if !table.is_null() && !unsafe { table.deref() }.is_empty() {
break table;
}
// try to allocate the table
let mut sc = self.size_ctl.load(Ordering::SeqCst);
if sc < 0 {
// we lost the initialization race; just spin
std::thread::yield_now();
continue;
}
if self.size_ctl.compare_and_swap(sc, -1, Ordering::SeqCst) == sc {
// we get to do it!
let mut table = self.table.load(Ordering::SeqCst, guard);
// safety: we loaded the table while epoch was pinned. table won't be deallocated
// until next epoch at the earliest.
if table.is_null() || unsafe { table.deref() }.is_empty() {
let n = if sc > 0 {
sc as usize
} else {
DEFAULT_CAPACITY
};
let new_table = Owned::new(Table::new(n));
table = new_table.into_shared(guard);
self.table.store(table, Ordering::SeqCst);
sc = load_factor!(n as isize)
}
self.size_ctl.store(sc, Ordering::SeqCst);
break table;
}
}
}
#[inline]
/// Maps `key` to `value` in this table.
///
/// The value can be retrieved by calling [`HashMap::get`] with a key that is equal to the original key.
pub fn insert<'g>(&'g self, key: K, value: V, guard: &'g Guard) -> Option<&'g V> {
self.check_guard(guard);
self.put(key, value, false, guard)
}
/// Removes all entries from this map.
pub fn clear(&self, guard: &Guard) {
// Negative number of deletions
let mut delta = 0;
let mut idx = 0usize;
let mut table = self.table.load(Ordering::SeqCst, guard);
// Safety: self.table is a valid pointer because we checked it above.
while !table.is_null() && idx < unsafe { table.deref() }.len() {
let tab = unsafe { table.deref() };
let raw_node = tab.bin(idx, guard);
if raw_node.is_null() {
idx += 1;
continue;
}
// Safety: node is a valid pointer because we checked
// it in the above if stmt.
match unsafe { raw_node.deref() } {
BinEntry::Moved(next_table) => {
table = self.help_transfer(table, *next_table, guard);
// start from the first bin again in the new table
idx = 0;
}
BinEntry::Node(ref node) => {
let head_lock = node.lock.lock();
// need to check that this is _still_ the head
let current_head = tab.bin(idx, guard);
if current_head != raw_node {
// nope -- try the bin again
continue;
}
// we now own the bin
// unlink it from the map to prevent others from entering it
tab.store_bin(idx, Shared::null());
// next, walk the nodes of the bin and free the nodes and their values as we go
// note that we do not free the head node yet, since we're holding the lock it contains
let mut p = node.next.load(Ordering::SeqCst, guard);
while !p.is_null() {
delta -= 1;
p = {
// safety: we loaded p under guard, and guard is still pinned, so p has not been dropped.
let node = unsafe { p.deref() }
.as_node()
.expect("entry following Node should always be a Node");
let next = node.next.load(Ordering::SeqCst, guard);
let value = node.value.load(Ordering::SeqCst, guard);
// NOTE: do not use the reference in `node` after this point!
// free the node's value
// safety: any thread that sees this p's value must have read the bin before we stored null
// into it above. it must also have pinned the epoch before that time. therefore, the
// defer_destroy below won't be executed until that thread's guard is dropped, at which
// point it holds no outstanding references to the value anyway.
unsafe { guard.defer_destroy(value) };
// free the bin entry itself
// safety: same argument as for value above.
unsafe { guard.defer_destroy(p) };
next
};
}
drop(head_lock);
// finally, we can drop the head node and its value
let value = node.value.load(Ordering::SeqCst, guard);
// NOTE: do not use the reference in `node` after this point!
// safety: same as the argument for being allowed to free the nodes beyond the head above
unsafe { guard.defer_destroy(value) };
unsafe { guard.defer_destroy(raw_node) };
delta -= 1;
idx += 1;
}
};
}
if delta != 0 {
self.add_count(delta, None, guard);
}
}
fn put<'g>(
&'g self,
key: K,
value: V,
no_replacement: bool,
guard: &'g Guard,
) -> Option<&'g V> {
let h = self.hash(&key);
let mut table = self.table.load(Ordering::SeqCst, guard);
let mut node = Owned::new(BinEntry::Node(Node {
key,
value: Atomic::new(value),
hash: h,
next: Atomic::null(),
lock: parking_lot::Mutex::new(()),
}));
loop {
// safety: see argument below for !is_null case
if table.is_null() || unsafe { table.deref() }.is_empty() {
table = self.init_table(guard);
continue;
}
// safety: table is a valid pointer.
//
// we are in one of three cases:
//
// 1. if table is the one we read before the loop, then we read it while holding the
// guard, so it won't be dropped until after we drop that guard b/c the drop logic
// only queues a drop for the next epoch after removing the table.
//
// 2. if table is read by init_table, then either we did a load, and the argument is
// as for point 1. or, we allocated a table, in which case the earliest it can be
// deallocated is in the next epoch. we are holding up the epoch by holding the
// guard, so this deref is safe.
//
// 3. if table is set by a Moved node (below) through help_transfer, it will _either_
// keep using `table` (which is fine by 1. and 2.), or use the `next_table` raw
// pointer from inside the Moved. to see that if a Moved(t) is _read_, then t must
// still be valid, see the safety comment on BinEntry::Moved.
let t = unsafe { table.deref() };
let bini = t.bini(h);
let mut bin = t.bin(bini, guard);
if bin.is_null() {
// fast path -- bin is empty so stick us at the front
match t.cas_bin(bini, bin, node, guard) {
Ok(_old_null_ptr) => {
self.add_count(1, Some(0), guard);
guard.flush();
return None;
}
Err(changed) => {
assert!(!changed.current.is_null());
node = changed.new;
bin = changed.current;
}
}
}
// slow path -- bin is non-empty
// safety: bin is a valid pointer.
//
// there are two cases when a bin pointer is invalidated:
//
// 1. if the table was resized, bin is a move entry, and the resize has completed. in
// that case, the table (and all its heads) will be dropped in the next epoch
// following that.
// 2. if the table is being resized, bin may be swapped with a move entry. the old bin
// will then be dropped in the following epoch after that happens.
//
// in both cases, we held the guard when we got the reference to the bin. if any such
// swap happened, it must have happened _after_ we read. since we did the read while
// pinning the epoch, the drop must happen in the _next_ epoch (i.e., the one that we
// are holding up by holding on to our guard).
let key = &node.as_node().unwrap().key;
match *unsafe { bin.deref() } {
BinEntry::Moved(next_table) => {
table = self.help_transfer(table, next_table, guard);
}
BinEntry::Node(ref head)
if no_replacement && head.hash == h && &head.key == key =>
{
// fast path if replacement is disallowed and first bin matches
let v = head.value.load(Ordering::SeqCst, guard);
// safety: since the value is present now, and we've held a guard from the
// beginning of the search, the value cannot be dropped until the next epoch,
// which won't arrive until after we drop our guard.
return Some(unsafe { v.deref() });
}
BinEntry::Node(ref head) => {
// bin is non-empty, need to link into it, so we must take the lock
let head_lock = head.lock.lock();
// need to check that this is _still_ the head
let current_head = t.bin(bini, guard);
if current_head != bin {
// nope -- try again from the start
continue;
}
// yes, it is still the head, so we can now "own" the bin
// note that there can still be readers in the bin!
// TODO: TreeBin & ReservationNode
let mut bin_count = 1;
let mut p = bin;
let old_val = loop {
// safety: we read the bin while pinning the epoch. a bin will never be
// dropped until the next epoch after it is removed. since it wasn't
// removed, and the epoch was pinned, that cannot be until after we drop
// our guard.
let n = unsafe { p.deref() }.as_node().unwrap();
if n.hash == h && &n.key == key {
// the key already exists in the map!
let current_value = n.value.load(Ordering::SeqCst, guard);
// safety: since the value is present now, and we've held a guard from
// the beginning of the search, the value cannot be dropped until the
// next epoch, which won't arrive until after we drop our guard.
let current_value = unsafe { current_value.deref() };
if no_replacement {
// the key is not absent, so don't update
} else if let BinEntry::Node(Node { value, .. }) = *node.into_box() {
// safety: we own value and have never shared it
let now_garbage = n.value.swap(
unsafe { value.into_owned() },
Ordering::SeqCst,
guard,
);
// NOTE: now_garbage == current_value
// safety: need to guarantee that now_garbage is no longer
// reachable. more specifically, no thread that executes _after_
// this line can ever get a reference to now_garbage.
//
// here are the possible cases:
//
// - another thread already has a reference to now_garbage.
// they must have read it before the call to swap.
// because of this, that thread must be pinned to an epoch <=
// the epoch of our guard. since the garbage is placed in our
// epoch, it won't be freed until the _next_ epoch, at which
// point, that thread must have dropped its guard, and with it,
// any reference to the value.
// - another thread is about to get a reference to this value.
// they execute _after_ the swap, and therefore do _not_ get a
// reference to now_garbage (they get value instead). there are
// no other ways to get to a value except through its Node's
// `value` field (which is what we swapped), so freeing
// now_garbage is fine.
unsafe { guard.defer_destroy(now_garbage) };
} else {
unreachable!();
}
break Some(current_value);
}
// TODO: This Ordering can probably be relaxed due to the Mutex
let next = n.next.load(Ordering::SeqCst, guard);
if next.is_null() {
// we're at the end of the bin -- stick the node here!
n.next.store(node, Ordering::SeqCst);
break None;
}
p = next;
bin_count += 1;
};
drop(head_lock);
// TODO: TREEIFY_THRESHOLD
if old_val.is_none() {
// increment count
self.add_count(1, Some(bin_count), guard);
}
guard.flush();
return old_val;
}
}
}
}
fn put_all<I: Iterator<Item = (K, V)>>(&self, iter: I, guard: &Guard) {
for (key, value) in iter {
self.put(key, value, false, guard);
}
}
/// If the value for the specified `key` is present, attempts to
/// compute a new mapping given the key and its current mapped value.
///
/// The new mapping is computed by the `remapping_function`, which may
/// return `None` to signalize that the mapping should be removed.
/// The entire method invocation is performed atomically.
/// The supplied function is invoked exactly once per invocation of
/// this method if the key is present, else not at all. Some
/// attempted update operations on this map by other threads may be
/// blocked while computation is in progress, so the computation
/// should be short and simple.
///
/// Returns the new value associated with the specified `key`, or `None`
/// if no value for the specified `key` is present.
pub fn compute_if_present<'g, Q, F>(
&'g self,
key: &Q,
remapping_function: F,
guard: &'g Guard,
) -> Option<&'g V>
where
K: Borrow<Q>,
Q: ?Sized + Hash + Eq,
F: FnOnce(&K, &V) -> Option<V>,
{
self.check_guard(guard);
let h = self.hash(&key);
let mut table = self.table.load(Ordering::SeqCst, guard);
loop {
// safety: see argument below for !is_null case
if table.is_null() || unsafe { table.deref() }.is_empty() {
table = self.init_table(guard);
continue;
}
// safety: table is a valid pointer.
//
// we are in one of three cases:
//
// 1. if table is the one we read before the loop, then we read it while holding the
// guard, so it won't be dropped until after we drop that guard b/c the drop logic
// only queues a drop for the next epoch after removing the table.
//
// 2. if table is read by init_table, then either we did a load, and the argument is
// as for point 1. or, we allocated a table, in which case the earliest it can be
// deallocated is in the next epoch. we are holding up the epoch by holding the
// guard, so this deref is safe.
//
// 3. if table is set by a Moved node (below) through help_transfer, it will _either_
// keep using `table` (which is fine by 1. and 2.), or use the `next_table` raw
// pointer from inside the Moved. to see that if a Moved(t) is _read_, then t must
// still be valid, see the safety comment on BinEntry::Moved.
let t = unsafe { table.deref() };
let bini = t.bini(h);
let bin = t.bin(bini, guard);
if bin.is_null() {
// fast path -- bin is empty so key is not present
return None;
}
// slow path -- bin is non-empty
// safety: bin is a valid pointer.
//
// there are two cases when a bin pointer is invalidated:
//
// 1. if the table was resized, bin is a move entry, and the resize has completed. in
// that case, the table (and all its heads) will be dropped in the next epoch
// following that.
// 2. if the table is being resized, bin may be swapped with a move entry. the old bin
// will then be dropped in the following epoch after that happens.
//
// in both cases, we held the guard when we got the reference to the bin. if any such
// swap happened, it must have happened _after_ we read. since we did the read while
// pinning the epoch, the drop must happen in the _next_ epoch (i.e., the one that we
// are holding up by holding on to our guard).
match *unsafe { bin.deref() } {
BinEntry::Moved(next_table) => {
table = self.help_transfer(table, next_table, guard);
}
BinEntry::Node(ref head) => {
// bin is non-empty, need to link into it, so we must take the lock
let head_lock = head.lock.lock();
// need to check that this is _still_ the head
let current_head = t.bin(bini, guard);
if current_head != bin {
// nope -- try again from the start
continue;
}
// yes, it is still the head, so we can now "own" the bin
// note that there can still be readers in the bin!
// TODO: TreeBin & ReservationNode
let mut removed_node = false;
let mut bin_count = 1;
let mut p = bin;
let mut pred: Shared<'_, BinEntry<K, V>> = Shared::null();
let new_val = loop {
// safety: we read the bin while pinning the epoch. a bin will never be
// dropped until the next epoch after it is removed. since it wasn't
// removed, and the epoch was pinned, that cannot be until after we drop
// our guard.
let n = unsafe { p.deref() }.as_node().unwrap();
// TODO: This Ordering can probably be relaxed due to the Mutex
let next = n.next.load(Ordering::SeqCst, guard);
if n.hash == h && n.key.borrow() == key {
// the key already exists in the map!
let current_value = n.value.load(Ordering::SeqCst, guard);
// safety: since the value is present now, and we've held a guard from
// the beginning of the search, the value cannot be dropped until the
// next epoch, which won't arrive until after we drop our guard.
let new_value =
remapping_function(&n.key, unsafe { current_value.deref() });
if let Some(value) = new_value {
let now_garbage =
n.value.swap(Owned::new(value), Ordering::SeqCst, guard);
// NOTE: now_garbage == current_value
// safety: need to guarantee that now_garbage is no longer
// reachable. more specifically, no thread that executes _after_
// this line can ever get a reference to now_garbage.
//
// here are the possible cases:
//
// - another thread already has a reference to now_garbage.
// they must have read it before the call to swap.
// because of this, that thread must be pinned to an epoch <=
// the epoch of our guard. since the garbage is placed in our
// epoch, it won't be freed until the _next_ epoch, at which
// point, that thread must have dropped its guard, and with it,
// any reference to the value.
// - another thread is about to get a reference to this value.
// they execute _after_ the swap, and therefore do _not_ get a
// reference to now_garbage (they get value instead). there are
// no other ways to get to a value except through its Node's
// `value` field (which is what we swapped), so freeing
// now_garbage is fine.
unsafe { guard.defer_destroy(now_garbage) };
// safety: since the value is present now, and we've held a guard from
// the beginning of the search, the value cannot be dropped until the
// next epoch, which won't arrive until after we drop our guard.
break Some(unsafe {
n.value.load(Ordering::SeqCst, guard).deref()
});
} else {
removed_node = true;
// remove the BinEntry containing the removed key value pair from the bucket
if !pred.is_null() {
// either by changing the pointer of the previous BinEntry, if present
// safety: see remove
unsafe { pred.deref() }
.as_node()
.unwrap()
.next
.store(next, Ordering::SeqCst);
} else {
// or by setting the next node as the first BinEntry if there is no previous entry
t.store_bin(bini, next);
}
// in either case, mark the BinEntry as garbage, since it was just removed
// safety: need to guarantee that the old value is no longer
// reachable. more specifically, no thread that executes _after_
// this line can ever get a reference to val.
//
// here are the possible cases:
//
// - another thread already has a reference to the old value.
// they must have read it before the call to store_bin.
// because of this, that thread must be pinned to an epoch <=
// the epoch of our guard. since the garbage is placed in our
// epoch, it won't be freed until the _next_ epoch, at which
// point, that thread must have dropped its guard, and with it,
// any reference to the value.
// - another thread is about to get a reference to this value.
// they execute _after_ the store_bin, and therefore do _not_ get a
// reference to the old value. there are no other ways to get to a
// value except through its Node's `value` field (which is now gone
// together with the node), so freeing the old value is fine.
unsafe { guard.defer_destroy(p) };
unsafe { guard.defer_destroy(current_value) };
break None;
}
}
pred = p;
if next.is_null() {
// we're at the end of the bin
break None;
}
p = next;
bin_count += 1;
};
drop(head_lock);
if removed_node {
// decrement count
self.add_count(-1, Some(bin_count), guard);
}
guard.flush();
return new_val;
}
}
}
}
fn help_transfer<'g>(
&'g self,
table: Shared<'g, Table<K, V>>,
next_table: *const Table<K, V>,
guard: &'g Guard,
) -> Shared<'g, Table<K, V>> {
if table.is_null() || next_table.is_null() {
return table;
}
let next_table = Shared::from(next_table);
// safety: table is only dropped on the next epoch change after it is swapped to null.
// we read it as not null, so it must not be dropped until a subsequent epoch. since we
// held `guard` at the time, we know that the current epoch continues to persist, and that
// our reference is therefore valid.
let rs = Self::resize_stamp(unsafe { table.deref() }.len()) << RESIZE_STAMP_SHIFT;
while next_table == self.next_table.load(Ordering::SeqCst, guard)
&& table == self.table.load(Ordering::SeqCst, guard)
{
let sc = self.size_ctl.load(Ordering::SeqCst);
if sc >= 0
|| sc == rs + MAX_RESIZERS
|| sc == rs + 1
|| self.transfer_index.load(Ordering::SeqCst) <= 0
{
break;
}
if self.size_ctl.compare_and_swap(sc, sc + 1, Ordering::SeqCst) == sc {
self.transfer(table, next_table, guard);
break;
}
}
next_table
}
fn add_count(&self, n: isize, resize_hint: Option<usize>, guard: &Guard) {
// TODO: implement the Java CounterCell business here
use std::cmp;
let mut count = match n.cmp(&0) {
cmp::Ordering::Greater => {
let n = n as usize;
self.count.fetch_add(n, Ordering::SeqCst) + n
}
cmp::Ordering::Less => {
let n = n.abs() as usize;
self.count.fetch_sub(n, Ordering::SeqCst) - n
}
cmp::Ordering::Equal => self.count.load(Ordering::SeqCst),
};