forked from cdacamar/fredbuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fredbuf.cpp
2114 lines (1931 loc) · 78.8 KB
/
fredbuf.cpp
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 <memory>
#include <string_view>
#include <string>
#include <vector>
#include "enum-utils.h"
#include "scope-guard.h"
namespace PieceTree
{
constexpr LFCount operator+(LFCount lhs, LFCount rhs)
{
return LFCount{ rep(lhs) + rep(rhs) };
}
RedBlackTree::Node::Node(Color c, const NodePtr& lft, const NodeData& data, const NodePtr& rgt)
: color(c), left(lft), data(data), right(rgt)
{
}
const RedBlackTree::Node* RedBlackTree::root_ptr() const
{
return root_node.get();
}
bool RedBlackTree::is_empty() const
{
return not root_node;
}
const NodeData& RedBlackTree::root() const
{
assert(not is_empty());
return root_node->data;
}
RedBlackTree RedBlackTree::left() const
{
assert(not is_empty());
return RedBlackTree(root_node->left);
}
RedBlackTree RedBlackTree::right() const
{
assert(not is_empty());
return RedBlackTree(root_node->right);
}
Color RedBlackTree::root_color() const
{
assert(!is_empty());
return root_node->color;
}
RedBlackTree RedBlackTree::insert(const NodeData& x, Offset at) const
{
RedBlackTree t = ins(x, at, Offset{ 0 });
return RedBlackTree(Color::Black, t.left(), t.root(), t.right());
}
RedBlackTree::RedBlackTree(Color c,
const RedBlackTree& lft,
const NodeData& val,
const RedBlackTree& rgt)
: root_node(std::make_shared<Node>(c, lft.root_node, attribute(val, lft), rgt.root_node))
{
}
RedBlackTree::RedBlackTree(const NodePtr& node)
: root_node(node)
{
}
RedBlackTree RedBlackTree::ins(const NodeData& x, Offset at, Offset total_offset) const
{
if (is_empty())
return RedBlackTree(Color::Red, RedBlackTree(), x, RedBlackTree());
const NodeData& y = root();
if (at < total_offset + y.left_subtree_length + y.piece.length)
return balance(root_color(), left().ins(x, at, total_offset), y, right());
return balance(root_color(), left(), y, right().ins(x, at, total_offset + y.left_subtree_length + y.piece.length));
}
RedBlackTree RedBlackTree::balance(Color c, const RedBlackTree& lft, const NodeData& x, const RedBlackTree& rgt)
{
if (c == Color::Black and lft.doubled_left())
return RedBlackTree(Color::Red,
lft.left().paint(Color::Black),
lft.root(),
RedBlackTree(Color::Black,
lft.right(),
x,
rgt));
else if (c == Color::Black and lft.doubled_right())
return RedBlackTree(Color::Red,
RedBlackTree(Color::Black,
lft.left(),
lft.root(),
lft.right().left()),
lft.right().root(),
RedBlackTree(Color::Black,
lft.right().right(),
x,
rgt));
else if (c == Color::Black and rgt.doubled_left())
return RedBlackTree(Color::Red,
RedBlackTree(Color::Black,
lft,
x,
rgt.left().left()),
rgt.left().root(),
RedBlackTree(Color::Black,
rgt.left().right(),
rgt.root(),
rgt.right()));
else if (c == Color::Black and rgt.doubled_right())
return RedBlackTree(Color::Red,
RedBlackTree(Color::Black,
lft,
x,
rgt.left()),
rgt.root(),
rgt.right().paint(Color::Black));
return RedBlackTree(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(Color c) const
{
assert(not is_empty());
return RedBlackTree(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 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)
{
}
};
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, .accumulated_offset = start_offset };
}
#ifdef EXPERIMENTAL_REMOVE
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(Offset at) const
{
auto t = rem(*this, at, Offset{ 0 });
if (t.is_empty())
return RedBlackTree();
return RedBlackTree(Color::Black, t.left(), t.root(), t.right());
}
RedBlackTree RedBlackTree::fuse(const RedBlackTree& left, const RedBlackTree& right)
{
// match: (left, right)
// case: (None, r)
if (left.is_empty())
return right;
if (right.is_empty())
return left;
// match: (left.color, right.color)
// case: (B, R)
if (left.root_color() == Color::Black and right.root_color() == Color::Red)
{
return RedBlackTree(Color::Red,
fuse(left, right.left()),
right.root(),
right.right());
}
// case: (R, B)
if (left.root_color() == Color::Red and right.root_color() == Color::Black)
{
return RedBlackTree(Color::Red,
left.left(),
left.root(),
fuse(left.right(), right));
}
// case: (R, R)
if (left.root_color() == Color::Red and right.root_color() == Color::Red)
{
auto fused = fuse(left.right(), right.left());
if (not fused.is_empty() and fused.root_color() == Color::Red)
{
auto new_left = RedBlackTree(Color::Red,
left.left(),
left.root(),
fused.left());
auto new_right = RedBlackTree(Color::Red,
fused.right(),
right.root(),
right.right());
return RedBlackTree(Color::Red,
new_left,
fused.root(),
new_right);
}
auto new_right = RedBlackTree(Color::Red,
fused,
right.root(),
right.right());
return RedBlackTree(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(left.right(), right.left());
if (not fused.is_empty() and fused.root_color() == Color::Red)
{
auto new_left = RedBlackTree(Color::Black,
left.left(),
left.root(),
fused.left());
auto new_right = RedBlackTree(Color::Black,
fused.right(),
right.root(),
right.right());
return RedBlackTree(Color::Red,
new_left,
fused.root(),
new_right);
}
auto new_right = RedBlackTree(Color::Black,
fused,
right.root(),
right.right());
auto new_node = RedBlackTree(Color::Red,
left.left(),
left.root(),
new_right);
return balance_left(new_node);
}
RedBlackTree RedBlackTree::balance(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(Color::Black);
auto r = node.right().paint(Color::Black);
return RedBlackTree(Color::Red,
l,
node.root(),
r);
}
assert(node.root_color() == Color::Black);
return balance(node.root_color(), node.left(), node.root(), node.right());
}
RedBlackTree RedBlackTree::balance_left(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(Color::Red,
left.left().paint(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(Color::Black,
left.left(),
left.root(),
left.right().paint(Color::Red));
return balance(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(Color::Black,
left.right().left().right(),
left.right().root(),
left.right().right().paint(Color::Red));
auto new_right = balance(unbalanced_new_right);
auto new_left = RedBlackTree(Color::Black,
left.left(),
left.root(),
left.right().left().left());
return RedBlackTree(Color::Red,
new_left,
left.right().left().root(),
new_right);
}
assert(!"impossible");
return left;
}
RedBlackTree RedBlackTree::balance_right(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(Color::Red,
right.left(),
right.root(),
right.right().paint(Color::Black));
}
// case: (Some(B), ..)
if (not right.left().is_empty() and right.left().root_color() == Color::Black)
{
auto new_right = RedBlackTree(Color::Black,
right.left().paint(Color::Red),
right.root(),
right.right());
return balance(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(Color::Black,
// Note: Because 'left' is red, it must have a left child.
right.left().left().paint(Color::Red),
right.left().root(),
right.left().right().left());
auto new_left = balance(unbalanced_new_left);
auto new_right = RedBlackTree(Color::Black,
right.left().right().right(),
right.root(),
right.right());
return RedBlackTree(Color::Red,
new_left,
right.left().right().root(),
new_right);
}
assert(!"impossible");
return right;
}
RedBlackTree RedBlackTree::remove_left(const RedBlackTree& root, Offset at, Offset total)
{
auto new_left = rem(root.left(), at, total);
auto new_node = RedBlackTree(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(new_node);
return new_node;
}
RedBlackTree RedBlackTree::remove_right(const RedBlackTree& root, Offset at, Offset total)
{
const NodeData& y = root.root();
auto new_right = rem(root.right(), at, total + y.left_subtree_length + y.piece.length);
auto new_node = RedBlackTree(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(new_node);
return new_node;
}
RedBlackTree RedBlackTree::rem(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(root, at, total);
if (at == total + y.left_subtree_length)
return fuse(root.left(), root.right());
return remove_right(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
{
void populate_line_starts(LineStarts* starts, std::string_view buf)
{
starts->clear();
LineStart start { };
starts->push_back(start);
const auto len = buf.size();
for (size_t i = 0; i < len; ++i)
{
char c = buf[i];
if (c == '\n')
{
start = LineStart{ i + 1 };
starts->push_back(start);
}
}
}
void compute_buffer_meta(BufferMeta* meta, const RedBlackTree& root)
{
meta->lf_count = tree_lf_count(root);
meta->total_content_length = tree_length(root);
}
} // namespace [anon]
const CharBuffer* BufferCollection::buffer_at(BufferIndex index) const
{
if (index == BufferIndex::ModBuf)
return &mod_buffer;
return orig_buffers[rep(index)].get();
}
CharOffset BufferCollection::buffer_offset(BufferIndex index, const BufferCursor& cursor) const
{
auto& starts = buffer_at(index)->line_starts;
return CharOffset{ rep(starts[rep(cursor.line)]) + rep(cursor.column) };
}
Tree::Tree():
buffers{ }
{
build_tree();
}
Tree::Tree(Buffers&& buffers):
buffers{ std::move(buffers) }
{
build_tree();
}
void Tree::build_tree()
{
buffers.mod_buffer.line_starts.clear();
buffers.mod_buffer.buffer.clear();
// In order to maintain the invariant of other buffers, the mod_buffer needs a single line-start of 0.
buffers.mod_buffer.line_starts.push_back({});
last_insert = { };
const auto buf_count = buffers.orig_buffers.size();
CharOffset offset = { };
for (size_t i = 0; i < buf_count; ++i)
{
const auto& buf = *buffers.orig_buffers[i];
assert(not buf.line_starts.empty());
// If this immutable buffer is empty, we can avoid creating a piece for it altogether.
if (buf.buffer.empty())
continue;
auto last_line = Line{ buf.line_starts.size() - 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[rep(last_line)]) } },
.length = Length{ buf.buffer.size() },
// Note: the number of newlines
.newline_count = LFCount{ rep(last_line) }
};
root = root.insert({ piece }, offset);
offset = offset + piece.length;
}
compute_buffer_meta();
}
void Tree::internal_insert(CharOffset offset, std::string_view txt)
{
assert(not txt.empty());
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({ piece }, CharOffset{ 0 });
return;
}
auto result = node_at(&buffers, root, 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, 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, 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({ 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({ 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(node_start_offset);
// Insert the left.
root = root.insert({ new_piece_left }, node_start_offset);
// Insert the new mid.
node_start_offset = node_start_offset + new_piece_left.length;
root = root.insert({ new_piece }, node_start_offset);
// Insert remainder.
node_start_offset = node_start_offset + new_piece.length;
root = root.insert({ 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, offset);
auto last = node_at(&buffers, root, 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)
{
root = root.remove(first.start_offset);
return;
}
// Shrink the node.
auto new_piece = trim_piece_left(&buffers, first_node->piece, end_split_pos);
// Remove the old one and update.
root = root.remove(first.start_offset)
.insert({ new_piece }, first.start_offset);
return;
}
// Trim the tail of this piece.
if (first.start_offset + first_node->piece.length == offset + count)
{
auto new_piece = trim_piece_right(&buffers, first_node->piece, start_split_pos);
// Remove the old one and update.
root = root.remove(first.start_offset)
.insert({ new_piece }, first.start_offset);
return;
}
// The removed buffer is somewhere in the middle. Trim it in both directions.
auto [left, right] = shrink_piece(&buffers, first_node->piece, start_split_pos, end_split_pos);
root = root.remove(first.start_offset)
// Note: We insert right first so that the 'left' will be inserted
// to the right node's left.
.insert({ right }, first.start_offset)
.insert({ left }, first.start_offset);
return;
}
// Traverse nodes and delete all nodes within the offset range. First we will build the
// partial pieces for the nodes that will eventually make up this range.
// There are four cases here:
// 1. The entire first node is deleted as well as all of the last node.
// 2. Part of the first node is deleted and all of the last node.
// 3. Part of the first node is deleted and part of the last node.
// 4. The entire first node is deleted and part of the last node.
auto new_first = trim_piece_right(&buffers, first_node->piece, start_split_pos);
if (last_node == nullptr)
{
remove_node_range(first, count);
}
else
{
auto end_split_pos = buffer_position(&buffers, last_node->piece, last.remainder);
auto new_last = trim_piece_left(&buffers, last_node->piece, end_split_pos);
remove_node_range(first, count);
// There's an edge case here where we delete all the nodes up to 'last' but
// last itself remains untouched. The test of 'remainder' in 'last' can identify
// this scenario to avoid inserting a duplicate of 'last'.
if (last.remainder != Length{})
{
if (new_last.length != Length{})
{
root = root.insert({ new_last }, first.start_offset);
}
}
}
if (new_first.length != Length{})
{
root = root.insert({ new_first }, first.start_offset);
}
}
// Fetches the length of the piece starting from the first line to 'index' or to the end of
// the piece.
Length Tree::accumulate_value(const BufferCollection* buffers, const Piece& piece, Line index)
{
auto* buffer = buffers->buffer_at(piece.index);
auto& line_starts = buffer->line_starts;
// Extend it so we can capture the entire line content including newline.
auto expected_start = extend(piece.first.line, rep(index) + 1);
auto first = rep(line_starts[rep(piece.first.line)]) + rep(piece.first.column);
if (expected_start > piece.last.line)
{
auto last = rep(line_starts[rep(piece.last.line)]) + rep(piece.last.column);
return Length{ last - first };
}
auto last = rep(line_starts[rep(expected_start)]);
return Length{ last - first };
}
// Fetches the length of the piece starting from the first line to 'index' or to the end of
// the piece.
Length Tree::accumulate_value_no_lf(const BufferCollection* buffers, const Piece& piece, Line index)
{
auto* buffer = buffers->buffer_at(piece.index);
auto& line_starts = buffer->line_starts;
// Extend it so we can capture the entire line content including newline.
auto expected_start = extend(piece.first.line, rep(index) + 1);
auto first = rep(line_starts[rep(piece.first.line)]) + rep(piece.first.column);
if (expected_start > piece.last.line)
{
auto last = rep(line_starts[rep(piece.last.line)]) + rep(piece.last.column);
if (last == first)
return Length{ };
if (buffer->buffer[last - 1] == '\n')
return Length{ last - 1 - first };
return Length{ last - first };
}
auto last = rep(line_starts[rep(expected_start)]);
if (last == first)
return Length{ };
if (buffer->buffer[last - 1] == '\n')
return Length{ last - 1 - first };
return Length{ last - first };
}
void Tree::populate_from_node(std::string* buf, const BufferCollection* buffers, const PieceTree::RedBlackTree& node)
{
auto& buffer = buffers->buffer_at(node.root().piece.index)->buffer;
auto old_buf_size = buf->size();
// We know we want the first line (index 0).
auto accumulated_value = accumulate_value(buffers, node.root().piece, node.root().piece.first.line);
auto start_offset = buffers->buffer_offset(node.root().piece.index, node.root().piece.first);
auto first = buffer.data() + rep(start_offset);
auto last = first + rep(accumulated_value);
buf->resize(buf->size() + std::distance(first, last));
std::copy(first, last, buf->data() + old_buf_size);
}
void Tree::populate_from_node(std::string* buf, const BufferCollection* buffers, const PieceTree::RedBlackTree& node, Line line_index)
{
auto accumulated_value = accumulate_value(buffers, node.root().piece, line_index);
Length prev_accumulated_value = { };
if (line_index != Line::IndexBeginning)
{
prev_accumulated_value = accumulate_value(buffers, node.root().piece, retract(line_index));
}
auto& buffer = buffers->buffer_at(node.root().piece.index)->buffer;
auto start_offset = buffers->buffer_offset(node.root().piece.index, node.root().piece.first);
auto first = buffer.data() + rep(start_offset) + rep(prev_accumulated_value);
auto last = buffer.data() + rep(start_offset) + rep(accumulated_value);
auto old_buf_size = buf->size();
buf->resize(buf->size() + std::distance(first, last));
std::copy(first, last, buf->data() + old_buf_size);
}
template <Tree::Accumulator accumulate>
void Tree::line_start(CharOffset* offset, const BufferCollection* buffers, const PieceTree::RedBlackTree& node, Line line)
{
if (node.is_empty())
return;
assert(line != Line::IndexBeginning);
auto line_index = rep(retract(line));
if (rep(node.root().left_subtree_lf_count) >= line_index)
{
line_start<accumulate>(offset, buffers, node.left(), line);
}
// The desired line is directly within the node.
else if (rep(node.root().left_subtree_lf_count + node.root().piece.newline_count) >= line_index)
{
line_index -= rep(node.root().left_subtree_lf_count);
Length len = node.root().left_subtree_length;
if (line_index != 0)
{
len = len + (*accumulate)(buffers, node.root().piece, Line{ line_index - 1 });
}
*offset = *offset + len;
}
// assemble the LHS and RHS.
else
{
// This case implies that 'left_subtree_lf_count' is strictly < line_index.
// The content is somewhere in the middle.
line_index -= rep(node.root().left_subtree_lf_count + node.root().piece.newline_count);
*offset = *offset + node.root().left_subtree_length + node.root().piece.length;
line_start<accumulate>(offset, buffers, node.right(), Line{ line_index + 1 });
}
}
void Tree::line_end_crlf(CharOffset* offset, const BufferCollection* buffers, const RedBlackTree& root, const RedBlackTree& node, Line line)
{
if (node.is_empty())
return;
assert(line != Line::IndexBeginning);
auto line_index = rep(retract(line));
if (rep(node.root().left_subtree_lf_count) >= line_index)
{
line_end_crlf(offset, buffers, root, node.left(), line);
}
// The desired line is directly within the node.
else if (rep(node.root().left_subtree_lf_count + node.root().piece.newline_count) >= line_index)
{
line_index -= rep(node.root().left_subtree_lf_count);
Length len = node.root().left_subtree_length;
if (line_index != 0)