1use std::sync::atomic::{AtomicPtr, AtomicBool, Ordering};
4use std::ptr;
5use std::cmp::Ordering as CmpOrdering;
6
7const MAX_HEIGHT: usize = 32;
8
9struct Node<K, V> {
10 key: K,
11 value: V,
12 next: [AtomicPtr<Node<K, V>>; MAX_HEIGHT],
13 height: usize,
14 marked: AtomicBool,
15}
16
17impl<K, V> Node<K, V> {
18 fn new(key: K, value: V, height: usize) -> Self {
19 let mut next: [AtomicPtr<Node<K, V>>; MAX_HEIGHT] = Default::default();
20 for i in 0..MAX_HEIGHT {
21 next[i] = AtomicPtr::new(ptr::null_mut());
22 }
23
24 Node {
25 key,
26 value,
27 next,
28 height,
29 marked: AtomicBool::new(false),
30 }
31 }
32}
33
34pub struct SkipList<K, V> {
36 head: Box<Node<K, V>>,
37}
38
39impl<K: Ord + Default + Clone, V: Default> SkipList<K, V> {
40 pub fn new() -> Self {
42 let head = Box::new(Node::new(K::default(), V::default(), MAX_HEIGHT));
43 SkipList { head }
44 }
45
46 fn random_height() -> usize {
47 let mut height = 1;
48 let mut rng = std::time::SystemTime::now()
49 .duration_since(std::time::UNIX_EPOCH)
50 .unwrap()
51 .subsec_nanos();
52
53 while height < MAX_HEIGHT && rng % 2 == 0 {
54 height += 1;
55 rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
56 }
57 height
58 }
59
60 fn find(&self, key: &K) -> ([*mut Node<K, V>; MAX_HEIGHT], [*mut Node<K, V>; MAX_HEIGHT]) {
61 let mut preds = [ptr::null_mut(); MAX_HEIGHT];
62 let mut succs = [ptr::null_mut(); MAX_HEIGHT];
63
64 let mut pred = &*self.head as *const Node<K, V> as *mut Node<K, V>;
65
66 for level in (0..MAX_HEIGHT).rev() {
67 let mut curr = unsafe { (*pred).next[level].load(Ordering::Acquire) };
68
69 while !curr.is_null() {
70 let curr_ref = unsafe { &*curr };
71
72 if curr_ref.marked.load(Ordering::Acquire) {
73 curr = curr_ref.next[level].load(Ordering::Acquire);
74 continue;
75 }
76
77 match curr_ref.key.cmp(key) {
78 CmpOrdering::Less => {
79 pred = curr;
80 curr = curr_ref.next[level].load(Ordering::Acquire);
81 }
82 _ => break,
83 }
84 }
85
86 preds[level] = pred;
87 succs[level] = curr;
88 }
89
90 (preds, succs)
91 }
92
93 pub fn insert(&self, key: K, value: V) -> bool {
95 let height = Self::random_height();
96 let new_node = Box::into_raw(Box::new(Node::new(key, value, height)));
97
98 loop {
99 let (preds, succs) = self.find(unsafe { &(*new_node).key });
100
101 if !succs[0].is_null() {
103 let succ_ref = unsafe { &*succs[0] };
104 if succ_ref.key == unsafe { (*new_node).key.clone() } && !succ_ref.marked.load(Ordering::Acquire) {
105 unsafe { drop(Box::from_raw(new_node)) };
106 return false;
107 }
108 }
109
110 for level in 0..height {
112 unsafe {
113 (*new_node).next[level].store(succs[level], Ordering::Relaxed);
114 }
115 }
116
117 let pred_next = unsafe { &(*preds[0]).next[0] };
119 match pred_next.compare_exchange(
120 succs[0],
121 new_node,
122 Ordering::Release,
123 Ordering::Acquire,
124 ) {
125 Ok(_) => {
126 for level in 1..height {
128 loop {
129 let pred = preds[level];
130 let succ = succs[level];
131 let pred_next = unsafe { &(*pred).next[level] };
132
133 if pred_next.compare_exchange(
134 succ,
135 new_node,
136 Ordering::Release,
137 Ordering::Acquire,
138 ).is_ok() {
139 break;
140 }
141
142 let (_new_preds, new_succs) = self.find(unsafe { &(*new_node).key });
143 if !new_succs[0].is_null() && unsafe { &*new_succs[0] }.key == unsafe { (*new_node).key.clone() } {
144 break;
145 }
146 }
147 }
148 return true;
149 }
150 Err(_) => continue,
151 }
152 }
153 }
154
155 pub fn contains(&self, key: &K) -> bool {
157 let (_, succs) = self.find(key);
158
159 if !succs[0].is_null() {
160 let succ_ref = unsafe { &*succs[0] };
161 succ_ref.key == *key && !succ_ref.marked.load(Ordering::Acquire)
162 } else {
163 false
164 }
165 }
166
167 pub fn get(&self, key: &K) -> Option<V>
169 where
170 V: Clone
171 {
172 let (_, succs) = self.find(key);
173
174 if !succs[0].is_null() {
175 let succ_ref = unsafe { &*succs[0] };
176 if succ_ref.key == *key && !succ_ref.marked.load(Ordering::Acquire) {
177 Some(succ_ref.value.clone())
178 } else {
179 None
180 }
181 } else {
182 None
183 }
184 }
185
186 pub fn remove(&self, key: &K) -> bool {
188 loop {
189 let (mut preds, succs) = self.find(key);
190
191 if succs[0].is_null() {
192 return false;
193 }
194
195 let node_to_remove = succs[0];
196 let node_ref = unsafe { &*node_to_remove };
197
198 if node_ref.key != *key {
199 return false;
200 }
201
202 if !node_ref.marked.compare_exchange(
204 false,
205 true,
206 Ordering::Release,
207 Ordering::Acquire,
208 ).is_ok() {
209 return false;
210 }
211
212 for level in (0..node_ref.height).rev() {
214 let succ = node_ref.next[level].load(Ordering::Acquire);
215 loop {
216 let pred_next = unsafe { &(*preds[level]).next[level] };
217 if pred_next.compare_exchange(
218 node_to_remove,
219 succ,
220 Ordering::Release,
221 Ordering::Acquire,
222 ).is_ok() {
223 break;
224 }
225
226 let (new_preds, _) = self.find(key);
227 if level < node_ref.height {
228 preds[level] = new_preds[level];
229 }
230 }
231 }
232
233 return true;
234 }
235 }
236}
237
238impl<K: Default + Ord + Clone, V: Default> Default for SkipList<K, V> {
239 fn default() -> Self {
240 Self::new()
241 }
242}
243
244unsafe impl<K: Send, V: Send> Send for SkipList<K, V> {}
245unsafe impl<K: Send + Sync, V: Send + Sync> Sync for SkipList<K, V> {}