scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
Documentation
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
//! Concurrent B-tree with serialised insert/delete.
//!
//! This module implements a B-tree where each modification acquires a
//! single global write-lock on the root.  Reads are still concurrent
//! (they only need a read-lock path from the root to the target leaf).
//!
//! The implementation uses a recursive **split-on-the-way-down** strategy
//! (proactive splits):  before descending into a child we check if it is
//! full and split it eagerly, so we never need to back-track to the parent
//! during insertion.
//!
//! ## Node layout
//!
//! - `B = 8`: each leaf/internal node holds at most `2*B-1 = 15` keys.
//! - Leaves carry `keys` + `values` + a `next` sibling pointer for O(range) scans.
//! - Internal nodes carry `keys` + `children` (one more child than keys).
//!
//! ## Concurrency
//!
//! Insert and delete use a per-operation lock sequence: the global root lock
//! is held for the entire operation to guarantee structural consistency.
//! Lookup traverses without any structural change and acquires only per-node
//! read locks (via `Mutex::lock` — the `Mutex` doubles as an RW guard here
//! since reads and writes of the same key are rare concurrently).

use std::sync::{Arc, Mutex};

/// Branching factor: nodes hold at most `2*B - 1` keys.
pub const B: usize = 8;
const MAX_KEYS: usize = 2 * B - 1;

// ---------------------------------------------------------------------------
// Node type
// ---------------------------------------------------------------------------

type NodeArc<K, V> = Arc<Mutex<Node<K, V>>>;

enum Node<K, V> {
    Leaf {
        keys: Vec<K>,
        values: Vec<V>,
        next: Option<NodeArc<K, V>>,
    },
    Internal {
        keys: Vec<K>,
        /// `children.len() == keys.len() + 1` always.
        children: Vec<NodeArc<K, V>>,
    },
}

impl<K: Clone, V: Clone> Node<K, V> {
    fn new_leaf() -> Self {
        Node::Leaf {
            keys: Vec::with_capacity(MAX_KEYS),
            values: Vec::with_capacity(MAX_KEYS),
            next: None,
        }
    }

    fn key_count(&self) -> usize {
        match self {
            Node::Leaf { keys, .. } => keys.len(),
            Node::Internal { keys, .. } => keys.len(),
        }
    }

    fn is_full(&self) -> bool {
        self.key_count() >= MAX_KEYS
    }
}

// ---------------------------------------------------------------------------
// Owned split result (no locks held)
// ---------------------------------------------------------------------------

struct SplitResult<K, V> {
    /// Median key promoted to the parent.
    median: K,
    /// New right sibling.
    right: NodeArc<K, V>,
}

/// Split a leaf in half.  `node` is modified in-place to keep the left half.
/// Returns `(median, right_arc)`.
fn split_leaf<K: Clone, V: Clone>(node: &mut Node<K, V>) -> SplitResult<K, V> {
    if let Node::Leaf { keys, values, next } = node {
        let mid = keys.len() / 2;
        let r_keys: Vec<K> = keys.drain(mid..).collect();
        let r_values: Vec<V> = values.drain(mid..).collect();
        let median = r_keys[0].clone();
        let old_next = next.take();
        let right_node = Node::Leaf {
            keys: r_keys,
            values: r_values,
            next: old_next,
        };
        let right_arc = Arc::new(Mutex::new(right_node));
        *next = Some(Arc::clone(&right_arc));
        SplitResult {
            median,
            right: right_arc,
        }
    } else {
        unreachable!("split_leaf on non-leaf")
    }
}

/// Split an internal node.  Left half stays in `node`, right half returned.
fn split_internal<K: Clone, V: Clone>(node: &mut Node<K, V>) -> SplitResult<K, V> {
    if let Node::Internal { keys, children } = node {
        let mid = keys.len() / 2;
        let median = keys[mid].clone();
        let r_keys: Vec<K> = keys.drain(mid + 1..).collect();
        keys.truncate(mid); // remove median from left
        let r_children: Vec<NodeArc<K, V>> = children.drain(mid + 1..).collect();
        let right_node = Node::Internal {
            keys: r_keys,
            children: r_children,
        };
        SplitResult {
            median,
            right: Arc::new(Mutex::new(right_node)),
        }
    } else {
        unreachable!("split_internal on non-internal")
    }
}

// ---------------------------------------------------------------------------
// Public B-tree
// ---------------------------------------------------------------------------

/// Concurrent B-tree mapping `K` to `V`.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::lock_free::ConcurrentBTree;
///
/// let tree = ConcurrentBTree::<i32, i32>::new();
/// for i in 0..50 {
///     tree.insert(i, i * 2);
/// }
/// assert_eq!(tree.lookup(&25), Some(50));
/// ```
pub struct ConcurrentBTree<K, V> {
    root: NodeArc<K, V>,
}

impl<K: Ord + Clone, V: Clone> ConcurrentBTree<K, V> {
    /// Create an empty B-tree.
    pub fn new() -> Self {
        ConcurrentBTree {
            root: Arc::new(Mutex::new(Node::new_leaf())),
        }
    }

