crossbeam_skiplist/base.rs
1//! A lock-free skip list. See [`SkipList`].
2
3use alloc::alloc::{alloc, dealloc, handle_alloc_error, Layout};
4use core::borrow::Borrow;
5use core::cmp;
6use core::fmt;
7use core::marker::PhantomData;
8use core::mem;
9use core::ops::{Bound, Deref, Index, RangeBounds};
10use core::ptr;
11use core::sync::atomic::{fence, AtomicUsize, Ordering};
12
13use crossbeam_epoch::{self as epoch, Atomic, Collector, Guard, Shared};
14use crossbeam_utils::CachePadded;
15
16/// Number of bits needed to store height.
17const HEIGHT_BITS: usize = 5;
18
19/// Maximum height of a skip list tower.
20const MAX_HEIGHT: usize = 1 << HEIGHT_BITS;
21
22/// The bits of `refs_and_height` that keep the height.
23const HEIGHT_MASK: usize = (1 << HEIGHT_BITS) - 1;
24
25/// The tower of atomic pointers.
26///
27/// The actual size of the tower will vary depending on the height that a node
28/// was allocated with.
29#[repr(C)]
30struct Tower<K, V> {
31 pointers: [Atomic<Node<K, V>>; 0],
32}
33
34impl<K, V> Index<usize> for Tower<K, V> {
35 type Output = Atomic<Node<K, V>>;
36 fn index(&self, index: usize) -> &Atomic<Node<K, V>> {
37 // This implementation is actually unsafe since we don't check if the
38 // index is in-bounds. But this is fine since this is only used internally.
39 unsafe { &*(&self.pointers as *const Atomic<Node<K, V>>).add(index) }
40 }
41}
42
43/// Tower at the head of a skip list.
44///
45/// This is located in the `SkipList` struct itself and holds a full height
46/// tower.
47#[repr(C)]
48struct Head<K, V> {
49 pointers: [Atomic<Node<K, V>>; MAX_HEIGHT],
50}
51
52impl<K, V> Head<K, V> {
53 /// Initializes a `Head`.
54 #[inline]
55 fn new() -> Self {
56 // Initializing arrays in rust is a pain...
57 Self {
58 pointers: Default::default(),
59 }
60 }
61}
62
63impl<K, V> Deref for Head<K, V> {
64 type Target = Tower<K, V>;
65 fn deref(&self) -> &Tower<K, V> {
66 unsafe { &*(self as *const _ as *const Tower<K, V>) }
67 }
68}
69
70/// A skip list node.
71///
72/// This struct is marked with `repr(C)` so that the specific order of fields is enforced.
73/// It is important that the tower is the last field since it is dynamically sized. The key,
74/// reference count, and height are kept close to the tower to improve cache locality during
75/// skip list traversal.
76#[repr(C)]
77struct Node<K, V> {
78 /// The value.
79 value: V,
80
81 /// The key.
82 key: K,
83
84 /// Keeps the reference count and the height of its tower.
85 ///
86 /// The reference count is equal to the number of `Entry`s pointing to this node, plus the
87 /// number of levels in which this node is installed.
88 refs_and_height: AtomicUsize,
89
90 /// The tower of atomic pointers.
91 tower: Tower<K, V>,
92}
93
94impl<K, V> Node<K, V> {
95 /// Allocates a node.
96 ///
97 /// The returned node will start with reference count of `ref_count` and the tower will be initialized
98 /// with null pointers. However, the key and the value will be left uninitialized, and that is
99 /// why this function is unsafe.
100 unsafe fn alloc(height: usize, ref_count: usize) -> *mut Self {
101 let layout = Self::get_layout(height);
102 unsafe {
103 let ptr = alloc(layout).cast::<Self>();
104 if ptr.is_null() {
105 handle_alloc_error(layout);
106 }
107
108 ptr::addr_of_mut!((*ptr).refs_and_height)
109 .write(AtomicUsize::new((height - 1) | ref_count << HEIGHT_BITS));
110 ptr::addr_of_mut!((*ptr).tower.pointers)
111 .cast::<Atomic<Self>>()
112 .write_bytes(0, height);
113 ptr
114 }
115 }
116
117 /// Deallocates a node.
118 ///
119 /// This function will not run any destructors.
120 unsafe fn dealloc(ptr: *mut Self) {
121 unsafe {
122 let height = (*ptr).height();
123 let layout = Self::get_layout(height);
124 dealloc(ptr.cast::<u8>(), layout);
125 }
126 }
127
128 /// Returns the layout of a node with the given `height`.
129 fn get_layout(height: usize) -> Layout {
130 assert!((1..=MAX_HEIGHT).contains(&height));
131
132 Layout::new::<Self>()
133 .extend(Layout::array::<Atomic<Self>>(height).unwrap())
134 .unwrap()
135 .0
136 .pad_to_align()
137 }
138
139 /// Returns the height of this node's tower.
140 #[inline]
141 fn height(&self) -> usize {
142 (self.refs_and_height.load(Ordering::Relaxed) & HEIGHT_MASK) + 1
143 }
144
145 /// Marks all pointers in the tower and returns `true` if the level 0 was not marked.
146 fn mark_tower(&self) -> bool {
147 let height = self.height();
148
149 for level in (0..height).rev() {
150 let tag = unsafe {
151 // We're loading the pointer only for the tag, so it's okay to use
152 // `epoch::unprotected()` in this situation.
153 // TODO(Amanieu): can we use release ordering here?
154 self.tower[level]
155 .fetch_or(1, Ordering::SeqCst, epoch::unprotected())
156 .tag()
157 };
158
159 // If the level 0 pointer was already marked, somebody else removed the node.
160 if level == 0 && tag == 1 {
161 return false;
162 }
163 }
164
165 // We marked the level 0 pointer, therefore we removed the node.
166 true
167 }
168
169 /// Returns `true` if the node is removed.
170 #[inline]
171 fn is_removed(&self) -> bool {
172 let tag = unsafe {
173 // We're loading the pointer only for the tag, so it's okay to use
174 // `epoch::unprotected()` in this situation.
175 self.tower[0]
176 .load(Ordering::Relaxed, epoch::unprotected())
177 .tag()
178 };
179 tag == 1
180 }
181
182 /// Attempts to increment the reference count of a node and returns `true` on success.
183 ///
184 /// The reference count can be incremented only if it is non-zero.
185 ///
186 /// # Panics
187 ///
188 /// Panics if the reference count overflows.
189 #[inline]
190 unsafe fn try_increment(&self) -> bool {
191 let mut refs_and_height = self.refs_and_height.load(Ordering::Relaxed);
192
193 loop {
194 // If the reference count is zero, then the node has already been
195 // queued for deletion. Incrementing it again could lead to a
196 // double-free.
197 if refs_and_height & !HEIGHT_MASK == 0 {
198 return false;
199 }
200
201 // If all bits in the reference count are ones, we're about to overflow it.
202 let new_refs_and_height = refs_and_height
203 .checked_add(1 << HEIGHT_BITS)
204 .expect("SkipList reference count overflow");
205
206 // Try incrementing the count.
207 match self.refs_and_height.compare_exchange_weak(
208 refs_and_height,
209 new_refs_and_height,
210 Ordering::Relaxed,
211 Ordering::Relaxed,
212 ) {
213 Ok(_) => return true,
214 Err(current) => refs_and_height = current,
215 }
216 }
217 }
218
219 /// Decrements the reference count of a node, destroying it if the count becomes zero.
220 #[inline]
221 unsafe fn decrement(&self, guard: &Guard) {
222 if self
223 .refs_and_height
224 .fetch_sub(1 << HEIGHT_BITS, Ordering::Release)
225 >> HEIGHT_BITS
226 == 1
227 {
228 fence(Ordering::Acquire);
229 unsafe { guard.defer_unchecked(move || Self::finalize(self)) }
230 }
231 }
232
233 /// Decrements the reference count of a node, pinning the thread and destroying the node
234 /// if the count become zero.
235 #[inline]
236 unsafe fn decrement_with_pin<F>(&self, parent: &SkipList<K, V>, pin: F)
237 where
238 F: FnOnce() -> Guard,
239 {
240 if self
241 .refs_and_height
242 .fetch_sub(1 << HEIGHT_BITS, Ordering::Release)
243 >> HEIGHT_BITS
244 == 1
245 {
246 fence(Ordering::Acquire);
247 let guard = &pin();
248 parent.check_guard(guard);
249 unsafe { guard.defer_unchecked(move || Self::finalize(self)) }
250 }
251 }
252
253 /// Drops the key and value of a node, then deallocates it.
254 #[cold]
255 unsafe fn finalize(ptr: *const Self) {
256 let ptr = ptr as *mut Self;
257
258 unsafe {
259 // Call destructors: drop the key and the value.
260 ptr::drop_in_place(&mut (*ptr).key);
261 ptr::drop_in_place(&mut (*ptr).value);
262
263 // Finally, deallocate the memory occupied by the node.
264 Self::dealloc(ptr);
265 }
266 }
267}
268
269impl<K, V> fmt::Debug for Node<K, V>
270where
271 K: fmt::Debug,
272 V: fmt::Debug,
273{
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.debug_tuple("Node")
276 .field(&self.key)
277 .field(&self.value)
278 .finish()
279 }
280}
281
282/// A search result.
283///
284/// The result indicates whether the key was found, as well as what were the adjacent nodes to the
285/// key on each level of the skip list.
286struct Position<'a, K, V> {
287 /// Reference to a node with the given key, if found.
288 ///
289 /// If this is `Some` then it will point to the same node as `right[0]`.
290 found: Option<&'a Node<K, V>>,
291
292 /// Adjacent nodes with smaller keys (predecessors).
293 left: [&'a Tower<K, V>; MAX_HEIGHT],
294
295 /// Adjacent nodes with equal or greater keys (successors).
296 right: [Shared<'a, Node<K, V>>; MAX_HEIGHT],
297}
298
299/// Frequently modified data associated with a skip list.
300struct HotData {
301 /// The seed for random height generation.
302 seed: AtomicUsize,
303
304 /// The number of entries in the skip list.
305 len: AtomicUsize,
306
307 /// Highest tower currently in use. This value is used as a hint for where
308 /// to start lookups and never decreases.
309 max_height: AtomicUsize,
310}
311
312/// A lock-free skip list.
313// TODO(stjepang): Embed a custom `epoch::Collector` inside `SkipList<K, V>`. Instead of adding
314// garbage to the default global collector, we should add it to a local collector tied to the
315// particular skip list instance.
316//
317// Since global collector might destroy garbage arbitrarily late in the future, some skip list
318// methods have `K: 'static` and `V: 'static` bounds. But a local collector embedded in the skip
319// list would destroy all remaining garbage when the skip list is dropped, so in that case we'd be
320// able to remove those bounds on types `K` and `V`.
321//
322// As a further future optimization, if `!mem::needs_drop::<K>() && !mem::needs_drop::<V>()`
323// (neither key nor the value have destructors), there's no point in creating a new local
324// collector, so we should simply use the global one.
325pub struct SkipList<K, V> {
326 /// The head of the skip list (just a dummy node, not a real entry).
327 head: Head<K, V>,
328
329 /// The `Collector` associated with this skip list.
330 collector: Collector,
331
332 /// Hot data associated with the skip list, stored in a dedicated cache line.
333 hot_data: CachePadded<HotData>,
334}
335
336unsafe impl<K: Send + Sync, V: Send + Sync> Send for SkipList<K, V> {}
337unsafe impl<K: Send + Sync, V: Send + Sync> Sync for SkipList<K, V> {}
338
339impl<K, V> SkipList<K, V> {
340 /// Returns a new, empty skip list.
341 pub fn new(collector: Collector) -> Self {
342 Self {
343 head: Head::new(),
344 collector,
345 hot_data: CachePadded::new(HotData {
346 seed: AtomicUsize::new(1),
347 len: AtomicUsize::new(0),
348 max_height: AtomicUsize::new(1),
349 }),
350 }
351 }
352
353 /// Returns `true` if the skip list is empty.
354 pub fn is_empty(&self) -> bool {
355 self.len() == 0
356 }
357
358 /// Returns the number of entries in the skip list.
359 ///
360 /// If the skip list is being concurrently modified, consider the returned number just an
361 /// approximation without any guarantees.
362 pub fn len(&self) -> usize {
363 let len = self.hot_data.len.load(Ordering::Relaxed);
364
365 // Due to the relaxed memory ordering, the length counter may sometimes
366 // underflow and produce a very large value. We treat such values as 0.
367 if len > isize::max_value() as usize {
368 0
369 } else {
370 len
371 }
372 }
373
374 /// Ensures that all `Guard`s used with the skip list come from the same
375 /// `Collector`.
376 fn check_guard(&self, guard: &Guard) {
377 if let Some(c) = guard.collector() {
378 assert!(c == &self.collector);
379 }
380 }
381}
382
383impl<K, V> SkipList<K, V>
384where
385 K: Ord,
386{
387 /// Returns the entry with the smallest key.
388 pub fn front<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>> {
389 self.check_guard(guard);
390 let n = self.next_node(&self.head, Bound::Unbounded, guard)?;
391 Some(Entry {
392 parent: self,
393 node: n,
394 guard,
395 })
396 }
397
398 /// Returns the entry with the largest key.
399 pub fn back<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>> {
400 self.check_guard(guard);
401 let n = self.search_bound(Bound::Unbounded, true, guard)?;
402 Some(Entry {
403 parent: self,
404 node: n,
405 guard,
406 })
407 }
408
409 /// Returns `true` if the map contains a value for the specified key.
410 pub fn contains_key<Q>(&self, key: &Q, guard: &Guard) -> bool
411 where
412 K: Borrow<Q>,
413 Q: Ord + ?Sized,
414 {
415 self.get(key, guard).is_some()
416 }
417
418 /// Returns an entry with the specified `key`.
419 pub fn get<'a: 'g, 'g, Q>(&'a self, key: &Q, guard: &'g Guard) -> Option<Entry<'a, 'g, K, V>>
420 where
421 K: Borrow<Q>,
422 Q: Ord + ?Sized,
423 {
424 self.check_guard(guard);
425 let n = self.search_bound(Bound::Included(key), false, guard)?;
426 if n.key.borrow() != key {
427 return None;
428 }
429 Some(Entry {
430 parent: self,
431 node: n,
432 guard,
433 })
434 }
435
436 /// Returns an `Entry` pointing to the lowest element whose key is above
437 /// the given bound. If no such element is found then `None` is
438 /// returned.
439 pub fn lower_bound<'a: 'g, 'g, Q>(
440 &'a self,
441 bound: Bound<&Q>,
442 guard: &'g Guard,
443 ) -> Option<Entry<'a, 'g, K, V>>
444 where
445 K: Borrow<Q>,
446 Q: Ord + ?Sized,
447 {
448 self.check_guard(guard);
449 let n = self.search_bound(bound, false, guard)?;
450 Some(Entry {
451 parent: self,
452 node: n,
453 guard,
454 })
455 }
456
457 /// Returns an `Entry` pointing to the highest element whose key is below
458 /// the given bound. If no such element is found then `None` is
459 /// returned.
460 pub fn upper_bound<'a: 'g, 'g, Q>(
461 &'a self,
462 bound: Bound<&Q>,
463 guard: &'g Guard,
464 ) -> Option<Entry<'a, 'g, K, V>>
465 where
466 K: Borrow<Q>,
467 Q: Ord + ?Sized,
468 {
469 self.check_guard(guard);
470 let n = self.search_bound(bound, true, guard)?;
471 Some(Entry {
472 parent: self,
473 node: n,
474 guard,
475 })
476 }
477
478 /// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist.
479 pub fn get_or_insert(&self, key: K, value: V, guard: &Guard) -> RefEntry<'_, K, V> {
480 self.insert_internal(key, || value, |_| false, guard)
481 }
482
483 /// Finds an entry with the specified key, or inserts a new `key`-`value` pair if none exist,
484 /// where value is calculated with a function.
485 ///
486 ///
487 /// <b>Note:</b> Another thread may write key value first, leading to the result of this closure
488 /// discarded. If closure is modifying some other state (such as shared counters or shared
489 /// objects), it may lead to <u>undesired behaviour</u> such as counters being changed without
490 /// result of closure inserted
491 pub fn get_or_insert_with<F>(&self, key: K, value: F, guard: &Guard) -> RefEntry<'_, K, V>
492 where
493 F: FnOnce() -> V,
494 {
495 self.insert_internal(key, value, |_| false, guard)
496 }
497
498 /// Returns an iterator over all entries in the skip list.
499 pub fn iter<'a: 'g, 'g>(&'a self, guard: &'g Guard) -> Iter<'a, 'g, K, V> {
500 self.check_guard(guard);
501 Iter {
502 parent: self,
503 head: None,
504 tail: None,
505 guard,
506 }
507 }
508
509 /// Returns an iterator over all entries in the skip list.
510 pub fn ref_iter(&self) -> RefIter<'_, K, V> {
511 RefIter {
512 parent: self,
513 head: None,
514 tail: None,
515 }
516 }
517
518 /// Returns an iterator over a subset of entries in the skip list.
519 pub fn range<'a: 'g, 'g, Q, R>(
520 &'a self,
521 range: R,
522 guard: &'g Guard,
523 ) -> Range<'a, 'g, Q, R, K, V>
524 where
525 K: Borrow<Q>,
526 R: RangeBounds<Q>,
527 Q: Ord + ?Sized,
528 {
529 self.check_guard(guard);
530 Range {
531 parent: self,
532 head: None,
533 tail: None,
534 range,
535 guard,
536 _marker: PhantomData,
537 }
538 }
539
540 /// Returns an iterator over a subset of entries in the skip list.
541 #[allow(clippy::needless_lifetimes)]
542 pub fn ref_range<'a, Q, R>(&'a self, range: R) -> RefRange<'a, Q, R, K, V>
543 where
544 K: Borrow<Q>,
545 R: RangeBounds<Q>,
546 Q: Ord + ?Sized,
547 {
548 RefRange {
549 parent: self,
550 range,
551 head: None,
552 tail: None,
553 _marker: PhantomData,
554 }
555 }
556
557 /// Generates a random height and returns it.
558 fn random_height(&self) -> usize {
559 // Pseudorandom number generation from "Xorshift RNGs" by George Marsaglia.
560 //
561 // This particular set of operations generates 32-bit integers. See:
562 // https://en.wikipedia.org/wiki/Xorshift#Example_implementation
563 let mut num = self.hot_data.seed.load(Ordering::Relaxed);
564 num ^= num << 13;
565 num ^= num >> 17;
566 num ^= num << 5;
567 self.hot_data.seed.store(num, Ordering::Relaxed);
568
569 let mut height = cmp::min(MAX_HEIGHT, num.trailing_zeros() as usize + 1);
570 unsafe {
571 // Keep decreasing the height while it's much larger than all towers currently in the
572 // skip list.
573 //
574 // Note that we're loading the pointer only to check whether it is null, so it's okay
575 // to use `epoch::unprotected()` in this situation.
576 while height >= 4
577 && self.head[height - 2]
578 .load(Ordering::Relaxed, epoch::unprotected())
579 .is_null()
580 {
581 height -= 1;
582 }
583 }
584
585 // Track the max height to speed up lookups
586 let mut max_height = self.hot_data.max_height.load(Ordering::Relaxed);
587 while height > max_height {
588 match self.hot_data.max_height.compare_exchange_weak(
589 max_height,
590 height,
591 Ordering::Relaxed,
592 Ordering::Relaxed,
593 ) {
594 Ok(_) => break,
595 Err(h) => max_height = h,
596 }
597 }
598 height
599 }
600
601 /// If we encounter a deleted node while searching, help with the deletion
602 /// by attempting to unlink the node from the list.
603 ///
604 /// If the unlinking is successful then this function returns the next node
605 /// with which the search should continue on the current level.
606 #[cold]
607 unsafe fn help_unlink<'a>(
608 &'a self,
609 pred: &'a Atomic<Node<K, V>>,
610 curr: &'a Node<K, V>,
611 succ: Shared<'a, Node<K, V>>,
612 guard: &'a Guard,
613 ) -> Option<Shared<'a, Node<K, V>>> {
614 // If `succ` is marked, that means `curr` is removed. Let's try
615 // unlinking it from the skip list at this level.
616 match pred.compare_exchange(
617 Shared::from(curr as *const _),
618 succ.with_tag(0),
619 Ordering::Release,
620 Ordering::Relaxed,
621 guard,
622 ) {
623 Ok(_) => {
624 unsafe { curr.decrement(guard) }
625 Some(succ.with_tag(0))
626 }
627 Err(_) => None,
628 }
629 }
630
631 /// Returns the successor of a node.
632 ///
633 /// This will keep searching until a non-deleted node is found. If a deleted
634 /// node is reached then a search is performed using the given key.
635 fn next_node<'a>(
636 &'a self,
637 pred: &'a Tower<K, V>,
638 lower_bound: Bound<&K>,
639 guard: &'a Guard,
640 ) -> Option<&'a Node<K, V>> {
641 unsafe {
642 // Load the level 0 successor of the current node.
643 let mut curr = pred[0].load_consume(guard);
644
645 // If `curr` is marked, that means `pred` is removed and we have to use
646 // a key search.
647 if curr.tag() == 1 {
648 return self.search_bound(lower_bound, false, guard);
649 }
650
651 while let Some(c) = curr.as_ref() {
652 let succ = c.tower[0].load_consume(guard);
653
654 if succ.tag() == 1 {
655 if let Some(c) = self.help_unlink(&pred[0], c, succ, guard) {
656 // On success, continue searching through the current level.
657 curr = c;
658 continue;
659 } else {
660 // On failure, we cannot do anything reasonable to continue
661 // searching from the current position. Restart the search.
662 return self.search_bound(lower_bound, false, guard);
663 }
664 }
665
666 return Some(c);
667 }
668
669 None
670 }
671 }
672
673 /// Searches for first/last node that is greater/less/equal to a key in the skip list.
674 ///
675 /// If `upper_bound == true`: the last node less than (or equal to) the key.
676 ///
677 /// If `upper_bound == false`: the first node greater than (or equal to) the key.
678 ///
679 /// This is unsafe because the returned nodes are bound to the lifetime of
680 /// the `SkipList`, not the `Guard`.
681 fn search_bound<'a, Q>(
682 &'a self,
683 bound: Bound<&Q>,
684 upper_bound: bool,
685 guard: &'a Guard,
686 ) -> Option<&'a Node<K, V>>
687 where
688 K: Borrow<Q>,
689 Q: Ord + ?Sized,
690 {
691 unsafe {
692 'search: loop {
693 // The current level we're at.
694 let mut level = self.hot_data.max_height.load(Ordering::Relaxed);
695
696 // Fast loop to skip empty tower levels.
697 while level >= 1
698 && self.head[level - 1]
699 .load(Ordering::Relaxed, guard)
700 .is_null()
701 {
702 level -= 1;
703 }
704
705 // The current best node
706 let mut result = None;
707
708 // The predecessor node
709 let mut pred = &*self.head;
710
711 while level >= 1 {
712 level -= 1;
713
714 // Two adjacent nodes at the current level.
715 let mut curr = pred[level].load_consume(guard);
716
717 // If `curr` is marked, that means `pred` is removed and we have to restart the
718 // search.
719 if curr.tag() == 1 {
720 continue 'search;
721 }
722
723 // Iterate through the current level until we reach a node with a key greater
724 // than or equal to `key`.
725 while let Some(c) = curr.as_ref() {
726 let succ = c.tower[level].load_consume(guard);
727
728 if succ.tag() == 1 {
729 if let Some(c) = self.help_unlink(&pred[level], c, succ, guard) {
730 // On success, continue searching through the current level.
731 curr = c;
732 continue;
733 } else {
734 // On failure, we cannot do anything reasonable to continue
735 // searching from the current position. Restart the search.
736 continue 'search;
737 }
738 }
739
740 // If `curr` contains a key that is greater than (or equal) to `key`, we're
741 // done with this level.
742 //
743 // The condition determines whether we should stop the search. For the upper
744 // bound, we return the last node before the condition became true. For the
745 // lower bound, we return the first node after the condition became true.
746 if upper_bound {
747 if !below_upper_bound(&bound, c.key.borrow()) {
748 break;
749 }
750 result = Some(c);
751 } else if above_lower_bound(&bound, c.key.borrow()) {
752 result = Some(c);
753 break;
754 }
755
756 // Move one step forward.
757 pred = &c.tower;
758 curr = succ;
759 }
760 }
761
762 return result;
763 }
764 }
765 }
766
767 /// Searches for a key in the skip list and returns a list of all adjacent nodes.
768 fn search_position<'a, Q>(&'a self, key: &Q, guard: &'a Guard) -> Position<'a, K, V>
769 where
770 K: Borrow<Q>,
771 Q: Ord + ?Sized,
772 {
773 unsafe {
774 'search: loop {
775 // The result of this search.
776 let mut result = Position {
777 found: None,
778 left: [&*self.head; MAX_HEIGHT],
779 right: [Shared::null(); MAX_HEIGHT],
780 };
781
782 // The current level we're at.
783 let mut level = self.hot_data.max_height.load(Ordering::Relaxed);
784
785 // Fast loop to skip empty tower levels.
786 while level >= 1
787 && self.head[level - 1]
788 .load(Ordering::Relaxed, guard)
789 .is_null()
790 {
791 level -= 1;
792 }
793
794 // The predecessor node
795 let mut pred = &*self.head;
796
797 while level >= 1 {
798 level -= 1;
799
800 // Two adjacent nodes at the current level.
801 let mut curr = pred[level].load_consume(guard);
802
803 // If `curr` is marked, that means `pred` is removed and we have to restart the
804 // search.
805 if curr.tag() == 1 {
806 continue 'search;
807 }
808
809 // Iterate through the current level until we reach a node with a key greater
810 // than or equal to `key`.
811 while let Some(c) = curr.as_ref() {
812 let succ = c.tower[level].load_consume(guard);
813
814 if succ.tag() == 1 {
815 if let Some(c) = self.help_unlink(&pred[level], c, succ, guard) {
816 // On success, continue searching through the current level.
817 curr = c;
818 continue;
819 } else {
820 // On failure, we cannot do anything reasonable to continue
821 // searching from the current position. Restart the search.
822 continue 'search;
823 }
824 }
825
826 // If `curr` contains a key that is greater than or equal to `key`, we're
827 // done with this level.
828 match c.key.borrow().cmp(key) {
829 cmp::Ordering::Greater => break,
830 cmp::Ordering::Equal => {
831 result.found = Some(c);
832 break;
833 }
834 cmp::Ordering::Less => {}
835 }
836
837 // Move one step forward.
838 pred = &c.tower;
839 curr = succ;
840 }
841
842 // Store the position at the current level into the result.
843 result.left[level] = pred;
844 result.right[level] = curr;
845 }
846
847 return result;
848 }
849 }
850 }
851
852 /// Inserts an entry with the specified `key` and `value`.
853 ///
854 /// If `replace` is `true`, then any existing entry with this key will first be removed.
855 fn insert_internal<F, CompareF>(
856 &self,
857 key: K,
858 value: F,
859 replace: CompareF,
860 guard: &Guard,
861 ) -> RefEntry<'_, K, V>
862 where
863 F: FnOnce() -> V,
864 CompareF: Fn(&V) -> bool,
865 {
866 self.check_guard(guard);
867
868 unsafe {
869 // Rebind the guard to the lifetime of self. This is a bit of a
870 // hack but it allows us to return references that are not bound to
871 // the lifetime of the guard.
872 let guard = &*(guard as *const _);
873
874 let mut search;
875 loop {
876 // First try searching for the key.
877 // Note that the `Ord` implementation for `K` may panic during the search.
878 search = self.search_position(&key, guard);
879
880 let r = match search.found {
881 Some(r) => r,
882 None => break,
883 };
884 let replace = replace(&r.value);
885 if replace {
886 // If a node with the key was found and we should replace it, mark its tower
887 // and then repeat the search.
888 if r.mark_tower() {
889 self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
890 }
891 } else {
892 // If a node with the key was found and we're not going to replace it, let's
893 // try returning it as an entry.
894 if let Some(e) = RefEntry::try_acquire(self, r) {
895 return e;
896 }
897
898 // If we couldn't increment the reference count, that means someone has just
899 // now removed the node.
900 break;
901 }
902 }
903
904 // create value before creating node, so extra allocation doesn't happen if value() function panics
905 let value = value();
906 // Create a new node.
907 let height = self.random_height();
908 let (node, n) = {
909 // The reference count is initially two to account for:
910 // 1. The entry that will be returned.
911 // 2. The link at the level 0 of the tower.
912 let n = Node::<K, V>::alloc(height, 2);
913
914 // Write the key and the value into the node.
915 ptr::addr_of_mut!((*n).key).write(key);
916 ptr::addr_of_mut!((*n).value).write(value);
917
918 (Shared::<Node<K, V>>::from(n as *const _), &*n)
919 };
920
921 // Optimistically increment `len`.
922 self.hot_data.len.fetch_add(1, Ordering::Relaxed);
923
924 loop {
925 // Set the lowest successor of `n` to `search.right[0]`.
926 n.tower[0].store(search.right[0], Ordering::Relaxed);
927
928 // Try installing the new node into the skip list (at level 0).
929 // TODO(Amanieu): can we use release ordering here?
930 if search.left[0][0]
931 .compare_exchange(
932 search.right[0],
933 node,
934 Ordering::SeqCst,
935 Ordering::SeqCst,
936 guard,
937 )
938 .is_ok()
939 {
940 break;
941 }
942
943 // We failed. Let's search for the key and try again.
944 {
945 // Create a guard that destroys the new node in case search panics.
946 struct ScopeGuard<K, V>(*const Node<K, V>);
947 impl<K, V> Drop for ScopeGuard<K, V> {
948 fn drop(&mut self) {
949 unsafe { Node::finalize(self.0) }
950 }
951 }
952 let sg = ScopeGuard(node.as_raw());
953 search = self.search_position(&n.key, guard);
954 mem::forget(sg);
955 }
956
957 if let Some(r) = search.found {
958 let replace = replace(&r.value);
959 if replace {
960 // If a node with the key was found and we should replace it, mark its
961 // tower and then repeat the search.
962 if r.mark_tower() {
963 self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
964 }
965 } else {
966 // If a node with the key was found and we're not going to replace it,
967 // let's try returning it as an entry.
968 if let Some(e) = RefEntry::try_acquire(self, r) {
969 // Destroy the new node.
970 Node::finalize(node.as_raw());
971 self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
972
973 return e;
974 }
975
976 // If we couldn't increment the reference count, that means someone has
977 // just now removed the node.
978 }
979 }
980 }
981
982 // The new node was successfully installed. Let's create an entry associated with it.
983 let entry = RefEntry {
984 parent: self,
985 node: n,
986 };
987
988 // Build the rest of the tower above level 0.
989 'build: for level in 1..height {
990 loop {
991 // Obtain the predecessor and successor at the current level.
992 let pred = search.left[level];
993 let succ = search.right[level];
994
995 // Load the current value of the pointer in the tower at this level.
996 // TODO(Amanieu): can we use relaxed ordering here?
997 let next = n.tower[level].load(Ordering::SeqCst, guard);
998
999 // If the current pointer is marked, that means another thread is already
1000 // removing the node we've just inserted. In that case, let's just stop
1001 // building the tower.
1002 if next.tag() == 1 {
1003 break 'build;
1004 }
1005
1006 // When searching for `key` and traversing the skip list from the highest level
1007 // to the lowest, it is possible to observe a node with an equal key at higher
1008 // levels and then find it missing at the lower levels if it gets removed
1009 // during traversal. Even worse, it is possible to observe completely different
1010 // nodes with the exact same key at different levels.
1011 //
1012 // Linking the new node to a dead successor with an equal key could create
1013 // subtle corner cases that would require special care. It's much easier to
1014 // simply prohibit linking two nodes with equal keys.
1015 //
1016 // If the successor has the same key as the new node, that means it is marked
1017 // as removed and should be unlinked from the skip list. In that case, let's
1018 // repeat the search to make sure it gets unlinked and try again.
1019 //
1020 // If this comparison or the following search panics, we simply stop building
1021 // the tower without breaking any invariants. Note that building higher levels
1022 // is completely optional. Only the lowest level really matters, and all the
1023 // higher levels are there just to make searching faster.
1024 if succ.as_ref().map(|s| &s.key) == Some(&n.key) {
1025 search = self.search_position(&n.key, guard);
1026 continue;
1027 }
1028
1029 // Change the pointer at the current level from `next` to `succ`. If this CAS
1030 // operation fails, that means another thread has marked the pointer and we
1031 // should stop building the tower.
1032 // TODO(Amanieu): can we use release ordering here?
1033 if n.tower[level]
1034 .compare_exchange(next, succ, Ordering::SeqCst, Ordering::SeqCst, guard)
1035 .is_err()
1036 {
1037 break 'build;
1038 }
1039
1040 // Increment the reference count. The current value will always be at least 1
1041 // because we are holding `entry`.
1042 n.refs_and_height
1043 .fetch_add(1 << HEIGHT_BITS, Ordering::Relaxed);
1044
1045 // Try installing the new node at the current level.
1046 // TODO(Amanieu): can we use release ordering here?
1047 if pred[level]
1048 .compare_exchange(succ, node, Ordering::SeqCst, Ordering::SeqCst, guard)
1049 .is_ok()
1050 {
1051 // Success! Continue on the next level.
1052 break;
1053 }
1054
1055 // Installation failed. Decrement the reference count.
1056 n.refs_and_height
1057 .fetch_sub(1 << HEIGHT_BITS, Ordering::Relaxed);
1058
1059 // We don't have the most up-to-date search results. Repeat the search.
1060 //
1061 // If this search panics, we simply stop building the tower without breaking
1062 // any invariants. Note that building higher levels is completely optional.
1063 // Only the lowest level really matters, and all the higher levels are there
1064 // just to make searching faster.
1065 search = self.search_position(&n.key, guard);
1066 }
1067 }
1068
1069 // If any pointer in the tower is marked, that means our node is in the process of
1070 // removal or already removed. It is possible that another thread (either partially or
1071 // completely) removed the new node while we were building the tower, and just after
1072 // that we installed the new node at one of the higher levels. In order to undo that
1073 // installation, we must repeat the search, which will unlink the new node at that
1074 // level.
1075 // TODO(Amanieu): can we use relaxed ordering here?
1076 if n.tower[height - 1].load(Ordering::SeqCst, guard).tag() == 1 {
1077 self.search_bound(Bound::Included(&n.key), false, guard);
1078 }
1079
1080 // Finally, return the new entry.
1081 entry
1082 }
1083 }
1084}
1085
1086impl<K, V> SkipList<K, V>
1087where
1088 K: Ord + Send + 'static,
1089 V: Send + 'static,
1090{
1091 /// Inserts a `key`-`value` pair into the skip list and returns the new entry.
1092 ///
1093 /// If there is an existing entry with this key, it will be removed before inserting the new
1094 /// one.
1095 pub fn insert(&self, key: K, value: V, guard: &Guard) -> RefEntry<'_, K, V> {
1096 self.insert_internal(key, || value, |_| true, guard)
1097 }
1098
1099 /// Inserts a `key`-`value` pair into the skip list and returns the new entry.
1100 ///
1101 /// If there is an existing entry with this key and compare(entry.value) returns true,
1102 /// it will be removed before inserting the new one.
1103 /// The closure will not be called if the key is not present.
1104 pub fn compare_insert<F>(
1105 &self,
1106 key: K,
1107 value: V,
1108 compare_fn: F,
1109 guard: &Guard,
1110 ) -> RefEntry<'_, K, V>
1111 where
1112 F: Fn(&V) -> bool,
1113 {
1114 self.insert_internal(key, || value, compare_fn, guard)
1115 }
1116
1117 /// Removes an entry with the specified `key` from the map and returns it.
1118 pub fn remove<Q>(&self, key: &Q, guard: &Guard) -> Option<RefEntry<'_, K, V>>
1119 where
1120 K: Borrow<Q>,
1121 Q: Ord + ?Sized,
1122 {
1123 self.check_guard(guard);
1124
1125 unsafe {
1126 // Rebind the guard to the lifetime of self. This is a bit of a
1127 // hack but it allows us to return references that are not bound to
1128 // the lifetime of the guard.
1129 let guard = &*(guard as *const _);
1130
1131 loop {
1132 // Try searching for the key.
1133 let search = self.search_position(key, guard);
1134
1135 let n = search.found?;
1136
1137 // First try incrementing the reference count because we have to return the node as
1138 // an entry. If this fails, repeat the search.
1139 let entry = match RefEntry::try_acquire(self, n) {
1140 Some(e) => e,
1141 None => continue,
1142 };
1143
1144 // Try removing the node by marking its tower.
1145 if n.mark_tower() {
1146 // Success! Decrement `len`.
1147 self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
1148
1149 // Unlink the node at each level of the skip list. We could do this by simply
1150 // repeating the search, but it's usually faster to unlink it manually using
1151 // the `left` and `right` lists.
1152 for level in (0..n.height()).rev() {
1153 // TODO(Amanieu): can we use relaxed ordering here?
1154 let succ = n.tower[level].load(Ordering::SeqCst, guard).with_tag(0);
1155
1156 // Try linking the predecessor and successor at this level.
1157 // TODO(Amanieu): can we use release ordering here?
1158 if search.left[level][level]
1159 .compare_exchange(
1160 Shared::from(n as *const _),
1161 succ,
1162 Ordering::SeqCst,
1163 Ordering::SeqCst,
1164 guard,
1165 )
1166 .is_ok()
1167 {
1168 // Success! Decrement the reference count.
1169 n.decrement(guard);
1170 } else {
1171 // Failed! Just repeat the search to completely unlink the node.
1172 self.search_bound(Bound::Included(key), false, guard);
1173 break;
1174 }
1175 }
1176 }
1177 return Some(entry);
1178 }
1179 }
1180 }
1181
1182 /// Removes an entry from the front of the skip list.
1183 pub fn pop_front(&self, guard: &Guard) -> Option<RefEntry<'_, K, V>> {
1184 self.check_guard(guard);
1185 loop {
1186 let e = self.front(guard)?;
1187 if let Some(e) = e.pin() {
1188 if e.remove(guard) {
1189 return Some(e);
1190 } else {
1191 e.release(guard);
1192 }
1193 }
1194 }
1195 }
1196
1197 /// Removes an entry from the back of the skip list.
1198 pub fn pop_back(&self, guard: &Guard) -> Option<RefEntry<'_, K, V>> {
1199 self.check_guard(guard);
1200 loop {
1201 let e = self.back(guard)?;
1202 if let Some(e) = e.pin() {
1203 if e.remove(guard) {
1204 return Some(e);
1205 } else {
1206 e.release(guard);
1207 }
1208 }
1209 }
1210 }
1211
1212 /// Iterates over the map and removes every entry.
1213 pub fn clear(&self, guard: &mut Guard) {
1214 self.check_guard(guard);
1215
1216 /// Number of steps after which we repin the current thread and unlink removed nodes.
1217 const BATCH_SIZE: usize = 100;
1218
1219 loop {
1220 {
1221 // Search for the first entry in order to unlink all the preceding entries
1222 // we have removed.
1223 //
1224 // By unlinking nodes in batches we make sure that the final search doesn't
1225 // unlink all nodes at once, which could keep the current thread pinned for a
1226 // long time.
1227 let mut entry = self.lower_bound(Bound::Unbounded, guard);
1228
1229 for _ in 0..BATCH_SIZE {
1230 // Stop if we have reached the end of the list.
1231 let e = match entry {
1232 None => return,
1233 Some(e) => e,
1234 };
1235
1236 // Before removing the current entry, first obtain the following one.
1237 let next = e.next();
1238
1239 // Try removing the current entry.
1240 if e.node.mark_tower() {
1241 // Success! Decrement `len`.
1242 self.hot_data.len.fetch_sub(1, Ordering::Relaxed);
1243 }
1244
1245 entry = next;
1246 }
1247 }
1248
1249 // Repin the current thread because we don't want to keep it pinned in the same
1250 // epoch for a too long time.
1251 guard.repin();
1252 }
1253 }
1254}
1255
1256impl<K, V> Drop for SkipList<K, V> {
1257 fn drop(&mut self) {
1258 unsafe {
1259 let mut node = self.head[0]
1260 .load(Ordering::Relaxed, epoch::unprotected())
1261 .as_ref();
1262
1263 // Iterate through the whole skip list and destroy every node.
1264 while let Some(n) = node {
1265 // Unprotected loads are okay because this function is the only one currently using
1266 // the skip list.
1267 let next = n.tower[0]
1268 .load(Ordering::Relaxed, epoch::unprotected())
1269 .as_ref();
1270
1271 // Deallocate every node.
1272 Node::finalize(n);
1273
1274 node = next;
1275 }
1276 }
1277 }
1278}
1279
1280impl<K, V> fmt::Debug for SkipList<K, V>
1281where
1282 K: Ord + fmt::Debug,
1283 V: fmt::Debug,
1284{
1285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1286 f.pad("SkipList { .. }")
1287 }
1288}
1289
1290impl<K, V> IntoIterator for SkipList<K, V> {
1291 type Item = (K, V);
1292 type IntoIter = IntoIter<K, V>;
1293
1294 fn into_iter(self) -> IntoIter<K, V> {
1295 unsafe {
1296 // Load the front node.
1297 //
1298 // Unprotected loads are okay because this function is the only one currently using
1299 // the skip list.
1300 let front = self.head[0]
1301 .load(Ordering::Relaxed, epoch::unprotected())
1302 .as_raw();
1303
1304 // Clear the skip list by setting all pointers in head to null.
1305 for level in 0..MAX_HEIGHT {
1306 self.head[level].store(Shared::null(), Ordering::Relaxed);
1307 }
1308
1309 IntoIter {
1310 node: front as *mut Node<K, V>,
1311 }
1312 }
1313 }
1314}
1315
1316/// An entry in a skip list, protected by a `Guard`.
1317///
1318/// The lifetimes of the key and value are the same as that of the `Guard`
1319/// used when creating the `Entry` (`'g`). This lifetime is also constrained to
1320/// not outlive the `SkipList`.
1321pub struct Entry<'a: 'g, 'g, K, V> {
1322 parent: &'a SkipList<K, V>,
1323 node: &'g Node<K, V>,
1324 guard: &'g Guard,
1325}
1326
1327impl<'a: 'g, 'g, K: 'a, V: 'a> Entry<'a, 'g, K, V> {
1328 /// Returns `true` if the entry is removed from the skip list.
1329 pub fn is_removed(&self) -> bool {
1330 self.node.is_removed()
1331 }
1332
1333 /// Returns a reference to the key.
1334 pub fn key(&self) -> &'g K {
1335 &self.node.key
1336 }
1337
1338 /// Returns a reference to the value.
1339 pub fn value(&self) -> &'g V {
1340 &self.node.value
1341 }
1342
1343 /// Returns a reference to the parent `SkipList`
1344 pub fn skiplist(&self) -> &'a SkipList<K, V> {
1345 self.parent
1346 }
1347
1348 /// Attempts to pin the entry with a reference count, ensuring that it
1349 /// remains accessible even after the `Guard` is dropped.
1350 ///
1351 /// This method may return `None` if the reference count is already 0 and
1352 /// the node has been queued for deletion.
1353 pub fn pin(&self) -> Option<RefEntry<'a, K, V>> {
1354 unsafe { RefEntry::try_acquire(self.parent, self.node) }
1355 }
1356}
1357
1358impl<K, V> Entry<'_, '_, K, V>
1359where
1360 K: Ord + Send + 'static,
1361 V: Send + 'static,
1362{
1363 /// Removes the entry from the skip list.
1364 ///
1365 /// Returns `true` if this call removed the entry and `false` if it was already removed.
1366 pub fn remove(&self) -> bool {
1367 // Try marking the tower.
1368 if self.node.mark_tower() {
1369 // Success - the entry is removed. Now decrement `len`.
1370 self.parent.hot_data.len.fetch_sub(1, Ordering::Relaxed);
1371
1372 // Search for the key to unlink the node from the skip list.
1373 self.parent
1374 .search_bound(Bound::Included(&self.node.key), false, self.guard);
1375
1376 true
1377 } else {
1378 false
1379 }
1380 }
1381}
1382
1383impl<K, V> Clone for Entry<'_, '_, K, V> {
1384 fn clone(&self) -> Self {
1385 Self {
1386 parent: self.parent,
1387 node: self.node,
1388 guard: self.guard,
1389 }
1390 }
1391}
1392
1393impl<K, V> fmt::Debug for Entry<'_, '_, K, V>
1394where
1395 K: fmt::Debug,
1396 V: fmt::Debug,
1397{
1398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1399 f.debug_tuple("Entry")
1400 .field(self.key())
1401 .field(self.value())
1402 .finish()
1403 }
1404}
1405
1406impl<'a: 'g, 'g, K, V> Entry<'a, 'g, K, V>
1407where
1408 K: Ord,
1409{
1410 /// Moves to the next entry in the skip list.
1411 pub fn move_next(&mut self) -> bool {
1412 match self.next() {
1413 None => false,
1414 Some(n) => {
1415 *self = n;
1416 true
1417 }
1418 }
1419 }
1420
1421 /// Returns the next entry in the skip list.
1422 pub fn next(&self) -> Option<Entry<'a, 'g, K, V>> {
1423 let n = self.parent.next_node(
1424 &self.node.tower,
1425 Bound::Excluded(&self.node.key),
1426 self.guard,
1427 )?;
1428 Some(Entry {
1429 parent: self.parent,
1430 node: n,
1431 guard: self.guard,
1432 })
1433 }
1434
1435 /// Moves to the previous entry in the skip list.
1436 pub fn move_prev(&mut self) -> bool {
1437 match self.prev() {
1438 None => false,
1439 Some(n) => {
1440 *self = n;
1441 true
1442 }
1443 }
1444 }
1445
1446 /// Returns the previous entry in the skip list.
1447 pub fn prev(&self) -> Option<Entry<'a, 'g, K, V>> {
1448 let n = self
1449 .parent
1450 .search_bound(Bound::Excluded(&self.node.key), true, self.guard)?;
1451 Some(Entry {
1452 parent: self.parent,
1453 node: n,
1454 guard: self.guard,
1455 })
1456 }
1457}
1458
1459/// A reference-counted entry in a skip list.
1460///
1461/// You *must* call `release` to free this type, otherwise the node will be
1462/// leaked. This is because releasing the entry requires a `Guard`.
1463pub struct RefEntry<'a, K, V> {
1464 parent: &'a SkipList<K, V>,
1465 node: &'a Node<K, V>,
1466}
1467
1468impl<'a, K: 'a, V: 'a> RefEntry<'a, K, V> {
1469 /// Returns `true` if the entry is removed from the skip list.
1470 pub fn is_removed(&self) -> bool {
1471 self.node.is_removed()
1472 }
1473
1474 /// Returns a reference to the key.
1475 pub fn key(&self) -> &K {
1476 &self.node.key
1477 }
1478
1479 /// Returns a reference to the value.
1480 pub fn value(&self) -> &V {
1481 &self.node.value
1482 }
1483
1484 /// Returns a reference to the parent `SkipList`
1485 pub fn skiplist(&self) -> &'a SkipList<K, V> {
1486 self.parent
1487 }
1488
1489 /// Releases the reference on the entry.
1490 pub fn release(self, guard: &Guard) {
1491 self.parent.check_guard(guard);
1492 unsafe { self.node.decrement(guard) }
1493 }
1494
1495 /// Releases the reference of the entry, pinning the thread only when
1496 /// the reference count of the node becomes 0.
1497 pub fn release_with_pin<F>(self, pin: F)
1498 where
1499 F: FnOnce() -> Guard,
1500 {
1501 unsafe { self.node.decrement_with_pin(self.parent, pin) }
1502 }
1503
1504 /// Tries to create a new `RefEntry` by incrementing the reference count of
1505 /// a node.
1506 unsafe fn try_acquire(
1507 parent: &'a SkipList<K, V>,
1508 node: &Node<K, V>,
1509 ) -> Option<RefEntry<'a, K, V>> {
1510 if unsafe { node.try_increment() } {
1511 Some(RefEntry {
1512 parent,
1513
1514 // We re-bind the lifetime of the node here to that of the skip
1515 // list since we now hold a reference to it.
1516 node: unsafe { &*(node as *const _) },
1517 })
1518 } else {
1519 None
1520 }
1521 }
1522}
1523
1524impl<K, V> RefEntry<'_, K, V>
1525where
1526 K: Ord + Send + 'static,
1527 V: Send + 'static,
1528{
1529 /// Removes the entry from the skip list.
1530 ///
1531 /// Returns `true` if this call removed the entry and `false` if it was already removed.
1532 pub fn remove(&self, guard: &Guard) -> bool {
1533 self.parent.check_guard(guard);
1534
1535 // Try marking the tower.
1536 if self.node.mark_tower() {
1537 // Success - the entry is removed. Now decrement `len`.
1538 self.parent.hot_data.len.fetch_sub(1, Ordering::Relaxed);
1539
1540 // Search for the key to unlink the node from the skip list.
1541 self.parent
1542 .search_bound(Bound::Included(&self.node.key), false, guard);
1543
1544 true
1545 } else {
1546 false
1547 }
1548 }
1549}
1550
1551impl<K, V> Clone for RefEntry<'_, K, V> {
1552 fn clone(&self) -> Self {
1553 unsafe {
1554 // Incrementing will always succeed since we're already holding a reference to the node.
1555 Node::try_increment(self.node);
1556 }
1557 Self {
1558 parent: self.parent,
1559 node: self.node,
1560 }
1561 }
1562}
1563
1564impl<K, V> fmt::Debug for RefEntry<'_, K, V>
1565where
1566 K: fmt::Debug,
1567 V: fmt::Debug,
1568{
1569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1570 f.debug_tuple("RefEntry")
1571 .field(self.key())
1572 .field(self.value())
1573 .finish()
1574 }
1575}
1576
1577impl<'a, K, V> RefEntry<'a, K, V>
1578where
1579 K: Ord,
1580{
1581 /// Moves to the next entry in the skip list.
1582 pub fn move_next(&mut self, guard: &Guard) -> bool {
1583 match self.next(guard) {
1584 None => false,
1585 Some(e) => {
1586 mem::replace(self, e).release(guard);
1587 true
1588 }
1589 }
1590 }
1591
1592 /// Returns the next entry in the skip list.
1593 pub fn next(&self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1594 self.parent.check_guard(guard);
1595 unsafe {
1596 let mut n = self.node;
1597 loop {
1598 n = self
1599 .parent
1600 .next_node(&n.tower, Bound::Excluded(&n.key), guard)?;
1601 if let Some(e) = RefEntry::try_acquire(self.parent, n) {
1602 return Some(e);
1603 }
1604 }
1605 }
1606 }
1607
1608 /// Moves to the previous entry in the skip list.
1609 pub fn move_prev(&mut self, guard: &Guard) -> bool {
1610 match self.prev(guard) {
1611 None => false,
1612 Some(e) => {
1613 mem::replace(self, e).release(guard);
1614 true
1615 }
1616 }
1617 }
1618
1619 /// Returns the previous entry in the skip list.
1620 pub fn prev(&self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1621 self.parent.check_guard(guard);
1622 unsafe {
1623 let mut n = self.node;
1624 loop {
1625 n = self
1626 .parent
1627 .search_bound(Bound::Excluded(&n.key), true, guard)?;
1628 if let Some(e) = RefEntry::try_acquire(self.parent, n) {
1629 return Some(e);
1630 }
1631 }
1632 }
1633 }
1634}
1635
1636/// An iterator over the entries of a `SkipList`.
1637pub struct Iter<'a: 'g, 'g, K, V> {
1638 parent: &'a SkipList<K, V>,
1639 head: Option<&'g Node<K, V>>,
1640 tail: Option<&'g Node<K, V>>,
1641 guard: &'g Guard,
1642}
1643
1644impl<'a: 'g, 'g, K: 'a, V: 'a> Iterator for Iter<'a, 'g, K, V>
1645where
1646 K: Ord,
1647{
1648 type Item = Entry<'a, 'g, K, V>;
1649
1650 fn next(&mut self) -> Option<Entry<'a, 'g, K, V>> {
1651 self.head = match self.head {
1652 Some(n) => self
1653 .parent
1654 .next_node(&n.tower, Bound::Excluded(&n.key), self.guard),
1655 None => self
1656 .parent
1657 .next_node(&self.parent.head, Bound::Unbounded, self.guard),
1658 };
1659 if let (Some(h), Some(t)) = (self.head, self.tail) {
1660 if h.key >= t.key {
1661 self.head = None;
1662 self.tail = None;
1663 }
1664 }
1665 self.head.map(|n| Entry {
1666 parent: self.parent,
1667 node: n,
1668 guard: self.guard,
1669 })
1670 }
1671}
1672
1673impl<'a: 'g, 'g, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, 'g, K, V>
1674where
1675 K: Ord,
1676{
1677 fn next_back(&mut self) -> Option<Entry<'a, 'g, K, V>> {
1678 self.tail = match self.tail {
1679 Some(n) => self
1680 .parent
1681 .search_bound(Bound::Excluded(&n.key), true, self.guard),
1682 None => self.parent.search_bound(Bound::Unbounded, true, self.guard),
1683 };
1684 if let (Some(h), Some(t)) = (self.head, self.tail) {
1685 if h.key >= t.key {
1686 self.head = None;
1687 self.tail = None;
1688 }
1689 }
1690 self.tail.map(|n| Entry {
1691 parent: self.parent,
1692 node: n,
1693 guard: self.guard,
1694 })
1695 }
1696}
1697
1698impl<K, V> fmt::Debug for Iter<'_, '_, K, V>
1699where
1700 K: fmt::Debug,
1701 V: fmt::Debug,
1702{
1703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1704 f.debug_struct("Iter")
1705 .field("head", &self.head.map(|n| (&n.key, &n.value)))
1706 .field("tail", &self.tail.map(|n| (&n.key, &n.value)))
1707 .finish()
1708 }
1709}
1710
1711/// An iterator over reference-counted entries of a `SkipList`.
1712pub struct RefIter<'a, K, V> {
1713 parent: &'a SkipList<K, V>,
1714 head: Option<RefEntry<'a, K, V>>,
1715 tail: Option<RefEntry<'a, K, V>>,
1716}
1717
1718impl<K, V> fmt::Debug for RefIter<'_, K, V>
1719where
1720 K: fmt::Debug,
1721 V: fmt::Debug,
1722{
1723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1724 let mut d = f.debug_struct("RefIter");
1725 match &self.head {
1726 None => d.field("head", &None::<(&K, &V)>),
1727 Some(e) => d.field("head", &(e.key(), e.value())),
1728 };
1729 match &self.tail {
1730 None => d.field("tail", &None::<(&K, &V)>),
1731 Some(e) => d.field("tail", &(e.key(), e.value())),
1732 };
1733 d.finish()
1734 }
1735}
1736
1737impl<'a, K: 'a, V: 'a> RefIter<'a, K, V>
1738where
1739 K: Ord,
1740{
1741 /// Advances the iterator and returns the next value.
1742 pub fn next(&mut self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1743 self.parent.check_guard(guard);
1744 let next_head = match &self.head {
1745 Some(e) => e.next(guard),
1746 None => try_pin_loop(|| self.parent.front(guard)),
1747 };
1748 match (&next_head, &self.tail) {
1749 // The next key is larger than the latest tail key we observed with this iterator.
1750 (Some(ref next), Some(t)) if next.key() >= t.key() => {
1751 unsafe {
1752 next.node.decrement(guard);
1753 }
1754 None
1755 }
1756 (Some(_), _) => {
1757 if let Some(e) = mem::replace(&mut self.head, next_head.clone()) {
1758 unsafe {
1759 e.node.decrement(guard);
1760 }
1761 }
1762 next_head
1763 }
1764 (None, _) => None,
1765 }
1766 }
1767
1768 /// Removes and returns an element from the end of the iterator.
1769 pub fn next_back(&mut self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1770 self.parent.check_guard(guard);
1771 let next_tail = match &self.tail {
1772 Some(e) => e.prev(guard),
1773 None => try_pin_loop(|| self.parent.back(guard)),
1774 };
1775 match (&self.head, &next_tail) {
1776 // The prev key is smaller than the latest head key we observed with this iterator.
1777 (Some(h), Some(next)) if h.key() >= next.key() => {
1778 unsafe {
1779 next.node.decrement(guard);
1780 }
1781 None
1782 }
1783 (_, Some(_)) => {
1784 if let Some(e) = mem::replace(&mut self.tail, next_tail.clone()) {
1785 unsafe {
1786 e.node.decrement(guard);
1787 }
1788 }
1789 next_tail
1790 }
1791 (_, None) => None,
1792 }
1793 }
1794}
1795
1796impl<'a, K: 'a, V: 'a> RefIter<'a, K, V> {
1797 /// Decrements the reference count of `RefEntry` owned by the iterator.
1798 pub fn drop_impl(&mut self, guard: &Guard) {
1799 self.parent.check_guard(guard);
1800 if let Some(e) = self.head.take() {
1801 unsafe { e.node.decrement(guard) };
1802 }
1803 if let Some(e) = self.tail.take() {
1804 unsafe { e.node.decrement(guard) };
1805 }
1806 }
1807}
1808
1809/// An iterator over a subset of entries of a `SkipList`.
1810pub struct Range<'a: 'g, 'g, Q, R, K, V>
1811where
1812 K: Ord + Borrow<Q>,
1813 R: RangeBounds<Q>,
1814 Q: Ord + ?Sized,
1815{
1816 parent: &'a SkipList<K, V>,
1817 head: Option<&'g Node<K, V>>,
1818 tail: Option<&'g Node<K, V>>,
1819 range: R,
1820 guard: &'g Guard,
1821 _marker: PhantomData<fn() -> Q>, // covariant over `Q`
1822}
1823
1824impl<'a: 'g, 'g, Q, R, K: 'a, V: 'a> Iterator for Range<'a, 'g, Q, R, K, V>
1825where
1826 K: Ord + Borrow<Q>,
1827 R: RangeBounds<Q>,
1828 Q: Ord + ?Sized,
1829{
1830 type Item = Entry<'a, 'g, K, V>;
1831
1832 fn next(&mut self) -> Option<Entry<'a, 'g, K, V>> {
1833 self.head = match self.head {
1834 Some(n) => self
1835 .parent
1836 .next_node(&n.tower, Bound::Excluded(&n.key), self.guard),
1837 None => self
1838 .parent
1839 .search_bound(self.range.start_bound(), false, self.guard),
1840 };
1841 if let Some(h) = self.head {
1842 let bound = match self.tail {
1843 Some(t) => Bound::Excluded(t.key.borrow()),
1844 None => self.range.end_bound(),
1845 };
1846 if !below_upper_bound(&bound, h.key.borrow()) {
1847 self.head = None;
1848 self.tail = None;
1849 }
1850 }
1851 self.head.map(|n| Entry {
1852 parent: self.parent,
1853 node: n,
1854 guard: self.guard,
1855 })
1856 }
1857}
1858
1859impl<'a: 'g, 'g, Q, R, K: 'a, V: 'a> DoubleEndedIterator for Range<'a, 'g, Q, R, K, V>
1860where
1861 K: Ord + Borrow<Q>,
1862 R: RangeBounds<Q>,
1863 Q: Ord + ?Sized,
1864{
1865 fn next_back(&mut self) -> Option<Entry<'a, 'g, K, V>> {
1866 self.tail = match self.tail {
1867 Some(n) => self
1868 .parent
1869 .search_bound(Bound::Excluded(n.key.borrow()), true, self.guard),
1870 None => self
1871 .parent
1872 .search_bound(self.range.end_bound(), true, self.guard),
1873 };
1874 if let Some(t) = self.tail {
1875 let bound = match self.head {
1876 Some(h) => Bound::Excluded(h.key.borrow()),
1877 None => self.range.start_bound(),
1878 };
1879 if !above_lower_bound(&bound, t.key.borrow()) {
1880 self.head = None;
1881 self.tail = None;
1882 }
1883 }
1884 self.tail.map(|n| Entry {
1885 parent: self.parent,
1886 node: n,
1887 guard: self.guard,
1888 })
1889 }
1890}
1891
1892impl<Q, R, K, V> fmt::Debug for Range<'_, '_, Q, R, K, V>
1893where
1894 K: Ord + Borrow<Q> + fmt::Debug,
1895 V: fmt::Debug,
1896 R: RangeBounds<Q> + fmt::Debug,
1897 Q: Ord + ?Sized,
1898{
1899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1900 f.debug_struct("Range")
1901 .field("range", &self.range)
1902 .field("head", &self.head)
1903 .field("tail", &self.tail)
1904 .finish()
1905 }
1906}
1907
1908/// An iterator over reference-counted subset of entries of a `SkipList`.
1909pub struct RefRange<'a, Q, R, K, V>
1910where
1911 K: Ord + Borrow<Q>,
1912 R: RangeBounds<Q>,
1913 Q: Ord + ?Sized,
1914{
1915 parent: &'a SkipList<K, V>,
1916 pub(crate) head: Option<RefEntry<'a, K, V>>,
1917 pub(crate) tail: Option<RefEntry<'a, K, V>>,
1918 pub(crate) range: R,
1919 _marker: PhantomData<fn() -> Q>, // covariant over `Q`
1920}
1921
1922unsafe impl<Q, R, K, V> Send for RefRange<'_, Q, R, K, V>
1923where
1924 K: Ord + Borrow<Q>,
1925 R: RangeBounds<Q>,
1926 Q: Ord + ?Sized,
1927{
1928}
1929
1930unsafe impl<Q, R, K, V> Sync for RefRange<'_, Q, R, K, V>
1931where
1932 K: Ord + Borrow<Q>,
1933 R: RangeBounds<Q>,
1934 Q: Ord + ?Sized,
1935{
1936}
1937
1938impl<Q, R, K, V> fmt::Debug for RefRange<'_, Q, R, K, V>
1939where
1940 K: Ord + Borrow<Q> + fmt::Debug,
1941 V: fmt::Debug,
1942 R: RangeBounds<Q> + fmt::Debug,
1943 Q: Ord + ?Sized,
1944{
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 f.debug_struct("RefRange")
1947 .field("range", &self.range)
1948 .field("head", &self.head)
1949 .field("tail", &self.tail)
1950 .finish()
1951 }
1952}
1953
1954impl<'a, Q, R, K: 'a, V: 'a> RefRange<'a, Q, R, K, V>
1955where
1956 K: Ord + Borrow<Q>,
1957 R: RangeBounds<Q>,
1958 Q: Ord + ?Sized,
1959{
1960 /// Advances the iterator and returns the next value.
1961 pub fn next(&mut self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1962 self.parent.check_guard(guard);
1963 let next_head = match self.head {
1964 Some(ref e) => e.next(guard),
1965 None => try_pin_loop(|| self.parent.lower_bound(self.range.start_bound(), guard)),
1966 };
1967
1968 if let Some(ref h) = next_head {
1969 let bound = match self.tail {
1970 Some(ref t) => Bound::Excluded(t.key().borrow()),
1971 None => self.range.end_bound(),
1972 };
1973 if below_upper_bound(&bound, h.key().borrow()) {
1974 self.head = next_head.clone();
1975 next_head
1976 } else {
1977 unsafe {
1978 h.node.decrement(guard);
1979 }
1980 None
1981 }
1982 } else {
1983 None
1984 }
1985 }
1986
1987 /// Removes and returns an element from the end of the iterator.
1988 pub fn next_back(&mut self, guard: &Guard) -> Option<RefEntry<'a, K, V>> {
1989 self.parent.check_guard(guard);
1990 let next_tail = match self.tail {
1991 Some(ref e) => e.prev(guard),
1992 None => try_pin_loop(|| self.parent.upper_bound(self.range.end_bound(), guard)),
1993 };
1994
1995 if let Some(ref t) = next_tail {
1996 let bound = match self.head {
1997 Some(ref h) => Bound::Excluded(h.key().borrow()),
1998 None => self.range.start_bound(),
1999 };
2000 if above_lower_bound(&bound, t.key().borrow()) {
2001 self.tail = next_tail.clone();
2002 next_tail
2003 } else {
2004 unsafe {
2005 t.node.decrement(guard);
2006 }
2007 None
2008 }
2009 } else {
2010 None
2011 }
2012 }
2013
2014 /// Decrements a reference count owned by this iterator.
2015 pub fn drop_impl(&mut self, guard: &Guard) {
2016 self.parent.check_guard(guard);
2017 if let Some(e) = self.head.take() {
2018 unsafe { e.node.decrement(guard) };
2019 }
2020 if let Some(e) = self.tail.take() {
2021 unsafe { e.node.decrement(guard) };
2022 }
2023 }
2024}
2025
2026/// An owning iterator over the entries of a `SkipList`.
2027pub struct IntoIter<K, V> {
2028 /// The current node.
2029 ///
2030 /// All preceding nods have already been destroyed.
2031 node: *mut Node<K, V>,
2032}
2033
2034impl<K, V> Drop for IntoIter<K, V> {
2035 fn drop(&mut self) {
2036 // Iterate through the whole chain and destroy every node.
2037 while !self.node.is_null() {
2038 unsafe {
2039 // Unprotected loads are okay because this function is the only one currently using
2040 // the skip list.
2041 let next = (*self.node).tower[0].load(Ordering::Relaxed, epoch::unprotected());
2042
2043 // We can safely do this without deferring because references to
2044 // keys & values that we give out never outlive the SkipList.
2045 Node::finalize(self.node);
2046
2047 self.node = next.as_raw() as *mut Node<K, V>;
2048 }
2049 }
2050 }
2051}
2052
2053impl<K, V> Iterator for IntoIter<K, V> {
2054 type Item = (K, V);
2055
2056 fn next(&mut self) -> Option<(K, V)> {
2057 loop {
2058 // Have we reached the end of the skip list?
2059 if self.node.is_null() {
2060 return None;
2061 }
2062
2063 unsafe {
2064 // Take the key and value out of the node.
2065 let key = ptr::read(&(*self.node).key);
2066 let value = ptr::read(&(*self.node).value);
2067
2068 // Get the next node in the skip list.
2069 //
2070 // Unprotected loads are okay because this function is the only one currently using
2071 // the skip list.
2072 let next = (*self.node).tower[0].load(Ordering::Relaxed, epoch::unprotected());
2073
2074 // Deallocate the current node and move to the next one.
2075 Node::dealloc(self.node);
2076 self.node = next.as_raw() as *mut Node<K, V>;
2077
2078 // The current node may be marked. If it is, it's been removed from the skip list
2079 // and we should just skip it.
2080 if next.tag() == 0 {
2081 return Some((key, value));
2082 }
2083 }
2084 }
2085 }
2086}
2087
2088impl<K, V> fmt::Debug for IntoIter<K, V> {
2089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2090 f.pad("IntoIter { .. }")
2091 }
2092}
2093
2094/// Helper function to retry an operation until pinning succeeds or `None` is
2095/// returned.
2096pub(crate) fn try_pin_loop<'a: 'g, 'g, F, K, V>(mut f: F) -> Option<RefEntry<'a, K, V>>
2097where
2098 F: FnMut() -> Option<Entry<'a, 'g, K, V>>,
2099{
2100 loop {
2101 if let Some(e) = f()?.pin() {
2102 return Some(e);
2103 }
2104 }
2105}
2106
2107/// Helper function to check if a value is above a lower bound
2108fn above_lower_bound<T: Ord + ?Sized>(bound: &Bound<&T>, other: &T) -> bool {
2109 match *bound {
2110 Bound::Unbounded => true,
2111 Bound::Included(key) => other >= key,
2112 Bound::Excluded(key) => other > key,
2113 }
2114}
2115
2116/// Helper function to check if a value is below an upper bound
2117fn below_upper_bound<T: Ord + ?Sized>(bound: &Bound<&T>, other: &T) -> bool {
2118 match *bound {
2119 Bound::Unbounded => true,
2120 Bound::Included(key) => other <= key,
2121 Bound::Excluded(key) => other < key,
2122 }
2123}