forked from kanidm/concread
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcursor.rs
More file actions
2740 lines (2485 loc) · 94.2 KB
/
Copy pathcursor.rs
File metadata and controls
2740 lines (2485 loc) · 94.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The cursor is what actually knits a tree together from the parts
// we have, and has an important role to keep the system consistent.
//
// Additionally, the cursor also is responsible for general movement
// throughout the structure and how to handle that effectively
use super::node::*;
use crate::internals::lincowcell::LinCowCellCapable;
use std::borrow::Borrow;
use std::fmt::Debug;
use std::mem;
use super::iter::{Iter, KeyIter, RangeIter, ValueIter};
use super::mutiter::RangeMutIter;
use super::states::*;
use std::ops::RangeBounds;
use std::sync::Mutex;
/// The internal root of the tree, with associated garbage lists etc.
#[derive(Debug)]
pub(crate) struct SuperBlock<K, V>
where
K: Ord + Clone + Debug,
V: Clone,
{
root: *mut Node<K, V>,
size: usize,
txid: u64,
}
unsafe impl<K: Clone + Ord + Debug + Send + 'static, V: Clone + Send + 'static> Send
for SuperBlock<K, V>
{
}
unsafe impl<K: Clone + Ord + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static> Sync
for SuperBlock<K, V>
{
}
impl<K: Clone + Ord + Debug, V: Clone> LinCowCellCapable<CursorRead<K, V>, CursorWrite<K, V>>
for SuperBlock<K, V>
{
fn create_reader(&self) -> CursorRead<K, V> {
// This sets up the first reader.
CursorRead::new(self)
}
fn create_writer(&self) -> CursorWrite<K, V> {
// Create a writer.
CursorWrite::new(self)
}
fn pre_commit(
&mut self,
mut new: CursorWrite<K, V>,
prev: &CursorRead<K, V>,
) -> CursorRead<K, V> {
let mut prev_last_seen = prev.last_seen.lock().unwrap();
debug_assert!((*prev_last_seen).is_empty());
let new_last_seen = &mut new.last_seen;
// swap the two lists. We should now have "empty"
std::mem::swap(&mut (*prev_last_seen), &mut (*new_last_seen));
debug_assert!((*new_last_seen).is_empty());
// Now when the lock is dropped, both sides see the correct info and garbage for drops.
// We are done, time to seal everything.
new.first_seen.iter().for_each(|n| {
Node::make_ro_raw(*n);
});
// Clear first seen, we won't be dropping them from here.
new.first_seen.clear();
// == Push data into our sb. ==
self.root = new.root;
self.size = new.length;
self.txid = new.txid;
// Create the new reader.
CursorRead::new(self)
}
}
impl<K: Clone + Ord + Debug, V: Clone> SuperBlock<K, V> {
/// This is UNSAFE because you *MUST* understand how to manage the transactions
/// of this type and to give a correct linearised transaction manager the ability
/// to control this.
///
/// More than likely, you WILL NOT do this so you should RUN AWAY and try to forget
/// you ever saw this function at all.
pub unsafe fn new() -> Self {
let leaf: *mut Leaf<K, V> = Node::new_leaf(1);
SuperBlock {
root: leaf as *mut Node<K, V>,
size: 0,
txid: 1,
}
}
#[cfg(test)]
pub(crate) fn new_test(txid: u64, root: *mut Node<K, V>) -> Self {
assert!(txid < (TXID_MASK >> TXID_SHF));
assert!(txid > 0);
// let last_seen: Vec<*mut Node<K, V>> = Vec::with_capacity(16);
let mut first_seen = Vec::with_capacity(16);
// Do a pre-verify to be sure it's sane.
assert!(Node::verify_raw(root));
// Collect anythinng from root into this txid if needed.
// Set txid to txid on all tree nodes from the root.
first_seen.push(root);
Node::sblock_collect_raw(root, &mut first_seen);
// Lock them all
first_seen.iter().for_each(|n| {
Node::make_ro_raw(*n);
});
// Determine our count internally.
let (length, _) = Node::tree_density_raw(root);
// Good to go!
SuperBlock {
txid,
size: length,
root,
}
}
}
#[derive(Debug)]
pub(crate) struct CursorRead<K, V>
where
K: Ord + Clone + Debug,
V: Clone,
{
txid: u64,
length: usize,
root: *mut Node<K, V>,
last_seen: Mutex<Vec<*mut Node<K, V>>>,
}
unsafe impl<K: Clone + Ord + Debug + Send + 'static, V: Clone + Send + 'static> Send
for CursorRead<K, V>
{
}
unsafe impl<K: Clone + Ord + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static> Sync
for CursorRead<K, V>
{
}
#[derive(Debug)]
pub(crate) struct CursorWrite<K, V>
where
K: Ord + Clone + Debug,
V: Clone,
{
txid: u64,
length: usize,
root: *mut Node<K, V>,
last_seen: Vec<*mut Node<K, V>>,
first_seen: Vec<*mut Node<K, V>>,
}
unsafe impl<K: Clone + Ord + Debug + Send + 'static, V: Clone + Send + 'static> Send
for CursorWrite<K, V>
{
}
unsafe impl<K: Clone + Ord + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static> Sync
for CursorWrite<K, V>
{
}
pub(crate) trait CursorReadOps<K: Clone + Ord + Debug, V: Clone> {
#[allow(unused)]
fn get_root_ref(&self) -> &Node<K, V>;
fn get_root(&self) -> *mut Node<K, V>;
fn len(&self) -> usize;
fn get_txid(&self) -> u64;
#[cfg(test)]
fn get_tree_density(&self) -> (usize, usize) {
// Walk the tree and calculate the packing efficiency.
let rref = self.get_root();
Node::tree_density_raw(rref)
}
fn search<Q>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
let mut node = self.get_root();
for _i in 0..65536 {
if unsafe { (*node).is_leaf() } {
let lref = leaf_ref!(node, K, V);
return lref.get_ref(k).map(|v| unsafe {
// Strip the lifetime and rebind to the lifetime of `self`.
// This is safe because we know that these nodes will NOT
// be altered during the lifetime of this txn, so the references
// will remain stable.
let x = v as *const V;
&*x as &V
});
} else {
let bref = branch_ref!(node, K, V);
let idx = bref.locate_node(k);
node = bref.get_idx_unchecked(idx);
}
}
panic!("Tree depth exceeded max limit (65536). This may indicate memory corruption.");
}
fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Ord + ?Sized,
{
self.search(k).is_some()
}
fn first_key_value(&self) -> Option<(&K, &V)> {
let mut node = self.get_root();
for _i in 0..65536 {
if unsafe { (*node).is_leaf() } {
let lref = leaf_ref!(node, K, V);
return lref.min_value();
} else {
let bref = branch_ref!(node, K, V);
node = bref.min_node();
}
}
panic!("Tree depth exceeded max limit (65536). This may indicate memory corruption.");
}
fn last_key_value(&self) -> Option<(&K, &V)> {
let mut node = self.get_root();
for _i in 0..65536 {
if unsafe { (*node).is_leaf() } {
let lref = leaf_ref!(node, K, V);
return lref.max_value();
} else {
let bref = branch_ref!(node, K, V);
node = bref.max_node();
}
}
panic!("Tree depth exceeded max limit (65536). This may indicate memory corruption.");
}
fn range<'n, R, T>(&'n self, range: R) -> RangeIter<'n, K, V>
where
K: Borrow<T>,
T: Ord + ?Sized,
R: RangeBounds<T>,
{
RangeIter::new(self.get_root(), range, self.len())
}
fn kv_iter<'n>(&'n self) -> Iter<'n, K, V> {
Iter::new(self.get_root(), self.len())
}
fn k_iter<'n>(&'n self) -> KeyIter<'n, K, V> {
KeyIter::new(self.get_root(), self.len())
}
fn v_iter<'n>(&'n self) -> ValueIter<'n, K, V> {
ValueIter::new(self.get_root(), self.len())
}
#[cfg(test)]
fn verify(&self) -> bool {
Node::no_cycles_raw(self.get_root()) && Node::verify_raw(self.get_root()) && {
let (l, _) = self.get_tree_density();
l == self.len()
}
}
}
impl<K: Clone + Ord + Debug, V: Clone> CursorWrite<K, V> {
pub(crate) fn new(sblock: &SuperBlock<K, V>) -> Self {
let txid = sblock.txid + 1;
assert!(txid < (TXID_MASK >> TXID_SHF));
// println!("starting wr txid -> {:?}", txid);
let length = sblock.size;
let root = sblock.root;
// TODO: Could optimise how big these are based
// on past trends? Or based on % tree size?
let last_seen = Vec::with_capacity(16);
let first_seen = Vec::with_capacity(16);
CursorWrite {
txid,
length,
root,
last_seen,
first_seen,
}
}
pub(crate) fn clear(&mut self) {
// Reset the values in this tree.
// We need to mark everything as disposable, and create a new root!
self.last_seen.push(self.root);
unsafe { (*self.root).sblock_collect(&mut self.last_seen) };
let nroot: *mut Leaf<K, V> = Node::new_leaf(self.txid);
let mut nroot = nroot as *mut Node<K, V>;
self.first_seen.push(nroot);
mem::swap(&mut self.root, &mut nroot);
self.length = 0;
}
// Functions as insert_or_update
pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
let r = match clone_and_insert(
self.root,
self.txid,
k,
v,
&mut self.last_seen,
&mut self.first_seen,
) {
CRInsertState::NoClone(res) => res,
CRInsertState::Clone(res, mut nnode) => {
// We have a new root node, swap it in.
// !!! It's already been cloned and marked for cleaning by the clone_and_insert
// call.
// eprintln!("swap: {:?}, {:?}", self.root, nnode);
mem::swap(&mut self.root, &mut nnode);
// Return the insert result
res
}
CRInsertState::CloneSplit(lnode, rnode) => {
// The previous root had to split - make a new
// root now and put it inplace.
let mut nroot = Node::new_branch(self.txid, lnode, rnode) as *mut Node<K, V>;
self.first_seen.push(nroot);
// The root was cloned as part of clone split
// This swaps the POINTERS not the content!
mem::swap(&mut self.root, &mut nroot);
// As we split, there must NOT have been an existing
// key to overwrite.
None
}
CRInsertState::Split(rnode) => {
// The previous root was already part of this txn, but has now
// split. We need to construct a new root and swap them.
//
// Note, that we have to briefly take an extra RC on the root so
// that we can get it into the branch.
let mut nroot = Node::new_branch(self.txid, self.root, rnode) as *mut Node<K, V>;
self.first_seen.push(nroot);
// println!("ls push 2");
// self.last_seen.push(self.root);
mem::swap(&mut self.root, &mut nroot);
// As we split, there must NOT have been an existing
// key to overwrite.
None
}
CRInsertState::RevSplit(lnode) => {
let mut nroot = Node::new_branch(self.txid, lnode, self.root) as *mut Node<K, V>;
self.first_seen.push(nroot);
// println!("ls push 3");
// self.last_seen.push(self.root);
mem::swap(&mut self.root, &mut nroot);
None
}
CRInsertState::CloneRevSplit(rnode, lnode) => {
let mut nroot = Node::new_branch(self.txid, lnode, rnode) as *mut Node<K, V>;
self.first_seen.push(nroot);
// root was cloned in the rev split
// println!("ls push 4");
// self.last_seen.push(self.root);
mem::swap(&mut self.root, &mut nroot);
None
}
};
// If this is none, it means a new slot is now occupied.
if r.is_none() {
self.length += 1;
}
r
}
pub(crate) fn remove(&mut self, k: &K) -> Option<V> {
let r = match clone_and_remove(
self.root,
self.txid,
k,
&mut self.last_seen,
&mut self.first_seen,
) {
CRRemoveState::NoClone(res) => res,
CRRemoveState::Clone(res, mut nnode) => {
mem::swap(&mut self.root, &mut nnode);
res
}
CRRemoveState::Shrink(res) => {
if self_meta!(self.root).is_leaf() {
// No action - we have an empty tree.
res
} else {
// Root is being demoted, get the last branch and
// promote it to the root.
self.last_seen.push(self.root);
let rmut = branch_ref!(self.root, K, V);
let mut pnode = rmut.extract_last_node();
mem::swap(&mut self.root, &mut pnode);
res
}
}
CRRemoveState::CloneShrink(res, mut nnode) => {
if self_meta!(nnode).is_leaf() {
// The tree is empty, but we cloned the root to get here.
mem::swap(&mut self.root, &mut nnode);
res
} else {
// Our root is getting demoted here, get the remaining branch
self.last_seen.push(nnode);
let rmut = branch_ref!(nnode, K, V);
let mut pnode = rmut.extract_last_node();
// Promote it to the new root
mem::swap(&mut self.root, &mut pnode);
res
}
}
};
if r.is_some() {
self.length -= 1;
}
r
}
#[cfg(test)]
pub(crate) fn path_clone(&mut self, k: &K) {
match path_clone(
self.root,
self.txid,
k,
&mut self.last_seen,
&mut self.first_seen,
) {
CRCloneState::Clone(mut nroot) => {
// We cloned the root, so swap it.
mem::swap(&mut self.root, &mut nroot);
}
CRCloneState::NoClone => {}
};
}
pub(crate) fn get_mut_ref(&mut self, k: &K) -> Option<&mut V> {
match path_clone(
self.root,
self.txid,
k,
&mut self.last_seen,
&mut self.first_seen,
) {
CRCloneState::Clone(mut nroot) => {
// We cloned the root, so swap it.
mem::swap(&mut self.root, &mut nroot);
}
CRCloneState::NoClone => {}
};
// Now get the ref.
path_get_mut_ref(self.root, k)
}
pub(crate) fn split_off_lt(&mut self, k: &K) {
/*
// Remove all the values less than from the top of the tree.
loop {
let result = clone_and_split_off_trim_lt(
self.root,
self.txid,
k,
&mut self.last_seen,
&mut self.first_seen,
);
// println!("clone_and_split_off_trim_lt -> {:?}", result);
match result {
CRTrimState::Complete => break,
CRTrimState::Clone(mut nroot) => {
// We cloned the root as we changed it, but don't need
// to recurse so we break the loop.
mem::swap(&mut self.root, &mut nroot);
break;
}
CRTrimState::Promote(mut nroot) => {
mem::swap(&mut self.root, &mut nroot);
// This will continue and try again.
}
}
}
*/
/*
// Now work up the tree and clean up the remaining path in between
let result = clone_and_split_off_prune_lt(&mut self.root, self.txid, k);
// println!("clone_and_split_off_prune_lt -> {:?}", result);
match result {
CRPruneState::OkNoClone => {}
CRPruneState::OkClone(mut nroot) => {
mem::swap(&mut self.root, &mut nroot);
}
CRPruneState::Prune => {
if self.root.is_leaf() {
// No action, the tree is now empty.
} else {
// Root is being demoted, get the last branch and
// promote it to the root.
let rmut = Arc::get_mut(&mut self.root).unwrap().as_mut_branch();
let mut pnode = rmut.extract_last_node();
mem::swap(&mut self.root, &mut pnode);
}
}
CRPruneState::ClonePrune(mut clone) => {
if self.root.is_leaf() {
mem::swap(&mut self.root, &mut clone);
} else {
let rmut = Arc::get_mut(&mut clone).unwrap().as_mut_branch();
let mut pnode = rmut.extract_last_node();
mem::swap(&mut self.root, &mut pnode);
}
}
};
*/
// Get rid of anything else dangling
let mut rmkeys: Vec<K> = Vec::new();
for ki in self.k_iter() {
if ki >= k {
break;
}
rmkeys.push(ki.clone());
}
for kr in rmkeys.into_iter() {
let _ = self.remove(&kr);
}
// Iterate over the remaining kv's to fix our k,v count.
let newsize = self.kv_iter().count();
self.length = newsize;
}
#[cfg(test)]
pub(crate) fn root_txid(&self) -> u64 {
self.get_root_ref().get_txid()
}
#[cfg(test)]
pub(crate) fn tree_density(&self) -> (usize, usize) {
Node::<K, V>::tree_density_raw(self.get_root())
}
pub(crate) fn range_mut<'n, R, T>(&'n mut self, range: R) -> RangeMutIter<'n, K, V>
where
K: Borrow<T>,
T: Ord + ?Sized,
R: RangeBounds<T>,
{
RangeMutIter::new(self, range)
}
}
impl<K: Clone + Ord + Debug, V: Clone> Extend<(K, V)> for CursorWrite<K, V> {
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
iter.into_iter().for_each(|(k, v)| {
let _ = self.insert(k, v);
});
}
}
impl<K: Clone + Ord + Debug, V: Clone> Drop for CursorWrite<K, V> {
fn drop(&mut self) {
// If there is content in first_seen, this means we aborted and must rollback
// of these items!
// println!("Releasing CW FS -> {:?}", self.first_seen);
self.first_seen.iter().for_each(|n| Node::free(*n))
}
}
impl<K: Clone + Ord + Debug, V: Clone> Drop for CursorRead<K, V> {
fn drop(&mut self) {
// If there is content in last_seen, a future generation wants us to remove it!
let last_seen_guard = self
.last_seen
.try_lock()
.expect("Unable to lock, something is horridly wrong!");
last_seen_guard.iter().for_each(|n| Node::free(*n));
std::mem::drop(last_seen_guard);
}
}
impl<K: Clone + Ord + Debug, V: Clone> Drop for SuperBlock<K, V> {
fn drop(&mut self) {
// eprintln!("Releasing SuperBlock ...");
// We must be the last SB and no txns exist. Drop the tree now.
// TODO: Calc this based on size.
let mut first_seen = Vec::with_capacity(16);
// eprintln!("{:?}", self.root);
first_seen.push(self.root);
Node::sblock_collect_raw(self.root, &mut first_seen);
first_seen.iter().for_each(|n| Node::free(*n));
}
}
impl<K: Clone + Ord + Debug, V: Clone> CursorRead<K, V> {
pub(crate) fn new(sblock: &SuperBlock<K, V>) -> Self {
// println!("starting rd txid -> {:?}", sblock.txid);
CursorRead {
txid: sblock.txid,
length: sblock.size,
root: sblock.root,
last_seen: Mutex::new(Vec::with_capacity(0)),
}
}
}
impl<K: Clone + Ord + Debug, V: Clone> CursorReadOps<K, V> for CursorRead<K, V> {
fn get_root_ref(&self) -> &Node<K, V> {
unsafe { &*(self.root) }
}
fn get_root(&self) -> *mut Node<K, V> {
self.root
}
fn len(&self) -> usize {
self.length
}
fn get_txid(&self) -> u64 {
self.txid
}
}
impl<K: Clone + Ord + Debug, V: Clone> CursorReadOps<K, V> for CursorWrite<K, V> {
fn get_root_ref(&self) -> &Node<K, V> {
unsafe { &*(self.root) }
}
fn get_root(&self) -> *mut Node<K, V> {
self.root
}
fn len(&self) -> usize {
self.length
}
fn get_txid(&self) -> u64 {
self.txid
}
}
fn clone_and_insert<K: Clone + Ord + Debug, V: Clone>(
node: *mut Node<K, V>,
txid: u64,
k: K,
v: V,
last_seen: &mut Vec<*mut Node<K, V>>,
first_seen: &mut Vec<*mut Node<K, V>>,
) -> CRInsertState<K, V> {
/*
* Let's talk about the magic of this function. Come, join
* me around the [🔥🔥🔥]
*
* This function is the heart and soul of a copy on write
* structure - as we progress to the leaf location where we
* wish to perform an alteration, we clone (if required) all
* nodes on the path. This way an abort (rollback) of the
* commit simply is to drop the cursor, where the "new"
* cloned values are only referenced. To commit, we only need
* to replace the tree root in the parent structures as
* the cloned path must by definition include the root, and
* will contain references to nodes that did not need cloning,
* thus keeping them alive.
*/
if self_meta!(node).is_leaf() {
// NOTE: We have to match, rather than map here, as rust tries to
// move k:v into both closures!
// Leaf path
match leaf_ref!(node, K, V).req_clone(txid) {
Some(cnode) => {
// println!();
first_seen.push(cnode);
// println!("ls push 5");
last_seen.push(node);
// Clone was required.
let mref = leaf_ref!(cnode, K, V);
// insert to the new node.
match mref.insert_or_update(k, v) {
LeafInsertState::Ok(res) => CRInsertState::Clone(res, cnode),
LeafInsertState::Split(rnode) => {
first_seen.push(rnode as *mut Node<K, V>);
// let rnode = Node::new_leaf_ins(txid, sk, sv);
CRInsertState::CloneSplit(cnode, rnode as *mut Node<K, V>)
}
LeafInsertState::RevSplit(lnode) => {
first_seen.push(lnode as *mut Node<K, V>);
CRInsertState::CloneRevSplit(cnode, lnode as *mut Node<K, V>)
}
}
}
None => {
// No clone required.
// simply do the insert.
let mref = leaf_ref!(node, K, V);
match mref.insert_or_update(k, v) {
LeafInsertState::Ok(res) => CRInsertState::NoClone(res),
LeafInsertState::Split(rnode) => {
// We split, but left is already part of the txn group, so lets
// just return what's new.
// let rnode = Node::new_leaf_ins(txid, sk, sv);
first_seen.push(rnode as *mut Node<K, V>);
CRInsertState::Split(rnode as *mut Node<K, V>)
}
LeafInsertState::RevSplit(lnode) => {
first_seen.push(lnode as *mut Node<K, V>);
CRInsertState::RevSplit(lnode as *mut Node<K, V>)
}
}
}
} // end match
} else {
// Branch path
// Decide if we need to clone - we do this as we descend due to a quirk in Arc
// get_mut, because we don't have access to get_mut_unchecked (and this api may
// never be stabilised anyway). When we change this to *mut + garbage lists we
// could consider restoring the reactive behaviour that clones up, rather than
// cloning down the path.
//
// NOTE: We have to match, rather than map here, as rust tries to
// move k:v into both closures!
match branch_ref!(node, K, V).req_clone(txid) {
Some(cnode) => {
first_seen.push(cnode);
last_seen.push(node);
// Not same txn, clone instead.
let nmref = branch_ref!(cnode, K, V);
let anode_idx = nmref.locate_node(&k);
let anode = nmref.get_idx_unchecked(anode_idx);
match clone_and_insert(anode, txid, k, v, last_seen, first_seen) {
CRInsertState::Clone(res, lnode) => {
nmref.replace_by_idx(anode_idx, lnode);
// Pass back up that we cloned.
CRInsertState::Clone(res, cnode)
}
CRInsertState::CloneSplit(lnode, rnode) => {
// CloneSplit here, would have already updated lnode/rnode into the
// gc lists.
// Second, we update anode_idx node with our lnode as the new clone.
nmref.replace_by_idx(anode_idx, lnode);
// Third we insert rnode - perfect world it's at anode_idx + 1, but
// we use the normal insert routine for now.
match nmref.add_node(rnode) {
BranchInsertState::Ok => CRInsertState::Clone(None, cnode),
BranchInsertState::Split(clnode, crnode) => {
// Create a new branch to hold these children.
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
// Return it
CRInsertState::CloneSplit(cnode, nrnode as *mut Node<K, V>)
}
}
}
CRInsertState::CloneRevSplit(nnode, lnode) => {
nmref.replace_by_idx(anode_idx, nnode);
match nmref.add_node_left(lnode, anode_idx) {
BranchInsertState::Ok => CRInsertState::Clone(None, cnode),
BranchInsertState::Split(clnode, crnode) => {
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
CRInsertState::CloneSplit(cnode, nrnode as *mut Node<K, V>)
}
}
}
CRInsertState::NoClone(_res) => {
// If our descendant did not clone, then we don't have to either.
unreachable!("Should never be possible.");
// CRInsertState::NoClone(res)
}
CRInsertState::Split(_rnode) => {
// I think
unreachable!("This represents a corrupt tree state");
}
CRInsertState::RevSplit(_lnode) => {
unreachable!("This represents a corrupt tree state");
}
} // end match
} // end Some,
None => {
let nmref = branch_ref!(node, K, V);
let anode_idx = nmref.locate_node(&k);
let anode = nmref.get_idx_unchecked(anode_idx);
match clone_and_insert(anode, txid, k, v, last_seen, first_seen) {
CRInsertState::Clone(res, lnode) => {
nmref.replace_by_idx(anode_idx, lnode);
// We did not clone, and no further work needed.
CRInsertState::NoClone(res)
}
CRInsertState::NoClone(res) => {
// If our descendant did not clone, then we don't have to do any adjustments
// or further work.
CRInsertState::NoClone(res)
}
CRInsertState::Split(rnode) => {
match nmref.add_node(rnode) {
// Similar to CloneSplit - we are either okay, and the insert was happy.
BranchInsertState::Ok => CRInsertState::NoClone(None),
// Or *we* split as well, and need to return a new sibling branch.
BranchInsertState::Split(clnode, crnode) => {
// Create a new branch to hold these children.
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
// Return it
CRInsertState::Split(nrnode as *mut Node<K, V>)
}
}
}
CRInsertState::CloneSplit(lnode, rnode) => {
// work inplace.
// Second, we update anode_idx node with our lnode as the new clone.
nmref.replace_by_idx(anode_idx, lnode);
// Third we insert rnode - perfect world it's at anode_idx + 1, but
// we use the normal insert routine for now.
match nmref.add_node(rnode) {
// Similar to CloneSplit - we are either okay, and the insert was happy.
BranchInsertState::Ok => CRInsertState::NoClone(None),
// Or *we* split as well, and need to return a new sibling branch.
BranchInsertState::Split(clnode, crnode) => {
// Create a new branch to hold these children.
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
// Return it
CRInsertState::Split(nrnode as *mut Node<K, V>)
}
}
}
CRInsertState::RevSplit(lnode) => match nmref.add_node_left(lnode, anode_idx) {
BranchInsertState::Ok => CRInsertState::NoClone(None),
BranchInsertState::Split(clnode, crnode) => {
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
CRInsertState::Split(nrnode as *mut Node<K, V>)
}
},
CRInsertState::CloneRevSplit(nnode, lnode) => {
nmref.replace_by_idx(anode_idx, nnode);
match nmref.add_node_left(lnode, anode_idx) {
BranchInsertState::Ok => CRInsertState::NoClone(None),
BranchInsertState::Split(clnode, crnode) => {
let nrnode = Node::new_branch(txid, clnode, crnode);
first_seen.push(nrnode as *mut Node<K, V>);
CRInsertState::Split(nrnode as *mut Node<K, V>)
}
}
}
} // end match
}
} // end match branch ref clone
} // end if leaf
}
fn path_clone<K: Clone + Ord + Debug, V: Clone>(
node: *mut Node<K, V>,
txid: u64,
k: &K,
last_seen: &mut Vec<*mut Node<K, V>>,
first_seen: &mut Vec<*mut Node<K, V>>,
) -> CRCloneState<K, V> {
if unsafe { (*node).is_leaf() } {
unsafe {
(*(node as *mut Leaf<K, V>))
.req_clone(txid)
.map(|cnode| {
// Track memory
last_seen.push(node);
// println!("ls push 7 {:?}", node);
first_seen.push(cnode);
CRCloneState::Clone(cnode)
})
.unwrap_or(CRCloneState::NoClone)
}
} else {
// We are in a branch, so locate our descendent and prepare
// to clone if needed.
// println!("txid -> {:?} {:?}", node_txid, txid);
let nmref = branch_ref!(node, K, V);
let anode_idx = nmref.locate_node(k);
let anode = nmref.get_idx_unchecked(anode_idx);
match path_clone(anode, txid, k, last_seen, first_seen) {
CRCloneState::Clone(cnode) => {
// Do we need to clone?
nmref
.req_clone(txid)
.map(|acnode| {
// We require to be cloned.
last_seen.push(node);
// println!("ls push 8");
first_seen.push(acnode);
let nmref = branch_ref!(acnode, K, V);
nmref.replace_by_idx(anode_idx, cnode);
CRCloneState::Clone(acnode)
})
.unwrap_or_else(|| {
// Nope, just insert and unwind.
nmref.replace_by_idx(anode_idx, cnode);
CRCloneState::NoClone
})
}
CRCloneState::NoClone => {
// Did not clone, unwind.
CRCloneState::NoClone
}
}
}
}
fn clone_and_remove<K: Clone + Ord + Debug, V: Clone>(
node: *mut Node<K, V>,
txid: u64,
k: &K,
last_seen: &mut Vec<*mut Node<K, V>>,
first_seen: &mut Vec<*mut Node<K, V>>,
) -> CRRemoveState<K, V> {
if self_meta!(node).is_leaf() {
leaf_ref!(node, K, V)
.req_clone(txid)
.map(|cnode| {
first_seen.push(cnode);
// println!("ls push 10 {:?}", node);
last_seen.push(node);
let mref = leaf_ref!(cnode, K, V);
match mref.remove(k) {
LeafRemoveState::Ok(res) => CRRemoveState::Clone(res, cnode),
LeafRemoveState::Shrink(res) => CRRemoveState::CloneShrink(res, cnode),
}
})
.unwrap_or_else(|| {
let mref = leaf_ref!(node, K, V);
match mref.remove(k) {
LeafRemoveState::Ok(res) => CRRemoveState::NoClone(res),
LeafRemoveState::Shrink(res) => CRRemoveState::Shrink(res),
}
})
} else {
// Locate the node we need to work on and then react if it
// requests a shrink.
branch_ref!(node, K, V)
.req_clone(txid)
.map(|cnode| {
first_seen.push(cnode);
// println!("ls push 11 {:?}", node);
last_seen.push(node);
// Done mm
let nmref = branch_ref!(cnode, K, V);
let anode_idx = nmref.locate_node(k);
let anode = nmref.get_idx_unchecked(anode_idx);
match clone_and_remove(anode, txid, k, last_seen, first_seen) {
CRRemoveState::NoClone(_res) => {
unreachable!("Should never occur");
}
CRRemoveState::Clone(res, lnode) => {
nmref.replace_by_idx(anode_idx, lnode);
CRRemoveState::Clone(res, cnode)
}
CRRemoveState::Shrink(_res) => {
unreachable!("This represents a corrupt tree state");
}
CRRemoveState::CloneShrink(res, nnode) => {
// Put our cloned child into the tree at the correct location, don't worry,
// the shrink_decision will deal with it.
nmref.replace_by_idx(anode_idx, nnode);
// Now setup the sibling, to the left *or* right.
let right_idx =
nmref.clone_sibling_idx(txid, anode_idx, last_seen, first_seen);
// Okay, now work out what we need to do.
match nmref.shrink_decision(right_idx) {
BranchShrinkState::Balanced => {
// K:V were distributed through left and right,
// so no further action needed.
CRRemoveState::Clone(res, cnode)
}
BranchShrinkState::Merge(dnode) => {
// Right was merged to left, and we remain
// valid
debug_assert!(!last_seen.contains(&dnode));
last_seen.push(dnode);