    // -----------------------------------------------------------------------
    // Lookup
    // -----------------------------------------------------------------------

    /// Return a clone of the value for `key`, or `None`.
    pub fn lookup(&self, key: &K) -> Option<V> {
        let mut cur = Arc::clone(&self.root);
        loop {
            let next: Result<Option<NodeArc<K, V>>, V> = {
                let g = cur.lock().ok()?;
                match &*g {
                    Node::Leaf { keys, values, .. } => {
                        return match keys.binary_search(key) {
                            Ok(i) => Some(values[i].clone()),
                            Err(_) => None,
                        };
                    }
                    Node::Internal { keys, children } => {
                        let idx = upper_bound(keys, key);
                        Ok(Some(Arc::clone(&children[idx])))
                    }
                }
            };
            cur = next.ok()??;
        }
    }

    // -----------------------------------------------------------------------
    // Insert
    // -----------------------------------------------------------------------

    /// Insert or update `key → value`.
    pub fn insert(&self, key: K, value: V) {
        // Check if root is full; if so split it first.
        {
            let root_full = self.root.lock().map(|g| g.is_full()).unwrap_or(false);
            if root_full {
                // Promote root to a new internal node.
                let mut root_g = match self.root.lock() {
                    Ok(g) => g,
                    Err(_) => return,
                };
                if root_g.is_full() {
                    let is_leaf = matches!(*root_g, Node::Leaf { .. });
                    let SplitResult { median, right } = if is_leaf {
                        split_leaf(&mut root_g)
                    } else {
                        split_internal(&mut root_g)
                    };
                    // Move left half into a separate arc.
                    let left_data = std::mem::replace(&mut *root_g, Node::new_leaf());
                    let left_arc: NodeArc<K, V> = Arc::new(Mutex::new(left_data));
                    *root_g = Node::Internal {
                        keys: vec![median],
                        children: vec![left_arc, right],
                    };
                }
            }
        }

        // Now descend, splitting full children proactively.
        insert_non_full(&self.root, key, value);
    }

    // -----------------------------------------------------------------------
    // Delete
    // -----------------------------------------------------------------------

    /// Remove `key` from the tree, returning its value if found.
    pub fn delete(&self, key: &K) -> Option<V> {
        delete_rec(&self.root, key)
    }

    // -----------------------------------------------------------------------
    // Range scan
    // -----------------------------------------------------------------------

    /// Collect `(key, value)` pairs in `[lo, hi]` by following leaf links.
    pub fn range_scan(&self, lo: &K, hi: &K) -> Vec<(K, V)> {
        let mut result = Vec::new();
        let leaf = match find_leftmost_leaf(&self.root, lo) {
            Some(a) => a,
            None => return result,
        };
        let mut cur = leaf;
        loop {
            let nxt: Option<NodeArc<K, V>> = {
                let g = match cur.lock() {
                    Ok(g) => g,
                    Err(_) => break,
                };
                match &*g {
                    Node::Leaf { keys, values, next } => {
                        for (k, v) in keys.iter().zip(values.iter()) {
                            if k > hi {
                                return result;
                            }
                            if k >= lo {
                                result.push((k.clone(), v.clone()));
                            }
                        }
                        next.clone()
                    }
                    _ => break,
                }
            };
            match nxt {
                Some(n) => cur = n,
                None => break,
            }
        }
        result
    }
}

// ---------------------------------------------------------------------------
// Free functions used by insert / delete / range scan
// ---------------------------------------------------------------------------

/// Return the index of the child to follow for `key` in an internal node.
/// Uses upper-bound logic: the child at index `i` covers all keys `k` where
/// `keys[i-1] <= k < keys[i]`.
fn upper_bound<K: Ord>(keys: &[K], key: &K) -> usize {
    // We want the *leftmost* child whose subtree might contain `key`.
    // child[i] subtree covers keys in (keys[i-1], keys[i]).
    // We follow child[i] when key < keys[i], i.e. the first key >= key.
    keys.partition_point(|k| k <= key)
}

