-
Notifications
You must be signed in to change notification settings - Fork 442
/
base.rs
2038 lines (1816 loc) · 66.3 KB
/
base.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
//! A lock-free skip list. See [`SkipList`].
use alloc::alloc::{alloc, dealloc, handle_alloc_error, Layout};
use core::borrow::Borrow;
use core::cmp;
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use core::ops::{Bound, Deref, Index, RangeBounds};
use core::ptr;
use core::sync::atomic::{fence, AtomicUsize, Ordering};
use crate::epoch::{self, Atomic, Collector, Guard, Shared};
use crate::utils::CachePadded;
/// Number of bits needed to store height.
const HEIGHT_BITS: usize = 5;
/// Maximum height of a skip list tower.
const MAX_HEIGHT: usize = 1 << HEIGHT_BITS;
/// The bits of `refs_and_height` that keep the height.
const HEIGHT_MASK: usize = (1 << HEIGHT_BITS) - 1;
/// The tower of atomic pointers.
///
/// The actual size of the tower will vary depending on the height that a node
/// was allocated with.
#[repr(C)]
struct Tower<K, V> {
pointers: [Atomic<Node<K, V>>; 0],
}
impl<K, V> Index<usize> for Tower<K, V> {
type Output = Atomic<Node<K, V>>;
fn index(&self, index: usize) -> &Atomic<Node<K, V>> {
// This implementation is actually unsafe since we don't check if the
// index is in-bounds. But this is fine since this is only used internally.
unsafe { self.pointers.get_unchecked(index) }
}
}
/// Tower at the head of a skip list.
///
/// This is located in the `SkipList` struct itself and holds a full height
/// tower.
#[repr(C)]
struct Head<K, V> {
pointers: [Atomic<Node<K, V>>; MAX_HEIGHT],
}
impl<K, V> Head<K, V> {
/// Initializes a `Head`.
#[inline]
fn new() -> Head<K, V> {
// Initializing arrays in rust is a pain...
Head {
pointers: Default::default(),
}
}
}
impl<K, V> Deref for Head<K, V> {
type Target = Tower<K, V>;
fn deref(&self) -> &Tower<K, V> {
unsafe { &*(self as *const _ as *const Tower<K, V>) }
}
}
/// A skip list node.
///
/// This struct is marked with `repr(C)` so that the specific order of fields is enforced.
/// It is important that the tower is the last field since it is dynamically sized. The key,
/// reference count, and height are kept close to the tower to improve cache locality during
/// skip list traversal.
#[repr(C)]
struct Node<K, V> {
/// The value.
value: V,
/// The key.
key: K,
/// Keeps the reference count and the height of its tower.
///
/// The reference count is equal to the number of `Entry`s pointing to this node, plus the
/// number of levels in which this node is installed.
refs_and_height: AtomicUsize,
/// The tower of atomic pointers.
tower: Tower<K, V>,
}
impl<K, V> Node<K, V> {
/// Allocates a node.
///
/// The returned node will start with reference count of `ref_count` and the tower will be initialized
/// with null pointers. However, the key and the value will be left uninitialized, and that is
/// why this function is unsafe.
unsafe fn alloc(height: usize, ref_count: usize) -> *mut Self {
let layout = Self::get_layout(height);
let ptr = alloc(layout) as *mut Self;
if ptr.is_null() {
handle_alloc_error(layout);
}
ptr::write(
&mut (*ptr).refs_and_height,
AtomicUsize::new((height - 1) | ref_count << HEIGHT_BITS),
);
ptr::write_bytes((*ptr).tower.pointers.as_mut_ptr(), 0, height);
ptr
}
/// Deallocates a node.
///
/// This function will not run any destructors.
unsafe fn dealloc(ptr: *mut Self) {
let height = (*ptr).height();
let layout = Self::get_layout(height);
dealloc(ptr as *mut u8, layout);
}
/// Returns the layout of a node with the given `height`.
unsafe fn get_layout(height: usize) -> Layout {
assert!((1..=MAX_HEIGHT).contains(&height));
let size_self = mem::size_of::<Self>();
let align_self = mem::align_of::<Self>();
let size_pointer = mem::size_of::<Atomic<Self>>();
Layout::from_size_align_unchecked(size_self + size_pointer * height, align_self)
}
/// Returns the height of this node's tower.
#[inline]
fn height(&self) -> usize {
(self.refs_and_height.load(Ordering::Relaxed) & HEIGHT_MASK) + 1
}
/// Marks all pointers in the tower and returns `true` if the level 0 was not marked.
fn mark_tower(&self) -> bool {
let height = self.height();
for level in (0..height).rev() {
let tag = unsafe {
// We're loading the pointer only for the tag, so it's okay to use
// `epoch::unprotected()` in this situation.
// TODO(Amanieu): can we use release ordering here?
self.tower[level]
.fetch_or(1, Ordering::SeqCst, epoch::unprotected())
.tag()
};
// If the level 0 pointer was already marked, somebody else removed the node.
if level == 0 && tag == 1 {
return false;
}
}
// We marked the level 0 pointer, therefore we removed the node.
true
}
/// Returns `true` if the node is removed.
#[inline]
fn is_removed(&self) -> bool {
let tag = unsafe {
// We're loading the pointer only for the tag, so it's okay to use
// `epoch::unprotected()` in this situation.
self.tower[0]
.load(Ordering::Relaxed, epoch::unprotected())
.tag()
};
tag == 1
}
/// Attempts to increment the reference count of a node and returns `true` on success.
///
/// The reference count can be incremented only if it is non-zero.
///
/// # Panics
///
/// Panics if the reference count overflows.
#[inline]
unsafe fn try_increment(&self) -> bool {
let mut refs_and_height = self.refs_and_height.load(Ordering::Relaxed);
loop {
// If the reference count is zero, then the node has already been
// queued for deletion. Incrementing it again could lead to a
// double-free.
if refs_and_height & !HEIGHT_MASK == 0 {
return false;
}
// If all bits in the reference count are ones, we're about to overflow it.
let new_refs_and_height = refs_and_height
.checked_add(1 << HEIGHT_BITS)
.expect("SkipList reference count overflow");
// Try incrementing the count.
match self.refs_and_height.compare_exchange_weak(
refs_and_height,
new_refs_and_height,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => return true,
Err(current) => refs_and_height = current,
}
}
}
/// Decrements the reference count of a node, destroying it if the count becomes zero.
#[inline]
unsafe fn decrement(&self, guard: &Guard) {
if self
.refs_and_height
.fetch_sub(1 << HEIGHT_BITS, Ordering::Release)
>> HEIGHT_BITS
== 1
{
fence(Ordering::Acquire);
guard.defer_unchecked(move || Self::finalize(self));
}
}
/// Decrements the reference count of a node, pinning the thread and destroying the node
/// if the count become zero.
#[inline]
unsafe fn decrement_with_pin<F>(&self, parent: &SkipList<K, V>, pin: F)
where
F: FnOnce() -> Guard,
{
if self
.refs_and_height
.fetch_sub(1 << HEIGHT_BITS, Ordering::Release)
>> HEIGHT_BITS
== 1
{
fence(Ordering::Acquire);
let guard = &pin();
parent.check_guard(guard);
guard.defer_unchecked(move || Self::finalize(self));
}
}
/// Drops the key and value of a node, then deallocates it.
#[cold]
unsafe fn finalize(ptr: *const Self) {
let ptr = ptr as *mut Self;
// Call destructors: drop the key and the value.
ptr::drop_in_place(&mut (*ptr).key);
ptr::drop_in_place(&mut (*ptr).value);
// Finally, deallocate the memory occupied by the node.
Node::dealloc(ptr);
}
}
impl<K, V> fmt::Debug for Node<K, V>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Node")
.field(&self.key)
.field(&self.value)
.finish()
}
}
/// A search result.
///
/// The result indicates whether the key was found, as well as what were the adjacent nodes to the
/// key on each level of the skip list.
struct Position<'a, K, V> {
/// Reference to a node with the given key, if found.
///
/// If this is `Some` then it will point to the same node as `right[0]`.
found: Option<&'a Node<K, V>>,
/// Adjacent nodes with smaller keys (predecessors).
left: [&'a Tower<K, V>; MAX_HEIGHT],
/// Adjacent nodes with equal or greater keys (successors).
right: [Shared<'a, Node<K, V>>; MAX_HEIGHT],
}
/// Frequently modified data associated with a skip list.
struct HotData {
/// The seed for random height generation.
seed: AtomicUsize,
/// The number of entries in the skip list.
len: AtomicUsize,
/// Highest tower currently in use. This value is used as a hint for where
/// to start lookups and never decreases.
max_height: AtomicUsize,
}
/// A lock-free skip list.
// TODO(stjepang): Embed a custom `epoch::Collector` inside `SkipList<K, V>`. Instead of adding
// garbage to the default global collector, we should add it to a local collector tied to the
// particular skip list instance.
//
// Since global collector might destroy garbage arbitrarily late in the future, some skip list
// methods have `K: 'static` and `V: 'static` bounds. But a local collector embedded in the skip
// list would destroy all remaining garbage when the skip list is dropped, so in that case we'd be
// able to remove those bounds on types `K` and `V`.
//
// As a further future optimization, if `!mem::needs_drop::<K>() && !mem::needs_drop::<V>()`
// (neither key nor the value have destructors), there's no point in creating a new local
// collector, so we should simply use the global one.
pub struct SkipList<K, V> {
/// The head of the skip list (just a dummy node, not a real entry).
head: Head<K, V>,
/// The `Collector` associated with this skip list.
collector: Collector,
/// Hot data associated with the skip list, stored in a dedicated cache line.
hot_data: CachePadded<HotData>,
}
unsafe impl<K: Send + Sync, V: Send + Sync> Send for SkipList<K, V> {}
unsafe impl<K: Send + Sync, V: Send + Sync> Sync for SkipList<K, V> {}
impl<K, V> SkipList<K, V> {
/// Returns a new, empty skip list.
pub fn new(collector: Collector) -> SkipList<K, V> {
SkipList {
head: Head::new(),
collector,
hot_data: CachePadded::new(HotData {
seed: AtomicUsize::new(1),
len: AtomicUsize::new(0),
max_height: AtomicUsize::new(1),
}),
}
}
/// Returns `true` if the skip list is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the number of entries in the skip list.
///
/// If the skip list is being concurrently modified, consider the returned number just an
/// approximation without any guarantees.
pub fn len(&self) -> usize {
let len = self.hot_data.len.load(Ordering::Relaxed);
// Due to the relaxed memory ordering, the length counter may sometimes
// underflow and produce a very large value. We treat such values as 0.
if len > isize::max_value() as usize {
0
} else {
len
}
}
/// Ensures that all `Guard`s used with the skip list come from the same
/// `Collector`.
fn check_guard(&self, guard: &Guard) {
if let Some(c) = guard.collector() {
assert!(c == &self.collector);
}
}
}
impl<K, V> SkipList<K, V>
where
K: Ord,
{
/// Returns the entry with the smallest key.
pub fn front<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>> {
self.check_guard(guard);
let n = self.next_node(&self.head, Bound::Unbounded, guard)?;
Some(Entry {
parent: self,
node: n,
guard,
})
}
/// Returns the entry with the largest key.
pub fn back<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>> {
self.check_guard(guard);
let n = self.search_bound(Bound::Unbounded, true, guard)?;
Some(Entry {
parent: self,
node: n,
guard,
})
}
/// Returns `true` if the map contains a value for the specified key.
pub fn contains_key<Q>(&self, key: &Q, guard: &Guard) -> bool
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.get(key, guard).is_some()
}
/// Returns an entry with the specified `key`.
pub fn get<'a: 'g, 'g, Q>(&'a self, key: &Q, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.check_guard(guard);
let n = self.search_bound(Bound::Included(key), false, guard)?;
if n.key.borrow() != key {
return None;
}
Some(Entry {
parent: self,
node: n,
guard,
})
}
/// Returns an `Entry` pointing to the lowest element whose key is above
/// the given bound. If no such element is found then `None` is
/// returned.
pub fn lower_bound<'a: 'g, 'g, Q>(
&'a self,
bound: Bound<&Q>,
guard: &'g Guard,
) -> Option<Entry<'a, 'g, K, V>>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.check_guard(guard);
let n = self.search_bound(bound, false, guard)?;
Some(Entry {
parent: self,
node: n,
guard,
})
}
/// Returns an `Entry` pointing to the highest element whose key is below
/// the given bound. If no such element is found then `None` is
/// returned.
pub fn upper_bound<'a: 'g, 'g, Q>(
&'a self,
bound: Bound<&Q>,
guard: &'g Guard,
) -> Option<Entry<'a, 'g, K, V>>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.check_guard(guard);
let n = self.search_bound(bound, true, guard)?;
Some(Entry {
parent: self,
node: n,
guard,
})
}
/// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist.
pub fn get_or_insert(&self, key: K, value: V, guard: &Guard) -> RefEntry<'_, K, V> {
self.insert_internal(key, value, false, guard)
}
/// Returns an iterator over all entries in the skip list.
pub fn iter<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Iter<'a, 'g, K, V> {
self.check_guard(guard);
Iter {
parent: self,
head: None,
tail: None,
guard,
}
}
/// Returns an iterator over all entries in the skip list.
pub fn ref_iter(&self) -> RefIter<'_, K, V> {
RefIter {
parent: self,
head: None,
tail: None,
}
}
/// Returns an iterator over a subset of entries in the skip list.
pub fn range<'a: 'g, 'g, Q, R>(
&'a self,
range: R,
guard: &'g Guard,
) -> Range<'a, 'g, Q, R, K, V>
where
K: Borrow<Q>,
R: RangeBounds<Q>,
Q: Ord + ?Sized,
{
self.check_guard(guard);
Range {
parent: self,
head: None,
tail: None,
range,
guard,
_marker: PhantomData,
}
}
/// Returns an iterator over a subset of entries in the skip list.
#[allow(clippy::needless_lifetimes)]
pub fn ref_range<'a, Q, R>(&'a self, range: R) -> RefRange<'a, Q, R, K, V>
where
K: Borrow<Q>,
R: RangeBounds<Q>,
Q: Ord + ?Sized,
{
RefRange {
parent: self,
range,
head: None,
tail: None,
_marker: PhantomData,
}
}
/// Generates a random height and returns it.
fn random_height(&self) -> usize {
// Pseudorandom number generation from "Xorshift RNGs" by George Marsaglia.
//
// This particular set of operations generates 32-bit integers. See:
// https://en.wikipedia.org/wiki/Xorshift#Example_implementation
let mut num = self.hot_data.seed.load(Ordering::Relaxed);
num ^= num << 13;
num ^= num >> 17;
num ^= num << 5;
self.hot_data.seed.store(num, Ordering::Relaxed);
let mut height = cmp::min(MAX_HEIGHT, num.trailing_zeros() as usize + 1);
unsafe {
// Keep decreasing the height while it's much larger than all towers currently in the
// skip list.
//
// Note that we're loading the pointer only to check whether it is null, so it's okay
// to use `epoch::unprotected()` in this situation.
while height >= 4
&& self.head[height - 2]
.load(Ordering::Relaxed, epoch::unprotected())
.is_null()
{
height -= 1;
}
}
// Track the max height to speed up lookups
let mut max_height = self.hot_data.max_height.load(Ordering::Relaxed);
while height > max_height {
match self.hot_data.max_height.compare_exchange_weak(
max_height,
height,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(h) => max_height = h,
}
}
height
}
/// If we encounter a deleted node while searching, help with the deletion
/// by attempting to unlink the node from the list.
///
/// If the unlinking is successful then this function returns the next node
/// with which the search should continue on the current level.
#[cold]
unsafe fn help_unlink<'a>(
&'a self,
pred: &'a Atomic<Node<K, V>>,
curr: &'a Node<K, V>,
succ: Shared<'a, Node<K, V>>,
guard: &'a Guard,
) -> Option<Shared<'a, Node<K, V>>> {
// If `succ` is marked, that means `curr` is removed. Let's try
// unlinking it from the skip list at this level.
match pred.compare_exchange(
Shared::from(curr as *const _),
succ.with_tag(0),
Ordering::Release,
Ordering::Relaxed,
guard,
) {
Ok(_) => {
curr.decrement(guard);
Some(succ.with_tag(0))
}
Err(_) => None,
}
}
/// Returns the successor of a node.
///
/// This will keep searching until a non-deleted node is found. If a deleted
/// node is reached then a search is performed using the given key.
fn next_node<'a>(
&'a self,
pred: &'a Tower<K, V>,
lower_bound: Bound<&K>,
guard: &'a Guard,
) -> Option<&'a Node<K, V>> {
unsafe {
// Load the level 0 successor of the current node.
let mut curr = pred[0].load_consume(guard);
// If `curr` is marked, that means `pred` is removed and we have to use
// a key search.
if curr.tag() == 1 {
return self.search_bound(lower_bound, false, guard);
}
while let Some(c) = curr.as_ref() {
let succ = c.tower[0].load_consume(guard);
if succ.tag() == 1 {
if let Some(c) = self.help_unlink(&pred[0], c, succ, guard) {
// On success, continue searching through the current level.
curr = c;
continue;
} else {
// On failure, we cannot do anything reasonable to continue
// searching from the current position. Restart the search.
return self.search_bound(lower_bound, false, guard);
}
}
return Some(c);
}
None
}
}
/// Searches for first/last node that is greater/less/equal to a key in the skip list.
///
/// If `upper_bound == true`: the last node less than (or equal to) the key.
///
/// If `upper_bound == false`: the first node greater than (or equal to) the key.
///
/// This is unsafe because the returned nodes are bound to the lifetime of
/// the `SkipList`, not the `Guard`.
fn search_bound<'a, Q>(
&'a self,
bound: Bound<&Q>,
upper_bound: bool,
guard: &'a Guard,
) -> Option<&'a Node<K, V>>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
unsafe {
'search: loop {
// The current level we're at.
let mut level = self.hot_data.max_height.load(Ordering::Relaxed);
// Fast loop to skip empty tower levels.
while level >= 1
&& self.head[level - 1]
.load(Ordering::Relaxed, guard)
.is_null()
{
level -= 1;
}
// The current best node
let mut result = None;
// The predecessor node
let mut pred = &*self.head;
while level >= 1 {
level -= 1;
// Two adjacent nodes at the current level.
let mut curr = pred[level].load_consume(guard);
// If `curr` is marked, that means `pred` is removed and we have to restart the
// search.
if curr.tag() == 1 {
continue 'search;
}
// Iterate through the current level until we reach a node with a key greater
// than or equal to `key`.
while let Some(c) = curr.as_ref() {
let succ = c.tower[level].load_consume(guard);
if succ.tag() == 1 {
if let Some(c) = self.help_unlink(&pred[level], c, succ, guard) {
// On success, continue searching through the current level.
curr = c;
continue;
} else {
// On failure, we cannot do anything reasonable to continue
// searching from the current position. Restart the search.
continue 'search;
}
}
// If `curr` contains a key that is greater than (or equal) to `key`, we're
// done with this level.
//
// The condition determines whether we should stop the search. For the upper
// bound, we return the last node before the condition became true. For the
// lower bound, we return the first node after the condition became true.
if upper_bound {
if !below_upper_bound(&bound, c.key.borrow()) {
break;
}
result = Some(c);
} else if above_lower_bound(&bound, c.key.borrow()) {
result = Some(c);
break;
}
// Move one step forward.
pred = &c.tower;
curr = succ;
}
}
return result;
}
}
}
/// Searches for a key in the skip list and returns a list of all adjacent nodes.
fn search_position<'a, Q>(&'a self, key: &Q, guard: &'a Guard) -> Position<'a, K, V>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
unsafe {
'search: loop {
// The result of this search.
let mut result = Position {
found: None,
left: [&*self.head; MAX_HEIGHT],
right: [Shared::null(); MAX_HEIGHT],
};
// The current level we're at.
let mut level = self.hot_data.max_height.load(Ordering::Relaxed);
// Fast loop to skip empty tower levels.
while level >= 1
&& self.head[level - 1]
.load(Ordering::Relaxed, guard)
.is_null()
{
level -= 1;
}
// The predecessor node
let mut pred = &*self.head;
while level >= 1 {
level -= 1;
// Two adjacent nodes at the current level.
let mut curr = pred[level].load_consume(guard);
// If `curr` is marked, that means `pred` is removed and we have to restart the
// search.
if curr.tag() == 1 {
continue 'search;
}
// Iterate through the current level until we reach a node with a key greater
// than or equal to `key`.
while let Some(c) = curr.as_ref() {
let succ = c.tower[level].load_consume(guard);
if succ.tag() == 1 {
if let Some(c) = self.help_unlink(&pred[level], c, succ, guard) {
// On success, continue searching through the current level.
curr = c;
continue;
} else {
// On failure, we cannot do anything reasonable to continue
// searching from the current position. Restart the search.
continue 'search;
}
}
// If `curr` contains a key that is greater than or equal to `key`, we're
// done with this level.
match c.key.borrow().cmp(key) {
cmp::Ordering::Greater => break,
cmp::Ordering::Equal => {
result.found = Some(c);
break;
}
cmp::Ordering::Less => {}
}
// Move one step forward.
pred = &c.tower;
curr = succ;
}
// Store the position at the current level into the result.
result.left[level] = pred;
result.right[level] = curr;
}
return result;
}
}
}
/// Inserts an entry with the specified `key` and `value`.
///
/// If `replace` is `true`, then any existing entry with this key will first be removed.
fn insert_internal(
&self,
key: K,
value: V,
replace: bool,
guard: &Guard,
) -> RefEntry<'_, K, V> {
self.check_guard(guard);
unsafe {
// Rebind the guard to the lifetime of self. This is a bit of a
// hack but it allows us to return references that are not bound to
// the lifetime of the guard.
let guard = &*(guard as *const _);
let mut search;
loop {
// First try searching for the key.
// Note that the `Ord` implementation for `K` may panic during the search.
search = self.search_position(&key, guard);
let r = match search.found {
Some(r) => r,
None => break,
};
if replace {
// If a node with the key was found and we should replace it, mark its tower
// and then repeat the search.
if r.mark_tower() {
self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
}
} else {
// If a node with the key was found and we're not going to replace it, let's
// try returning it as an entry.
if let Some(e) = RefEntry::try_acquire(self, r) {
return e;
}
// If we couldn't increment the reference count, that means someone has just
// now removed the node.
break;
}
}
// Create a new node.
let height = self.random_height();
let (node, n) = {
// The reference count is initially two to account for:
// 1. The entry that will be returned.
// 2. The link at the level 0 of the tower.
let n = Node::<K, V>::alloc(height, 2);
// Write the key and the value into the node.
ptr::write(&mut (*n).key, key);
ptr::write(&mut (*n).value, value);
(Shared::<Node<K, V>>::from(n as *const _), &*n)
};
// Optimistically increment `len`.
self.hot_data.len.fetch_add(1, Ordering::Relaxed);
loop {
// Set the lowest successor of `n` to `search.right[0]`.
n.tower[0].store(search.right[0], Ordering::Relaxed);
// Try installing the new node into the skip list (at level 0).
// TODO(Amanieu): can we use release ordering here?
if search.left[0][0]
.compare_exchange(
search.right[0],
node,
Ordering::SeqCst,
Ordering::SeqCst,
guard,
)
.is_ok()
{
break;
}
// We failed. Let's search for the key and try again.
{
// Create a guard that destroys the new node in case search panics.
let sg = scopeguard::guard((), |_| {
Node::finalize(node.as_raw());
});
search = self.search_position(&n.key, guard);
mem::forget(sg);
}
if let Some(r) = search.found {
if replace {
// If a node with the key was found and we should replace it, mark its
// tower and then repeat the search.
if r.mark_tower() {
self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
}
} else {
// If a node with the key was found and we're not going to replace it,
// let's try returning it as an entry.
if let Some(e) = RefEntry::try_acquire(self, r) {
// Destroy the new node.
Node::finalize(node.as_raw());
self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
return e;
}
// If we couldn't increment the reference count, that means someone has
// just now removed the node.
}
}
}
// The new node was successfully installed. Let's create an entry associated with it.
let entry = RefEntry {
parent: self,
node: n,
};
// Build the rest of the tower above level 0.
'build: for level in 1..height {
loop {
// Obtain the predecessor and successor at the current level.
let pred = search.left[level];
let succ = search.right[level];
// Load the current value of the pointer in the tower at this level.
// TODO(Amanieu): can we use relaxed ordering here?
let next = n.tower[level].load(Ordering::SeqCst, guard);
// If the current pointer is marked, that means another thread is already
// removing the node we've just inserted. In that case, let's just stop
// building the tower.
if next.tag() == 1 {
break 'build;
}
// When searching for `key` and traversing the skip list from the highest level
// to the lowest, it is possible to observe a node with an equal key at higher
// levels and then find it missing at the lower levels if it gets removed
// during traversal. Even worse, it is possible to observe completely different
// nodes with the exact same key at different levels.
//
// Linking the new node to a dead successor with an equal key could create
// subtle corner cases that would require special care. It's much easier to
// simply prohibit linking two nodes with equal keys.
//
// If the successor has the same key as the new node, that means it is marked
// as removed and should be unlinked from the skip list. In that case, let's
// repeat the search to make sure it gets unlinked and try again.
//
// If this comparison or the following search panics, we simply stop building
// the tower without breaking any invariants. Note that building higher levels
// is completely optional. Only the lowest level really matters, and all the
// higher levels are there just to make searching faster.
if succ.as_ref().map(|s| &s.key) == Some(&n.key) {
search = self.search_position(&n.key, guard);
continue;
}
// Change the pointer at the current level from `next` to `succ`. If this CAS
// operation fails, that means another thread has marked the pointer and we
// should stop building the tower.
// TODO(Amanieu): can we use release ordering here?