forked from cdacamar/fredbuf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfredbuf.cpp
More file actions
2615 lines (2388 loc) · 103 KB
/
fredbuf.cpp
File metadata and controls
2615 lines (2388 loc) · 103 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
#include "fredbuf.h"
#include <cassert>
#include "enum-utils.h"
#include "macros.h"
#include "os.h"
#include "scope-guard.h"
#include "util.h"
namespace PieceTree
{
#ifdef COUNT_ALLOC
size_t alloc_count;
size_t dealloc_count;
#endif
constexpr LFCount operator+(LFCount lhs, LFCount rhs)
{
return LFCount{ rep(lhs) + rep(rhs) };
}
namespace
{
bool nil_node(const RBNodeCounted* node)
{
return node == &null_node_inst;
}
RBNodeCounted* nil_node()
{
return &null_node_inst;
}
} // namespace [anon]
// Counted node management.
void dec_node_ref(const RBNodeCounted* node)
{
if (nil_node(node))
return;
uint64_t count = os_atomic_u64_dec_eval(&node->blk->ref_count);
if (count == 0)
{
dec_node_ref(node->payload.left);
dec_node_ref(node->payload.right);
// Finally, detach this node and add to the free list atomically.
RBNodeFreeList old_head{};
RBNodeFreeList next_head{};
static_assert(alignof(RBNodeFreeList) == 16);
os_atomic_u128_eval(&node->blk->base_blk->free_list, &old_head);
RBNodeCounted* mut_node = const_cast<RBNodeCounted*>(node);
do
{
mut_node->free_next = old_head.head;
next_head.head = mut_node;
next_head.tag = old_head.tag + 1;
} while (not os_atomic_u128_eval_cond_assign(&node->blk->base_blk->free_list, next_head, &old_head));
}
}
const RBNodeCounted* take_node_ref(const RBNodeCounted* node)
{
if (not nil_node(node))
{
FRED_UNUSED_RESULT(os_atomic_u64_inc_eval(&node->blk->ref_count));
}
return node;
}
const RBNodeCounted* make_node(RBTreeBlock* blk, Color c, const RBNodeCounted* lft, const NodeData& data, const RBNodeCounted* rgt)
{
RBNodeCounted* node = nil_node();
RBNodeBlock* node_blk = nullptr;
// Try to fetch a node from the free list atomically.
{
RBNodeFreeList old_head;
RBNodeFreeList next_head{};
os_atomic_u128_eval(&blk->free_list, &old_head);
do
{
if (nil_node(old_head.head))
{
node = nil_node();
break;
}
node = old_head.head;
next_head.head = old_head.head->free_next;
next_head.tag = old_head.tag + 1;
} while (not os_atomic_u128_eval_cond_assign(&blk->free_list, next_head, &old_head));
if (not nil_node(node))
{
node_blk = node->blk;
}
}
if (nil_node(node))
{
node = Arena::push_array_no_zero<RBNodeCounted>(blk->alloc_arena, 1);
node_blk = Arena::push_array<RBNodeBlock>(blk->alloc_arena, 1);
}
zero_bytes(node);
zero_bytes(node_blk);
// Set pointer trees to null.
node->payload.left = node->payload.right = nil_node();
node_blk->base_blk = blk;
node->payload.left = take_node_ref(lft);
node->payload.data = data;
node->payload.right = take_node_ref(rgt);
node->payload.color = c;
node->blk = node_blk;
return node;
}
RedBlackTree::RedBlackTree(RedBlackTree&& other):
root_node{ other.root_node }
{
other.root_node = nil_node();
}
RedBlackTree& RedBlackTree::operator=(RedBlackTree&& other)
{
// Swap these, so the dtor for 'other' will handle decrementing the ref.
const RBNodeCounted* old_root = root_node;
root_node = other.root_node;
other.root_node = old_root;
return *this;
}
RedBlackTree::~RedBlackTree()
{
dec_node_ref(root_node);
}
const RBNodeCounted* RedBlackTree::root_ptr() const
{
return root_node;
}
bool RedBlackTree::is_empty() const
{
return nil_node(root_node);
}
const NodeData& RedBlackTree::root() const
{
assert(not is_empty());
return root_node->payload.data;
}
RedBlackTree RedBlackTree::left() const
{
assert(not is_empty());
return RedBlackTree(root_node->payload.left);
}
RedBlackTree RedBlackTree::right() const
{
assert(not is_empty());
return RedBlackTree(root_node->payload.right);
}
Color RedBlackTree::root_color() const
{
assert(!is_empty());
return root_node->payload.color;
}
RedBlackTree RedBlackTree::insert(RBTreeBlock* blk, const NodeData& x, Offset at) const
{
RedBlackTree t = ins(blk, x, at, Offset{ 0 });
return RedBlackTree(blk, Color::Black, t.left(), t.root(), t.right());
}
RedBlackTree::RedBlackTree(RBTreeBlock* blk,
Color c,
const RedBlackTree& lft,
const NodeData& val,
const RedBlackTree& rgt)
: root_node(take_node_ref(make_node(blk, c, lft.root_node, attribute(val, lft), rgt.root_node)))
{
}
RedBlackTree::RedBlackTree(const RBNodeCounted* node):
root_node(take_node_ref(node))
{
}
RedBlackTree RedBlackTree::ins(RBTreeBlock* blk, const NodeData& x, Offset at, Offset total_offset) const
{
if (is_empty())
return RedBlackTree(blk, Color::Red, RedBlackTree(), x, RedBlackTree());
const NodeData& y = root();
if (at < total_offset + y.left_subtree_length + y.piece.length)
return balance(blk, root_color(), left().ins(blk, x, at, total_offset), y, right());
return balance(blk, root_color(), left(), y, right().ins(blk, x, at, total_offset + y.left_subtree_length + y.piece.length));
}
RedBlackTree RedBlackTree::balance(RBTreeBlock* blk, Color c, const RedBlackTree& lft, const NodeData& x, const RedBlackTree& rgt)
{
if (c == Color::Black and lft.doubled_left())
return RedBlackTree(blk, Color::Red,
lft.left().paint(blk, Color::Black),
lft.root(),
RedBlackTree(blk, Color::Black,
lft.right(),
x,
rgt));
else if (c == Color::Black and lft.doubled_right())
return RedBlackTree(blk, Color::Red,
RedBlackTree(blk, Color::Black,
lft.left(),
lft.root(),
lft.right().left()),
lft.right().root(),
RedBlackTree(blk, Color::Black,
lft.right().right(),
x,
rgt));
else if (c == Color::Black and rgt.doubled_left())
return RedBlackTree(blk, Color::Red,
RedBlackTree(blk, Color::Black,
lft,
x,
rgt.left().left()),
rgt.left().root(),
RedBlackTree(blk, Color::Black,
rgt.left().right(),
rgt.root(),
rgt.right()));
else if (c == Color::Black and rgt.doubled_right())
return RedBlackTree(blk, Color::Red,
RedBlackTree(blk, Color::Black,
lft,
x,
rgt.left()),
rgt.root(),
rgt.right().paint(blk, Color::Black));
return RedBlackTree(blk, c, lft, x, rgt);
}
bool RedBlackTree::doubled_left() const
{
return not is_empty()
and root_color() == Color::Red
and not left().is_empty()
and left().root_color() == Color::Red;
}
bool RedBlackTree::doubled_right() const
{
return not is_empty()
and root_color() == Color::Red
and not right().is_empty()
and right().root_color() == Color::Red;
}
RedBlackTree RedBlackTree::paint(RBTreeBlock* blk, Color c) const
{
assert(not is_empty());
return RedBlackTree(blk, c, left(), root(), right());
}
PieceTree::Length tree_length(const RedBlackTree& root)
{
if (root.is_empty())
return { };
return root.root().left_subtree_length + root.root().piece.length + tree_length(root.right());
}
PieceTree::LFCount tree_lf_count(const RedBlackTree& root)
{
if (root.is_empty())
return { };
return root.root().left_subtree_lf_count + root.root().piece.newline_count + tree_lf_count(root.right());
}
NodeData attribute(const NodeData& data, const RedBlackTree& left)
{
auto new_data = data;
new_data.left_subtree_length = tree_length(left);
new_data.left_subtree_lf_count = tree_lf_count(left);
return new_data;
}
struct WalkResult
{
RedBlackTree tree;
Offset accumulated_offset;
};
WalkResult pred(const RedBlackTree& root, Offset start_offset)
{
RedBlackTree t = root.left();
while (!t.right().is_empty())
{
start_offset = start_offset + t.root().left_subtree_length + t.root().piece.length;
t = t.right();
}
// Add the final offset from the last right node.
start_offset = start_offset + t.root().left_subtree_length;
return { .tree = t.dup(), .accumulated_offset = start_offset };
}
#ifdef EXPERIMENTAL_REMOVE
struct RedBlackTree::ColorTree
{
const Color color;
const RedBlackTree tree;
static ColorTree double_black()
{
return ColorTree();
}
explicit ColorTree(RedBlackTree const &tree)
: color(tree.is_empty() ? Color::Black : tree.root_color()), tree(tree)
{
}
explicit ColorTree(Color c, const RedBlackTree& lft, const NodeData& x, const RedBlackTree& rgt)
: color(c), tree(c, lft, x, rgt)
{
}
private:
ColorTree(): color(Color::DoubleBlack)
{
}
};
RedBlackTree RedBlackTree::remove(Offset at) const
{
auto t = rem(at, Offset{ 0 }).tree;
if (t.is_empty())
return RedBlackTree();
return RedBlackTree(Color::Black, t.left(), t.root(), t.right());
}
RedBlackTree::ColorTree RedBlackTree::remove_double_black(Color c, ColorTree const &lft, const NodeData& x, ColorTree const &rgt)
{
if (lft.color == Color::DoubleBlack)
{
auto left = lft.tree.is_empty() ? RedBlackTree() : lft.tree.paint(Color::Black);
if (rgt.color == Color::Black)
{
assert(c != Color::DoubleBlack);
return ColorTree(extend(c), left, x, rgt.tree.paint(Color::Red));
}
else
return ColorTree(Color::Black, RedBlackTree(Color::Black, left, x, rgt.tree.left().paint(Color::Red)), rgt.tree.root(), rgt.tree.right());
}
else if (rgt.color == Color::DoubleBlack)
{
auto right = rgt.tree.is_empty() ? RedBlackTree() : rgt.tree.paint(Color::Black);
if (lft.color == Color::Black)
{
assert(c != Color::DoubleBlack);
return ColorTree(extend(c), lft.tree.paint(Color::Red), x, right);
}
else
return ColorTree(Color::Black, lft.tree.left(), lft.tree.root(), RedBlackTree(Color::Black, lft.tree.right().paint(Color::Red), x, right));
}
else
return ColorTree(c, lft.tree, x, rgt.tree);
}
RedBlackTree::ColorTree RedBlackTree::rem(Offset at, Offset total) const
{
if (is_empty())
return ColorTree(RedBlackTree());
const NodeData& y = root();
if (at < total + y.left_subtree_length)
return remove_double_black(root_color(), left().rem(at, total), y, ColorTree(right()));
if (at == total + y.left_subtree_length)
return remove_node();
return remove_double_black(root_color(), ColorTree(left()), y, right().rem(at, total + y.left_subtree_length + y.piece.length));
}
RedBlackTree::ColorTree RedBlackTree::remove_node() const
{
if (not left().is_empty()
and not right().is_empty())
{
auto [p, off] = pred(*this, Offset(0));
const NodeData& x = p.root();
Color c = root_color();
return remove_double_black(c, left().rem(off, Offset(0)), x, ColorTree(right()));
}
else if (not left().is_empty())
{
return ColorTree(left().paint(Color::Black));
}
else if (not right().is_empty())
{
return ColorTree(right().paint(Color::Black));
}
else if (root_color() == Color::Black)
{
return ColorTree::double_black();
}
return ColorTree(RedBlackTree());
}
#else
RedBlackTree RedBlackTree::remove(RBTreeBlock* blk, Offset at) const
{
auto t = rem(blk, *this, at, Offset{ 0 });
if (t.is_empty())
return RedBlackTree();
return RedBlackTree(blk, Color::Black, t.left(), t.root(), t.right());
}
RedBlackTree RedBlackTree::dup() const
{
return RedBlackTree(root_node);
}
RedBlackTree RedBlackTree::fuse(RBTreeBlock* blk, const RedBlackTree& left, const RedBlackTree& right)
{
// match: (left, right)
// case: (None, r)
if (left.is_empty())
return right.dup();
if (right.is_empty())
return left.dup();
// match: (left.color, right.color)
// case: (B, R)
if (left.root_color() == Color::Black and right.root_color() == Color::Red)
{
return RedBlackTree(blk, Color::Red,
fuse(blk, left, right.left()),
right.root(),
right.right());
}
// case: (R, B)
if (left.root_color() == Color::Red and right.root_color() == Color::Black)
{
return RedBlackTree(blk, Color::Red,
left.left(),
left.root(),
fuse(blk, left.right(), right));
}
// case: (R, R)
if (left.root_color() == Color::Red and right.root_color() == Color::Red)
{
auto fused = fuse(blk, left.right(), right.left());
if (not fused.is_empty() and fused.root_color() == Color::Red)
{
auto new_left = RedBlackTree(blk, Color::Red,
left.left(),
left.root(),
fused.left());
auto new_right = RedBlackTree(blk, Color::Red,
fused.right(),
right.root(),
right.right());
return RedBlackTree(blk, Color::Red,
new_left,
fused.root(),
new_right);
}
auto new_right = RedBlackTree(blk, Color::Red,
fused,
right.root(),
right.right());
return RedBlackTree(blk, Color::Red,
left.left(),
left.root(),
new_right);
}
// case: (B, B)
assert(left.root_color() == right.root_color() and left.root_color() == Color::Black);
auto fused = fuse(blk, left.right(), right.left());
if (not fused.is_empty() and fused.root_color() == Color::Red)
{
auto new_left = RedBlackTree(blk, Color::Black,
left.left(),
left.root(),
fused.left());
auto new_right = RedBlackTree(blk, Color::Black,
fused.right(),
right.root(),
right.right());
return RedBlackTree(blk, Color::Red,
new_left,
fused.root(),
new_right);
}
auto new_right = RedBlackTree(blk, Color::Black,
fused,
right.root(),
right.right());
auto new_node = RedBlackTree(blk, Color::Red,
left.left(),
left.root(),
new_right);
return balance_left(blk, new_node);
}
RedBlackTree RedBlackTree::balance(RBTreeBlock* blk, const RedBlackTree& node)
{
// Two red children.
if (not node.left().is_empty()
and node.left().root_color() == Color::Red
and not node.right().is_empty()
and node.right().root_color() == Color::Red)
{
auto l = node.left().paint(blk, Color::Black);
auto r = node.right().paint(blk, Color::Black);
return RedBlackTree(blk,
Color::Red,
l,
node.root(),
r);
}
assert(node.root_color() == Color::Black);
return balance(blk, node.root_color(), node.left(), node.root(), node.right());
}
RedBlackTree RedBlackTree::balance_left(RBTreeBlock* blk, const RedBlackTree& left)
{
// match: (color_l, color_r, color_r_l)
// case: (Some(R), ..)
if (not left.left().is_empty() and left.left().root_color() == Color::Red)
{
return RedBlackTree(blk, Color::Red,
left.left().paint(blk, Color::Black),
left.root(),
left.right());
}
// case: (_, Some(B), _)
if (not left.right().is_empty() and left.right().root_color() == Color::Black)
{
auto new_left = RedBlackTree(blk, Color::Black,
left.left(),
left.root(),
left.right().paint(blk, Color::Red));
return balance(blk, new_left);
}
// case: (_, Some(R), Some(B))
if (not left.right().is_empty() and left.right().root_color() == Color::Red
and not left.right().left().is_empty() and left.right().left().root_color() == Color::Black)
{
auto unbalanced_new_right = RedBlackTree(blk, Color::Black,
left.right().left().right(),
left.right().root(),
left.right().right().paint(blk, Color::Red));
auto new_right = balance(blk, unbalanced_new_right);
auto new_left = RedBlackTree(blk, Color::Black,
left.left(),
left.root(),
left.right().left().left());
return RedBlackTree(blk, Color::Red,
new_left,
left.right().left().root(),
new_right);
}
assert(!"impossible");
return left.dup();
}
RedBlackTree RedBlackTree::balance_right(RBTreeBlock* blk, const RedBlackTree& right)
{
// match: (color_l, color_l_r, color_r)
// case: (.., Some(R))
if (not right.right().is_empty() and right.right().root_color() == Color::Red)
{
return RedBlackTree(blk, Color::Red,
right.left(),
right.root(),
right.right().paint(blk, Color::Black));
}
// case: (Some(B), ..)
if (not right.left().is_empty() and right.left().root_color() == Color::Black)
{
auto new_right = RedBlackTree(blk, Color::Black,
right.left().paint(blk, Color::Red),
right.root(),
right.right());
return balance(blk, new_right);
}
// case: (Some(R), Some(B), _)
if (not right.left().is_empty() and right.left().root_color() == Color::Red
and not right.left().right().is_empty() and right.left().right().root_color() == Color::Black)
{
auto unbalanced_new_left = RedBlackTree(blk, Color::Black,
// Note: Because 'left' is red, it must have a left child.
right.left().left().paint(blk, Color::Red),
right.left().root(),
right.left().right().left());
auto new_left = balance(blk, unbalanced_new_left);
auto new_right = RedBlackTree(blk, Color::Black,
right.left().right().right(),
right.root(),
right.right());
return RedBlackTree(blk, Color::Red,
new_left,
right.left().right().root(),
new_right);
}
assert(!"impossible");
return right.dup();
}
RedBlackTree RedBlackTree::remove_left(RBTreeBlock* blk, const RedBlackTree& root, Offset at, Offset total)
{
auto new_left = rem(blk, root.left(), at, total);
auto new_node = RedBlackTree(blk, Color::Red,
new_left,
root.root(),
root.right());
// In this case, the root was a red node and must've had at least two children.
if (not root.left().is_empty()
and root.left().root_color() == Color::Black)
return balance_left(blk, new_node);
return new_node;
}
RedBlackTree RedBlackTree::remove_right(RBTreeBlock* blk, const RedBlackTree& root, Offset at, Offset total)
{
const NodeData& y = root.root();
auto new_right = rem(blk, root.right(), at, total + y.left_subtree_length + y.piece.length);
auto new_node = RedBlackTree(blk, Color::Red,
root.left(),
root.root(),
new_right);
// In this case, the root was a red node and must've had at least two children.
if (not root.right().is_empty()
and root.right().root_color() == Color::Black)
return balance_right(blk, new_node);
return new_node;
}
RedBlackTree RedBlackTree::rem(RBTreeBlock* blk, const RedBlackTree& root, Offset at, Offset total)
{
if (root.is_empty())
return RedBlackTree();
const NodeData& y = root.root();
if (at < total + y.left_subtree_length)
return remove_left(blk, root, at, total);
if (at == total + y.left_subtree_length)
return fuse(blk, root.left(), root.right());
return remove_right(blk, root, at, total);
}
#endif // EXPERIMENTAL_REMOVE
#ifdef TEXTBUF_DEBUG
// Borrowed from https://github.com/dotnwat/persistent-rbtree/blob/master/tree.h:checkConsistency.
int check_black_node_invariant(const RedBlackTree& node)
{
if (node.is_empty())
return 1;
if (node.root_color() == Color::Red and
((not node.left().is_empty() and node.left().root_color() == Color::Red)
or (not node.right().is_empty() and node.right().root_color() == Color::Red)))
{
return 1;
}
auto l = check_black_node_invariant(node.left());
auto r = check_black_node_invariant(node.right());
if (l != 0 and r != 0 and l != r)
return 0;
if (l != 0 and r != 0)
return node.root_color() == Color::Red ? l : l + 1;
return 0;
}
void satisfies_rb_invariants(const RedBlackTree& root)
{
// 1. Every node is either red or black.
// 2. All NIL nodes (figure 1) are considered black.
// 3. A red node does not have a red child.
// 4. Every path from a given node to any of its descendant NIL nodes goes through the same number of black nodes.
// The internal nodes in this RB tree can be totally black so we will not count them directly, we'll just track
// odd nodes as either red or black.
// Measure the number of black nodes we need to validate.
if (root.is_empty()
or (root.left().is_empty() and root.right().is_empty()))
return;
assert(check_black_node_invariant(root) != 0);
}
#endif // TEXTBUF_DEBUG
} // namespace PieceTree
namespace PieceTree
{
namespace
{
struct LineStartsNode
{
LineStartsNode* next;
LineStart start;
};
struct LineStartsList
{
LineStartsNode* first;
LineStartsNode* last;
uint64_t count;
};
void push_line_starts_node(Arena::Arena* arena, LineStartsList* lst, LineStart start)
{
LineStartsNode* node = Arena::push_array<LineStartsNode>(arena, 1);
node->start = start;
SLLQueuePush(lst->first, lst->last, node);
++lst->count;
}
LineStarts join_line_starts_list(Arena::Arena* arena, const LineStartsList& lst)
{
LineStarts result{};
result.starts = Arena::push_array_no_zero<LineStart>(arena, lst.count);
result.count = lst.count;
uint64_t i = 0;
for EachNode(n, lst.first)
{
result.starts[i++] = n->start;
}
return result;
}
void populate_line_starts(Arena::Arena* arena, LineStarts* starts, String8 buf)
{
LineStartsList lst{};
LineStart start { };
auto scratch = Arena::scratch_begin({ &arena, 1 });
push_line_starts_node(scratch.arena, &lst, start);
for EachIndex(i, buf.size)
{
char c = buf.str[i];
if (c == '\n')
{
start = LineStart{ i + 1 };
push_line_starts_node(scratch.arena, &lst, start);
}
}
*starts = join_line_starts_list(arena, lst);
Arena::scratch_end(scratch);
}
void compute_buffer_meta(BufferMeta* meta, const RedBlackTree& root)
{
meta->lf_count = tree_lf_count(root);
meta->total_content_length = tree_length(root);
}
void append_mut_buf_start(BufferCollection* collection, LineStart start)
{
LineStart* new_starts = Arena::push_array_no_zero_aligned<LineStart>(collection->mut_buf_starts_arena, 1, Arena::Alignment{ alignof(LineStart) });
LineStarts* starts = &collection->mod_buffer.line_starts;
assert(starts->starts + starts->count == new_starts);
new_starts[0] = start;
++starts->count;
}
void grow_mut_buf(BufferCollection* collection, uint64_t grow_by)
{
if (grow_by == 0)
return;
char* buf = Arena::push_array_no_zero_aligned<char>(collection->mut_buf_arena, grow_by, Arena::Alignment{ alignof(char) });
FRED_UNUSED(buf);
// When this buffer is created, it was originally designated a null-terminator slot at the beginning, so new buffers we
// allocate will need a null-terminator appended.
assert(collection->mod_buffer.buffer.str + collection->mod_buffer.buffer.size + 1 == buf);
// Note: We do not change the base of 'str', only its size.
collection->mod_buffer.buffer.size += grow_by;
// Append our null to the newly returned buffer piece.
collection->mod_buffer.buffer.str[collection->mod_buffer.buffer.size] = 0;
}
} // namespace [anon]
const CharBuffer* BufferCollection::buffer_at(BufferIndex index) const
{
if (index == BufferIndex::ModBuf)
return &mod_buffer;
return &orig_buffers.buffers[rep(index)];
}
CharOffset BufferCollection::buffer_offset(BufferIndex index, const BufferCursor& cursor) const
{
LineStart* starts = buffer_at(index)->line_starts.starts;
return CharOffset{ rep(starts[rep(cursor.line)]) + rep(cursor.column) };
}
// Buffer collection management.
void dec_buffer_ref(BufferCollection* collection)
{
uint64_t count = os_atomic_u64_dec_eval(collection->orig_buffers.ref_count);
if (count == 0)
{
// Note: The arena used to allocate nodes is the same one for the immutable buffers,
// so we do not need to release it.
Arena::release(collection->mut_buf_starts_arena);
Arena::release(collection->undo_redo_stack_arena);
Arena::release(collection->mut_buf_arena);
Arena::release(collection->immutable_buf_arena);
}
}
BufferCollection take_buffer_ref(const BufferCollection* collection)
{
FRED_UNUSED_RESULT(os_atomic_u64_inc_eval(collection->orig_buffers.ref_count));
return *collection;
}
Tree::Tree(BufferCollection buffers):
buffers{ buffers }
{
build_tree();
}
void Tree::build_tree()
{
// First, take a reference to this immutable buffer set.
take_buffer_ref(&buffers);
// Note: The buffers were populated with valid array starts from the builder.
// In order to maintain the invariant of other buffers, the mod_buffer needs a single line-start of 0.
append_mut_buf_start(&buffers, {});
last_insert = { };
const auto buf_count = buffers.orig_buffers.count;
CharOffset offset = { };
for (size_t i = 0; i < buf_count; ++i)
{
const CharBuffer* buf = &buffers.orig_buffers.buffers[i];
// Enforced by 'populate_line_starts'.
assert(buf->line_starts.count != 0);
// If this immutable buffer is empty, we can avoid creating a piece for it altogether.
if (buf->buffer.size == 0)
continue;
auto last_line = Line{ buf->line_starts.count - 1 };
// Create a new node that spans this buffer and retains an index to it.
// Insert the node into the balanced tree.
Piece piece {
.index = BufferIndex{ i },
.first = { .line = Line{ 0 }, .column = Column{ 0 } },
.last = { .line = last_line, .column = Column{ buf->buffer.size - rep(buf->line_starts.starts[rep(last_line)]) } },
.length = Length{ buf->buffer.size },
// Note: the number of newlines
.newline_count = LFCount{ rep(last_line) }
};
root = root.insert(buffers.rb_tree_blk, { piece }, offset);
offset = offset + piece.length;
}
compute_buffer_meta();
}
void Tree::internal_insert(CharOffset offset, String8 txt)
{
assert(txt.size != 0);
end_last_insert = extend(offset, txt.size);
ScopeGuard guard{ [&] {
compute_buffer_meta();
#ifdef TEXTBUF_DEBUG
satisfies_rb_invariants(root);
#endif // TEXTBUF_DEBUG
} };
if (root.is_empty())
{
auto piece = build_piece(txt);
root = root.insert(buffers.rb_tree_blk, { piece }, CharOffset{ 0 });
return;
}
auto result = node_at(&buffers, root.dup(), offset);
// If the offset is beyond the buffer, just select the last node.
if (result.node == nullptr)
{
auto off = CharOffset{ 0 };
if (meta.total_content_length != Length{})
{
off = off + retract(meta.total_content_length);
}
result = node_at(&buffers, root.dup(), off);
}
// There are 3 cases:
// 1. We are inserting at the beginning of an existing node.
// 2. We are inserting at the end of an existing node.
// 3. We are inserting in the middle of the node.
auto [node, remainder, node_start_offset, line] = result;
assert(node != nullptr);
auto insert_pos = buffer_position(&buffers, node->piece, remainder);
// Case #1.
if (node_start_offset == offset)
{
// There's a bonus case here. If our last insertion point was the same as this piece's
// last and it inserted into the mod buffer, then we can simply 'extend' this piece by
// the following process:
// 1. Fetch the previous node (if we can) and compare.
// 2. Build the new piece.
// 3. Remove the old piece.
// 4. Extend the old piece's length to the length of the newly created piece.
// 5. Re-insert the new piece.
if (offset != CharOffset{})
{
auto prev_node_result = node_at(&buffers, root.dup(), retract(offset));
if (prev_node_result.node->piece.index == BufferIndex::ModBuf
and prev_node_result.node->piece.last == last_insert)
{
auto new_piece = build_piece(txt);
combine_pieces(prev_node_result, new_piece);
return;
}
}
auto piece = build_piece(txt);
root = root.insert(buffers.rb_tree_blk, { piece }, offset);
return;
}
const bool inside_node = offset < node_start_offset + node->piece.length;
// Case #2.
if (not inside_node)
{
// There's a bonus case here. If our last insertion point was the same as this piece's
// last and it inserted into the mod buffer, then we can simply 'extend' this piece by
// the following process:
// 1. Build the new piece.
// 2. Remove the old piece.
// 3. Extend the old piece's length to the length of the newly created piece.
// 4. Re-insert the new piece.
if (node->piece.index == BufferIndex::ModBuf and node->piece.last == last_insert)
{
auto new_piece = build_piece(txt);
combine_pieces(result, new_piece);
return;
}
// Insert the new piece at the end.
auto piece = build_piece(txt);
root = root.insert(buffers.rb_tree_blk, { piece }, offset);
return;
}
// Case #3.
// The basic approach here is to split the existing node into two pieces
// and insert the new piece in between them.
auto new_len_right = distance(buffers.buffer_offset(node->piece.index, insert_pos),
buffers.buffer_offset(node->piece.index, node->piece.last));
auto new_piece_right = node->piece;
new_piece_right.first = insert_pos;
new_piece_right.length = new_len_right;
new_piece_right.newline_count = line_feed_count(&buffers, node->piece.index, insert_pos, node->piece.last);
// Remove the original node tail.
auto new_piece_left = trim_piece_right(&buffers, node->piece, insert_pos);
auto new_piece = build_piece(txt);
// Remove the original node.
root = root.remove(buffers.rb_tree_blk, node_start_offset);
// Insert the left.
root = root.insert(buffers.rb_tree_blk, { new_piece_left }, node_start_offset);
// Insert the new mid.
node_start_offset = node_start_offset + new_piece_left.length;
root = root.insert(buffers.rb_tree_blk, { new_piece }, node_start_offset);
// Insert remainder.
node_start_offset = node_start_offset + new_piece.length;
root = root.insert(buffers.rb_tree_blk, { new_piece_right }, node_start_offset);
}
void Tree::internal_remove(CharOffset offset, Length count)
{
assert(rep(count) != 0 and not root.is_empty());
ScopeGuard guard{ [&] {
compute_buffer_meta();
#ifdef TEXTBUF_DEBUG
satisfies_rb_invariants(root);
#endif // TEXTBUF_DEBUG
} };
auto first = node_at(&buffers, root.dup(), offset);
auto last = node_at(&buffers, root.dup(), offset + count);
auto first_node = first.node;
auto last_node = last.node;
auto start_split_pos = buffer_position(&buffers, first_node->piece, first.remainder);
// Simple case: the range of characters we want to delete are
// held directly within this node. Remove the node, resize it
// then add it back.
if (first_node == last_node)
{
auto end_split_pos = buffer_position(&buffers, first_node->piece, last.remainder);
// We're going to shrink the node starting from the beginning.
if (first.start_offset == offset)
{
// Delete the entire node.
if (count == first_node->piece.length)