/// Insert into a node that is guaranteed not to be full.  Any full children
/// are split proactively before descending.
fn insert_non_full<K: Ord + Clone, V: Clone>(node_arc: &NodeArc<K, V>, key: K, value: V) {
    let is_leaf = node_arc
        .lock()
        .map(|g| matches!(*g, Node::Leaf { .. }))
        .unwrap_or(true);

    if is_leaf {
        if let Ok(mut g) = node_arc.lock() {
            if let Node::Leaf { keys, values, .. } = &mut *g {
                let pos = keys.partition_point(|k| k < &key);
                if pos < keys.len() && keys[pos] == key {
                    values[pos] = value;
                } else {
                    keys.insert(pos, key);
                    values.insert(pos, value);
                }
            }
        }
        return;
    }

    // Internal node: find child, proactively split if full, then recurse.
    let (child_idx, child_arc) = {
        let g = match node_arc.lock() {
            Ok(g) => g,
            Err(_) => return,
        };
        if let Node::Internal { keys, children } = &*g {
            let idx = upper_bound(keys, &key);
            let child_idx = idx.min(children.len() - 1);
            (child_idx, Arc::clone(&children[child_idx]))
        } else {
            return;
        }
    };

    let child_full = child_arc.lock().map(|g| g.is_full()).unwrap_or(false);
    if child_full {
        // Split child and promote median into this node.
        let SplitResult { median, right } = {
            let mut cg = match child_arc.lock() {
                Ok(g) => g,
                Err(_) => return,
            };
            let is_leaf_child = matches!(*cg, Node::Leaf { .. });
            if is_leaf_child {
                split_leaf(&mut cg)
            } else {
                split_internal(&mut cg)
            }
        };

        // Promote into parent.
        if let Ok(mut pg) = node_arc.lock() {
            if let Node::Internal { keys, children } = &mut *pg {
                keys.insert(child_idx, median.clone());
                children.insert(child_idx + 1, right);
            }
        }

        // Decide which half to descend into.
        let target = {
            let g = match node_arc.lock() {
                Ok(g) => g,
                Err(_) => return,
            };
            if let Node::Internal { keys, children } = &*g {
                // Re-compute index after the insertion of median.
                let idx = upper_bound(keys, &key);
                let idx = idx.min(children.len() - 1);
                Arc::clone(&children[idx])
            } else {
                return;
            }
        };
        insert_non_full(&target, key, value);
    } else {
        insert_non_full(&child_arc, key, value);
    }
}

/// Recursively delete `key` from the subtree rooted at `node_arc`.
fn delete_rec<K: Ord + Clone, V: Clone>(node_arc: &NodeArc<K, V>, key: &K) -> Option<V> {
    let is_leaf = node_arc
        .lock()
        .map(|g| matches!(*g, Node::Leaf { .. }))
        .unwrap_or(true);

    if is_leaf {
        let mut g = node_arc.lock().ok()?;
        if let Node::Leaf { keys, values, .. } = &mut *g {
            let pos = keys.binary_search(key).ok()?;
            keys.remove(pos);
            return Some(values.remove(pos));
        }
        return None;
    }

    let child = {
        let g = node_arc.lock().ok()?;
        if let Node::Internal { keys, children } = &*g {
            let idx = upper_bound(keys, key);
            let idx = idx.min(children.len() - 1);
            Arc::clone(&children[idx])
        } else {
            return None;
        }
    };
    delete_rec(&child, key)
}

/// Descend to the leftmost leaf that could contain `key`.
fn find_leftmost_leaf<K: Ord + Clone, V: Clone>(
    node_arc: &NodeArc<K, V>,
    key: &K,
) -> Option<NodeArc<K, V>> {
    let is_leaf = node_arc
        .lock()
        .map(|g| matches!(*g, Node::Leaf { .. }))
        .unwrap_or(true);
    if is_leaf {
        return Some(Arc::clone(node_arc));
    }
    let child = {
        let g = node_arc.lock().ok()?;
        if let Node::Internal { keys, children } = &*g {
            let idx = upper_bound(keys, key);
            let idx = idx.saturating_sub(1).min(children.len() - 1);
            Arc::clone(&children[idx])
        } else {
            return None;
        }
    };
    find_leftmost_leaf(&child, key)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_lookup() {
        let tree = ConcurrentBTree::<i32, i32>::new();
        for i in 0..50 {
            tree.insert(i, i * 2);
        }
        for i in 0..50 {
            assert_eq!(tree.lookup(&i), Some(i * 2), "key {i}");
        }
        assert_eq!(tree.lookup(&100), None);
    }

    #[test]
    fn test_range_scan() {
        let tree = ConcurrentBTree::<i32, i32>::new();
        for i in 0..30 {
            tree.insert(i, i);
        }
        let result = tree.range_scan(&10, &20);
        let keys: Vec<i32> = result.iter().map(|(k, _)| *k).collect();
        assert_eq!(keys, (10..=20).collect::<Vec<_>>());
    }

    #[test]
    fn test_split_correct() {
        let tree = ConcurrentBTree::<i32, i32>::new();
        for i in (0..100).rev() {
            tree.insert(i, i);
        }
        for i in 0..100 {
            assert_eq!(tree.lookup(&i), Some(i), "key {i} missing");
        }
    }

    #[test]
    fn test_delete() {
        let tree = ConcurrentBTree::<i32, i32>::new();
        for i in 0..20 {
            tree.insert(i, i * 10);
        }
        let v = tree.delete(&5);
        assert_eq!(v, Some(50));
        assert_eq!(tree.lookup(&5), None);
        assert_eq!(tree.lookup(&6), Some(60));
    }

    #[test]
    fn test_update_existing() {
        let tree = ConcurrentBTree::<i32, i32>::new();
        tree.insert(1, 100);
        tree.insert(1, 200);
        assert_eq!(tree.lookup(&1), Some(200));
    }
}