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
use crate::prelude::SkipList;
use crate::skiplist::{HEAD_INDEX, Index, SkipNode, TAIL_INDEX};
use crate::{CppMapError, IsEqual, IsLessThan};
use smallvec::smallvec;
use std::fmt::Debug;
impl<K, V> SkipList<K, V>
where
K: Debug + Clone + IsLessThan,
V: Debug + Clone,
{
#[inline(always)]
/// Insert a key-value pair at the specified pos if possible.
/// Returns the index of the inserted node
/// Does nothing if that exact key already exists in the list
pub fn insert_with_hint(
&mut self,
key: K,
value: V,
hint: Index,
) -> Result<Index, CppMapError> {
//let key_clone = key.clone();
let rv = self.insert_with_hint_(key, value, hint)?;
//println!("insert_with_hint key={:?} hint={}, inserted at pos:{}", key_clone, hint, rv.0);
Ok(rv)
}
/// Insert a key-value pair at the specified pos if possible.
/// Returns the index of the inserted node
/// Does nothing if that exact key already exists in the list
pub(super) fn insert_with_hint_(
&mut self,
key: K,
value: V,
hint: Index,
) -> Result<Index, CppMapError> {
if self.is_empty() {
return self.insert(key, value);
}
// Get the initial hint position
if let Some(pos) = self.sequential_find_position_(&key, hint.0) {
// Short-circuit for head and tail insertion cases
if pos == HEAD_INDEX {
return self.insert(key, value);
}
// pick up the per thread rng
return Ok(Index(crate::skiplist::skiplist_impl::THREAD_RNG.with(
|r| {
let mut rng = r.borrow_mut();
self.single_pass_search_and_insert_(key, value, pos, &mut rng)
},
)));
}
// Fall back to standard insert if hint isn't helpful
Ok(Index(self.insert_(key, value)))
}
/// single-pass function that creates and inserts the node during initial traversal
fn single_pass_search_and_insert_(
&mut self,
key: K,
value: V,
hint_pos: usize,
rng: &mut rand::prelude::ThreadRng,
) -> usize {
// Target rank for insertion - use rank between hint node and next node
let target_rank = if hint_pos == TAIL_INDEX {
self.tail.rank
} else {
self.nodes[hint_pos].rank + 1
};
// Generate a random level for the new node early
let new_level = self.random_level(rng);
// Update current_level if necessary
let current_level = self.current_level;
if new_level > current_level {
self.current_level = new_level;
}
// Create/reuse a node index immediately
let new_index = Self::next_free_index_(self.nodes.len(), &mut self.free_index_pool);
// We'll need a list to store the connections to rewire
// Each entry contains (node_index, level) pairs that point to our successor
let mut connections: Vec<(usize, usize)> = Vec::with_capacity(new_level + 1);
let mut prev_at_level_zero = HEAD_INDEX;
// Traverse the skiplist to find the insertion point
let mut current = HEAD_INDEX;
// Start from the highest level and work down
for level in (0..=self.current_level).rev() {
// Traverse current level until we find node with rank not less than target
loop {
let next = self._forward(current, level);
// If we've reached the tail or a node where the rank is not less than our target
if next == TAIL_INDEX || self.nodes[next].rank >= target_rank {
// Found our insertion point at this level
if level <= new_level {
// Store this connection to rewire later
connections.push((current, level));
}
// Save level 0 predecessor for the rank calculation
if level == 0 {
prev_at_level_zero = current;
}
break;
}
// Continue moving forward at the current level
current = next;
}
}
// Now we have our insertion point, check for duplicate keys
let next_idx = self._forward_0(prev_at_level_zero);
dbg_assert!(next_idx != HEAD_INDEX);
if next_idx != TAIL_INDEX && self.nodes[next_idx].k().is_equal(&key) {
// Just like c++ std::map, do nothing on duplicate keys
return next_idx;
}
// Calculate the true rank for the new node
let (new_rank, is_congested) = self.get_rank_in_between(prev_at_level_zero, next_idx);
if is_congested {
self.is_congested = true;
}
// Create the new node with forward pointers to our successors
let forward_pointers = smallvec![TAIL_INDEX; new_level + 1];
// Initialize the node
if new_index == self.nodes.len() {
// Create and insert a new node
let new_node = SkipNode {
kv: Some((key, value)),
forward: forward_pointers, // We'll update this shortly
prev: prev_at_level_zero,
rank: new_rank,
};
Self::store_node_(new_node, new_index, &mut self.nodes);
} else {
// Reuse a node
let node = &mut self.nodes[new_index];
node.forward = forward_pointers; // We'll update this shortly
node.kv = Some((key, value));
node.prev = prev_at_level_zero;
node.rank = new_rank;
}
// Rewire the connections
for (node_idx, level) in connections {
// Get the next node at this level before we modify pointers
let next_at_level = self._forward(node_idx, level);
// Update the predecessor to point to our new node
match node_idx {
HEAD_INDEX => self.head.forward[level] = new_index,
TAIL_INDEX => panic!("Unexpected node type in insert update"),
_ => {
let node = &mut self.nodes[node_idx];
if level < node.forward.len() {
node.forward[level] = new_index;
}
}
}
// Update the new node's forward pointer at this level
match new_index {
HEAD_INDEX | TAIL_INDEX => panic!("Unexpected node type at new_index"),
_ => self.nodes[new_index].forward[level] = next_at_level,
}
}
// Update the prev pointer of the next node
match next_idx {
TAIL_INDEX => self.tail.prev = new_index,
HEAD_INDEX => panic!("Unexpected node type for next node"),
_ => self.nodes[next_idx].prev = new_index,
}
self.maybe_adjust_max_level(rng);
if self.is_congested {
self.rebalance_ranks();
}
new_index
}
#[inline(always)]
/// Insert a key-value pair
/// Returns the index of the inserted node
/// Does nothing if that exact key already exists in the list
pub fn insert(&mut self, key: K, value: V) -> Result<Index, CppMapError> {
Ok(Index(self.insert_(key, value)))
}
#[inline(always)]
/// Insert a key-value pair
/// Returns the index of the inserted node
/// Does nothing if that exact key already exists in the list
fn insert_(&mut self, key: K, value: V) -> usize {
let path = self.find_position_with_path_(&key);
//let found_pos = path[0];
self.insert_with_path_(key, value, path)
//println!("normal insert. found pos={}, inserted_at:{}", found_pos, inserted_at);
}
#[inline(always)]
/// Insert a key-value pair
/// Returns the index of the inserted node
/// Does nothing if that exact key already exists in the list
fn insert_with_path_(&mut self, key: K, value: V, path: Vec<usize>) -> usize {
// pick up the per thread rng
crate::skiplist::skiplist_impl::THREAD_RNG.with(|r| {
let mut rng = r.borrow_mut();
self.insert_with_path_and_rng_(key, value, path, &mut rng)
})
}
fn insert_with_path_and_rng_(
&mut self,
key: K,
value: V,
mut path: Vec<usize>,
rng: &mut rand::prelude::ThreadRng,
) -> usize {
let next_idx = self._forward_0(path[0]);
dbg_assert!(next_idx != HEAD_INDEX);
if next_idx != TAIL_INDEX && self.nodes[next_idx].k().is_equal(&key) {
// Just like c++ std::map, do nothing on duplicate keys
return next_idx;
}
// Generate a random level for the new node
let level = self.random_level(rng);
// Update current_level if necessary
#[allow(clippy::needless_range_loop)]
if level > self.current_level {
for i in (self.current_level + 1)..=level {
path[i] = HEAD_INDEX;
}
self.current_level = level;
}
// Create/reuse a node index
let new_index = Self::next_free_index_(self.nodes.len(), &mut self.free_index_pool);
// Find the prev and next nodes at level 0
let prev = path[0];
let next = self._forward_0(prev);
let (new_rank, is_congested) = self.get_rank_in_between(prev, next);
if is_congested {
self.is_congested = true;
}
if new_index == self.nodes.len() {
// Create and insert a new node
let new_node = SkipNode {
kv: Some((key, value)),
forward: smallvec![TAIL_INDEX; level + 1],
prev,
rank: new_rank,
};
Self::store_node_(new_node, new_index, &mut self.nodes);
} else {
// reuse a node
let node = &mut self.nodes[new_index];
// todo! should we try to re-use the existing smallvec instead?
node.forward = smallvec![TAIL_INDEX; level + 1];
node.kv = Some((key, value));
node.prev = prev;
node.rank = new_rank;
}
// Update the forward pointers of all nodes in the update vector
#[allow(clippy::needless_range_loop)]
for i in 0..=level {
let update_node = path[i];
let next_at_level = self._forward(update_node, i);
// Update the update_node to point to new_index
match update_node {
HEAD_INDEX => self.head.forward[i] = new_index,
TAIL_INDEX => panic!("Unexpected node type in insert update"),
_ => {
let node = &mut self.nodes[update_node];
if i < node.forward.len() {
node.forward[i] = new_index;
}
}
}
// Update the new node's forward pointer at this level
match new_index {
HEAD_INDEX | TAIL_INDEX => panic!("Unexpected node type at new_index"),
_ => self.nodes[new_index].forward[i] = next_at_level,
}
}
// Update the prev pointer of the next node
match next {
TAIL_INDEX => self.tail.prev = new_index,
HEAD_INDEX => panic!("Unexpected node type for next node"),
_ => self.nodes[next].prev = new_index,
}
self.maybe_adjust_max_level(rng);
if self.is_congested {
self.rebalance_ranks();
}
new_index
}
}