1 //===- RewriteRope.cpp - Rope specialized for rewriter --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the RewriteRope class, which is a powerful string.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Core/RewriteRope.h"
15 #include "clang/Basic/LLVM.h"
16 #include "llvm/Support/Casting.h"
21 using namespace clang;
23 /// RewriteRope is a "strong" string class, designed to make insertions and
24 /// deletions in the middle of the string nearly constant time (really, they are
25 /// O(log N), but with a very low constant factor).
27 /// The implementation of this datastructure is a conceptual linear sequence of
28 /// RopePiece elements. Each RopePiece represents a view on a separately
29 /// allocated and reference counted string. This means that splitting a very
30 /// long string can be done in constant time by splitting a RopePiece that
31 /// references the whole string into two rope pieces that reference each half.
32 /// Once split, another string can be inserted in between the two halves by
33 /// inserting a RopePiece in between the two others. All of this is very
34 /// inexpensive: it takes time proportional to the number of RopePieces, not the
35 /// length of the strings they represent.
37 /// While a linear sequences of RopePieces is the conceptual model, the actual
38 /// implementation captures them in an adapted B+ Tree. Using a B+ tree (which
39 /// is a tree that keeps the values in the leaves and has where each node
40 /// contains a reasonable number of pointers to children/values) allows us to
41 /// maintain efficient operation when the RewriteRope contains a *huge* number
42 /// of RopePieces. The basic idea of the B+ Tree is that it allows us to find
43 /// the RopePiece corresponding to some offset very efficiently, and it
44 /// automatically balances itself on insertions of RopePieces (which can happen
45 /// for both insertions and erases of string ranges).
47 /// The one wrinkle on the theory is that we don't attempt to keep the tree
48 /// properly balanced when erases happen. Erases of string data can both insert
49 /// new RopePieces (e.g. when the middle of some other rope piece is deleted,
50 /// which results in two rope pieces, which is just like an insert) or it can
51 /// reduce the number of RopePieces maintained by the B+Tree. In the case when
52 /// the number of RopePieces is reduced, we don't attempt to maintain the
53 /// standard 'invariant' that each node in the tree contains at least
54 /// 'WidthFactor' children/values. For our use cases, this doesn't seem to
57 /// The implementation below is primarily implemented in terms of three classes:
58 /// RopePieceBTreeNode - Common base class for:
60 /// RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
61 /// nodes. This directly represents a chunk of the string with those
62 /// RopePieces contatenated.
63 /// RopePieceBTreeInterior - An interior node in the B+ Tree, which manages
64 /// up to '2*WidthFactor' other nodes in the tree.
68 //===----------------------------------------------------------------------===//
69 // RopePieceBTreeNode Class
70 //===----------------------------------------------------------------------===//
72 /// RopePieceBTreeNode - Common base class of RopePieceBTreeLeaf and
73 /// RopePieceBTreeInterior. This provides some 'virtual' dispatching methods
74 /// and a flag that determines which subclass the instance is. Also
75 /// important, this node knows the full extend of the node, including any
76 /// children that it has. This allows efficient skipping over entire subtrees
77 /// when looking for an offset in the BTree.
78 class RopePieceBTreeNode {
80 /// WidthFactor - This controls the number of K/V slots held in the BTree:
81 /// how wide it is. Each level of the BTree is guaranteed to have at least
82 /// 'WidthFactor' elements in it (either ropepieces or children), (except
83 /// the root, which may have less) and may have at most 2*WidthFactor
85 enum { WidthFactor = 8 };
87 /// Size - This is the number of bytes of file this node (including any
88 /// potential children) covers.
91 /// IsLeaf - True if this is an instance of RopePieceBTreeLeaf, false if it
92 /// is an instance of RopePieceBTreeInterior.
95 RopePieceBTreeNode(bool isLeaf) : IsLeaf(isLeaf) {}
96 ~RopePieceBTreeNode() = default;
99 bool isLeaf() const { return IsLeaf; }
100 unsigned size() const { return Size; }
104 /// split - Split the range containing the specified offset so that we are
105 /// guaranteed that there is a place to do an insertion at the specified
106 /// offset. The offset is relative, so "0" is the start of the node.
108 /// If there is no space in this subtree for the extra piece, the extra tree
109 /// node is returned and must be inserted into a parent.
110 RopePieceBTreeNode *split(unsigned Offset);
112 /// insert - Insert the specified ropepiece into this tree node at the
113 /// specified offset. The offset is relative, so "0" is the start of the
116 /// If there is no space in this subtree for the extra piece, the extra tree
117 /// node is returned and must be inserted into a parent.
118 RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
120 /// erase - Remove NumBytes from this node at the specified offset. We are
121 /// guaranteed that there is a split at Offset.
122 void erase(unsigned Offset, unsigned NumBytes);
125 //===----------------------------------------------------------------------===//
126 // RopePieceBTreeLeaf Class
127 //===----------------------------------------------------------------------===//
129 /// RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
130 /// nodes. This directly represents a chunk of the string with those
131 /// RopePieces contatenated. Since this is a B+Tree, all values (in this case
132 /// instances of RopePiece) are stored in leaves like this. To make iteration
133 /// over the leaves efficient, they maintain a singly linked list through the
134 /// NextLeaf field. This allows the B+Tree forward iterator to be constant
135 /// time for all increments.
136 class RopePieceBTreeLeaf : public RopePieceBTreeNode {
137 /// NumPieces - This holds the number of rope pieces currently active in the
139 unsigned char NumPieces = 0;
141 /// Pieces - This tracks the file chunks currently in this leaf.
142 RopePiece Pieces[2*WidthFactor];
144 /// NextLeaf - This is a pointer to the next leaf in the tree, allowing
145 /// efficient in-order forward iteration of the tree without traversal.
146 RopePieceBTreeLeaf **PrevLeaf = nullptr;
147 RopePieceBTreeLeaf *NextLeaf = nullptr;
150 RopePieceBTreeLeaf() : RopePieceBTreeNode(true) {}
152 ~RopePieceBTreeLeaf() {
153 if (PrevLeaf || NextLeaf)
154 removeFromLeafInOrder();
158 bool isFull() const { return NumPieces == 2*WidthFactor; }
160 /// clear - Remove all rope pieces from this leaf.
163 Pieces[--NumPieces] = RopePiece();
167 unsigned getNumPieces() const { return NumPieces; }
169 const RopePiece &getPiece(unsigned i) const {
170 assert(i < getNumPieces() && "Invalid piece ID");
174 const RopePieceBTreeLeaf *getNextLeafInOrder() const { return NextLeaf; }
176 void insertAfterLeafInOrder(RopePieceBTreeLeaf *Node) {
177 assert(!PrevLeaf && !NextLeaf && "Already in ordering");
179 NextLeaf = Node->NextLeaf;
181 NextLeaf->PrevLeaf = &NextLeaf;
182 PrevLeaf = &Node->NextLeaf;
183 Node->NextLeaf = this;
186 void removeFromLeafInOrder() {
188 *PrevLeaf = NextLeaf;
190 NextLeaf->PrevLeaf = PrevLeaf;
191 } else if (NextLeaf) {
192 NextLeaf->PrevLeaf = nullptr;
196 /// FullRecomputeSizeLocally - This method recomputes the 'Size' field by
197 /// summing the size of all RopePieces.
198 void FullRecomputeSizeLocally() {
200 for (unsigned i = 0, e = getNumPieces(); i != e; ++i)
201 Size += getPiece(i).size();
204 /// split - Split the range containing the specified offset so that we are
205 /// guaranteed that there is a place to do an insertion at the specified
206 /// offset. The offset is relative, so "0" is the start of the node.
208 /// If there is no space in this subtree for the extra piece, the extra tree
209 /// node is returned and must be inserted into a parent.
210 RopePieceBTreeNode *split(unsigned Offset);
212 /// insert - Insert the specified ropepiece into this tree node at the
213 /// specified offset. The offset is relative, so "0" is the start of the
216 /// If there is no space in this subtree for the extra piece, the extra tree
217 /// node is returned and must be inserted into a parent.
218 RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
220 /// erase - Remove NumBytes from this node at the specified offset. We are
221 /// guaranteed that there is a split at Offset.
222 void erase(unsigned Offset, unsigned NumBytes);
224 static bool classof(const RopePieceBTreeNode *N) {
231 /// split - Split the range containing the specified offset so that we are
232 /// guaranteed that there is a place to do an insertion at the specified
233 /// offset. The offset is relative, so "0" is the start of the node.
235 /// If there is no space in this subtree for the extra piece, the extra tree
236 /// node is returned and must be inserted into a parent.
237 RopePieceBTreeNode *RopePieceBTreeLeaf::split(unsigned Offset) {
238 // Find the insertion point. We are guaranteed that there is a split at the
239 // specified offset so find it.
240 if (Offset == 0 || Offset == size()) {
241 // Fastpath for a common case. There is already a splitpoint at the end.
245 // Find the piece that this offset lands in.
246 unsigned PieceOffs = 0;
248 while (Offset >= PieceOffs+Pieces[i].size()) {
249 PieceOffs += Pieces[i].size();
253 // If there is already a split point at the specified offset, just return
255 if (PieceOffs == Offset)
258 // Otherwise, we need to split piece 'i' at Offset-PieceOffs. Convert Offset
259 // to being Piece relative.
260 unsigned IntraPieceOffset = Offset-PieceOffs;
262 // We do this by shrinking the RopePiece and then doing an insert of the tail.
263 RopePiece Tail(Pieces[i].StrData, Pieces[i].StartOffs+IntraPieceOffset,
265 Size -= Pieces[i].size();
266 Pieces[i].EndOffs = Pieces[i].StartOffs+IntraPieceOffset;
267 Size += Pieces[i].size();
269 return insert(Offset, Tail);
272 /// insert - Insert the specified RopePiece into this tree node at the
273 /// specified offset. The offset is relative, so "0" is the start of the node.
275 /// If there is no space in this subtree for the extra piece, the extra tree
276 /// node is returned and must be inserted into a parent.
277 RopePieceBTreeNode *RopePieceBTreeLeaf::insert(unsigned Offset,
278 const RopePiece &R) {
279 // If this node is not full, insert the piece.
281 // Find the insertion point. We are guaranteed that there is a split at the
282 // specified offset so find it.
283 unsigned i = 0, e = getNumPieces();
284 if (Offset == size()) {
285 // Fastpath for a common case.
288 unsigned SlotOffs = 0;
289 for (; Offset > SlotOffs; ++i)
290 SlotOffs += getPiece(i).size();
291 assert(SlotOffs == Offset && "Split didn't occur before insertion!");
294 // For an insertion into a non-full leaf node, just insert the value in
295 // its sorted position. This requires moving later values over.
297 Pieces[e] = Pieces[e-1];
304 // Otherwise, if this is leaf is full, split it in two halves. Since this
305 // node is full, it contains 2*WidthFactor values. We move the first
306 // 'WidthFactor' values to the LHS child (which we leave in this node) and
307 // move the last 'WidthFactor' values into the RHS child.
309 // Create the new node.
310 RopePieceBTreeLeaf *NewNode = new RopePieceBTreeLeaf();
312 // Move over the last 'WidthFactor' values from here to NewNode.
313 std::copy(&Pieces[WidthFactor], &Pieces[2*WidthFactor],
314 &NewNode->Pieces[0]);
315 // Replace old pieces with null RopePieces to drop refcounts.
316 std::fill(&Pieces[WidthFactor], &Pieces[2*WidthFactor], RopePiece());
318 // Decrease the number of values in the two nodes.
319 NewNode->NumPieces = NumPieces = WidthFactor;
321 // Recompute the two nodes' size.
322 NewNode->FullRecomputeSizeLocally();
323 FullRecomputeSizeLocally();
325 // Update the list of leaves.
326 NewNode->insertAfterLeafInOrder(this);
328 // These insertions can't fail.
329 if (this->size() >= Offset)
330 this->insert(Offset, R);
332 NewNode->insert(Offset - this->size(), R);
336 /// erase - Remove NumBytes from this node at the specified offset. We are
337 /// guaranteed that there is a split at Offset.
338 void RopePieceBTreeLeaf::erase(unsigned Offset, unsigned NumBytes) {
339 // Since we are guaranteed that there is a split at Offset, we start by
340 // finding the Piece that starts there.
341 unsigned PieceOffs = 0;
343 for (; Offset > PieceOffs; ++i)
344 PieceOffs += getPiece(i).size();
345 assert(PieceOffs == Offset && "Split didn't occur before erase!");
347 unsigned StartPiece = i;
349 // Figure out how many pieces completely cover 'NumBytes'. We want to remove
351 for (; Offset+NumBytes > PieceOffs+getPiece(i).size(); ++i)
352 PieceOffs += getPiece(i).size();
354 // If we exactly include the last one, include it in the region to delete.
355 if (Offset+NumBytes == PieceOffs+getPiece(i).size()) {
356 PieceOffs += getPiece(i).size();
360 // If we completely cover some RopePieces, erase them now.
361 if (i != StartPiece) {
362 unsigned NumDeleted = i-StartPiece;
363 for (; i != getNumPieces(); ++i)
364 Pieces[i-NumDeleted] = Pieces[i];
366 // Drop references to dead rope pieces.
367 std::fill(&Pieces[getNumPieces()-NumDeleted], &Pieces[getNumPieces()],
369 NumPieces -= NumDeleted;
371 unsigned CoverBytes = PieceOffs-Offset;
372 NumBytes -= CoverBytes;
376 // If we completely removed some stuff, we could be done.
377 if (NumBytes == 0) return;
379 // Okay, now might be erasing part of some Piece. If this is the case, then
380 // move the start point of the piece.
381 assert(getPiece(StartPiece).size() > NumBytes);
382 Pieces[StartPiece].StartOffs += NumBytes;
384 // The size of this node just shrunk by NumBytes.
388 //===----------------------------------------------------------------------===//
389 // RopePieceBTreeInterior Class
390 //===----------------------------------------------------------------------===//
394 /// RopePieceBTreeInterior - This represents an interior node in the B+Tree,
395 /// which holds up to 2*WidthFactor pointers to child nodes.
396 class RopePieceBTreeInterior : public RopePieceBTreeNode {
397 /// NumChildren - This holds the number of children currently active in the
399 unsigned char NumChildren = 0;
401 RopePieceBTreeNode *Children[2*WidthFactor];
404 RopePieceBTreeInterior() : RopePieceBTreeNode(false) {}
406 RopePieceBTreeInterior(RopePieceBTreeNode *LHS, RopePieceBTreeNode *RHS)
407 : RopePieceBTreeNode(false) {
411 Size = LHS->size() + RHS->size();
414 ~RopePieceBTreeInterior() {
415 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
416 Children[i]->Destroy();
419 bool isFull() const { return NumChildren == 2*WidthFactor; }
421 unsigned getNumChildren() const { return NumChildren; }
423 const RopePieceBTreeNode *getChild(unsigned i) const {
424 assert(i < NumChildren && "invalid child #");
428 RopePieceBTreeNode *getChild(unsigned i) {
429 assert(i < NumChildren && "invalid child #");
433 /// FullRecomputeSizeLocally - Recompute the Size field of this node by
434 /// summing up the sizes of the child nodes.
435 void FullRecomputeSizeLocally() {
437 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
438 Size += getChild(i)->size();
441 /// split - Split the range containing the specified offset so that we are
442 /// guaranteed that there is a place to do an insertion at the specified
443 /// offset. The offset is relative, so "0" is the start of the node.
445 /// If there is no space in this subtree for the extra piece, the extra tree
446 /// node is returned and must be inserted into a parent.
447 RopePieceBTreeNode *split(unsigned Offset);
449 /// insert - Insert the specified ropepiece into this tree node at the
450 /// specified offset. The offset is relative, so "0" is the start of the
453 /// If there is no space in this subtree for the extra piece, the extra tree
454 /// node is returned and must be inserted into a parent.
455 RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
457 /// HandleChildPiece - A child propagated an insertion result up to us.
458 /// Insert the new child, and/or propagate the result further up the tree.
459 RopePieceBTreeNode *HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS);
461 /// erase - Remove NumBytes from this node at the specified offset. We are
462 /// guaranteed that there is a split at Offset.
463 void erase(unsigned Offset, unsigned NumBytes);
465 static bool classof(const RopePieceBTreeNode *N) {
472 /// split - Split the range containing the specified offset so that we are
473 /// guaranteed that there is a place to do an insertion at the specified
474 /// offset. The offset is relative, so "0" is the start of the node.
476 /// If there is no space in this subtree for the extra piece, the extra tree
477 /// node is returned and must be inserted into a parent.
478 RopePieceBTreeNode *RopePieceBTreeInterior::split(unsigned Offset) {
479 // Figure out which child to split.
480 if (Offset == 0 || Offset == size())
481 return nullptr; // If we have an exact offset, we're already split.
483 unsigned ChildOffset = 0;
485 for (; Offset >= ChildOffset+getChild(i)->size(); ++i)
486 ChildOffset += getChild(i)->size();
488 // If already split there, we're done.
489 if (ChildOffset == Offset)
492 // Otherwise, recursively split the child.
493 if (RopePieceBTreeNode *RHS = getChild(i)->split(Offset-ChildOffset))
494 return HandleChildPiece(i, RHS);
495 return nullptr; // Done!
498 /// insert - Insert the specified ropepiece into this tree node at the
499 /// specified offset. The offset is relative, so "0" is the start of the
502 /// If there is no space in this subtree for the extra piece, the extra tree
503 /// node is returned and must be inserted into a parent.
504 RopePieceBTreeNode *RopePieceBTreeInterior::insert(unsigned Offset,
505 const RopePiece &R) {
506 // Find the insertion point. We are guaranteed that there is a split at the
507 // specified offset so find it.
508 unsigned i = 0, e = getNumChildren();
510 unsigned ChildOffs = 0;
511 if (Offset == size()) {
512 // Fastpath for a common case. Insert at end of last child.
514 ChildOffs = size()-getChild(i)->size();
516 for (; Offset > ChildOffs+getChild(i)->size(); ++i)
517 ChildOffs += getChild(i)->size();
522 // Insert at the end of this child.
523 if (RopePieceBTreeNode *RHS = getChild(i)->insert(Offset-ChildOffs, R))
524 return HandleChildPiece(i, RHS);
529 /// HandleChildPiece - A child propagated an insertion result up to us.
530 /// Insert the new child, and/or propagate the result further up the tree.
532 RopePieceBTreeInterior::HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS) {
533 // Otherwise the child propagated a subtree up to us as a new child. See if
534 // we have space for it here.
536 // Insert RHS after child 'i'.
537 if (i + 1 != getNumChildren())
538 memmove(&Children[i+2], &Children[i+1],
539 (getNumChildren()-i-1)*sizeof(Children[0]));
545 // Okay, this node is full. Split it in half, moving WidthFactor children to
546 // a newly allocated interior node.
548 // Create the new node.
549 RopePieceBTreeInterior *NewNode = new RopePieceBTreeInterior();
551 // Move over the last 'WidthFactor' values from here to NewNode.
552 memcpy(&NewNode->Children[0], &Children[WidthFactor],
553 WidthFactor*sizeof(Children[0]));
555 // Decrease the number of values in the two nodes.
556 NewNode->NumChildren = NumChildren = WidthFactor;
558 // Finally, insert the two new children in the side the can (now) hold them.
559 // These insertions can't fail.
561 this->HandleChildPiece(i, RHS);
563 NewNode->HandleChildPiece(i-WidthFactor, RHS);
565 // Recompute the two nodes' size.
566 NewNode->FullRecomputeSizeLocally();
567 FullRecomputeSizeLocally();
571 /// erase - Remove NumBytes from this node at the specified offset. We are
572 /// guaranteed that there is a split at Offset.
573 void RopePieceBTreeInterior::erase(unsigned Offset, unsigned NumBytes) {
574 // This will shrink this node by NumBytes.
577 // Find the first child that overlaps with Offset.
579 for (; Offset >= getChild(i)->size(); ++i)
580 Offset -= getChild(i)->size();
582 // Propagate the delete request into overlapping children, or completely
583 // delete the children as appropriate.
585 RopePieceBTreeNode *CurChild = getChild(i);
587 // If we are deleting something contained entirely in the child, pass on the
589 if (Offset+NumBytes < CurChild->size()) {
590 CurChild->erase(Offset, NumBytes);
594 // If this deletion request starts somewhere in the middle of the child, it
595 // must be deleting to the end of the child.
597 unsigned BytesFromChild = CurChild->size()-Offset;
598 CurChild->erase(Offset, BytesFromChild);
599 NumBytes -= BytesFromChild;
600 // Start at the beginning of the next child.
606 // If the deletion request completely covers the child, delete it and move
608 NumBytes -= CurChild->size();
611 if (i != getNumChildren())
612 memmove(&Children[i], &Children[i+1],
613 (getNumChildren()-i)*sizeof(Children[0]));
617 //===----------------------------------------------------------------------===//
618 // RopePieceBTreeNode Implementation
619 //===----------------------------------------------------------------------===//
621 void RopePieceBTreeNode::Destroy() {
622 if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
625 delete cast<RopePieceBTreeInterior>(this);
628 /// split - Split the range containing the specified offset so that we are
629 /// guaranteed that there is a place to do an insertion at the specified
630 /// offset. The offset is relative, so "0" is the start of the node.
632 /// If there is no space in this subtree for the extra piece, the extra tree
633 /// node is returned and must be inserted into a parent.
634 RopePieceBTreeNode *RopePieceBTreeNode::split(unsigned Offset) {
635 assert(Offset <= size() && "Invalid offset to split!");
636 if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
637 return Leaf->split(Offset);
638 return cast<RopePieceBTreeInterior>(this)->split(Offset);
641 /// insert - Insert the specified ropepiece into this tree node at the
642 /// specified offset. The offset is relative, so "0" is the start of the
645 /// If there is no space in this subtree for the extra piece, the extra tree
646 /// node is returned and must be inserted into a parent.
647 RopePieceBTreeNode *RopePieceBTreeNode::insert(unsigned Offset,
648 const RopePiece &R) {
649 assert(Offset <= size() && "Invalid offset to insert!");
650 if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
651 return Leaf->insert(Offset, R);
652 return cast<RopePieceBTreeInterior>(this)->insert(Offset, R);
655 /// erase - Remove NumBytes from this node at the specified offset. We are
656 /// guaranteed that there is a split at Offset.
657 void RopePieceBTreeNode::erase(unsigned Offset, unsigned NumBytes) {
658 assert(Offset+NumBytes <= size() && "Invalid offset to erase!");
659 if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
660 return Leaf->erase(Offset, NumBytes);
661 return cast<RopePieceBTreeInterior>(this)->erase(Offset, NumBytes);
664 //===----------------------------------------------------------------------===//
665 // RopePieceBTreeIterator Implementation
666 //===----------------------------------------------------------------------===//
668 static const RopePieceBTreeLeaf *getCN(const void *P) {
669 return static_cast<const RopePieceBTreeLeaf*>(P);
673 RopePieceBTreeIterator::RopePieceBTreeIterator(const void *n) {
674 const auto *N = static_cast<const RopePieceBTreeNode *>(n);
676 // Walk down the left side of the tree until we get to a leaf.
677 while (const auto *IN = dyn_cast<RopePieceBTreeInterior>(N))
680 // We must have at least one leaf.
681 CurNode = cast<RopePieceBTreeLeaf>(N);
683 // If we found a leaf that happens to be empty, skip over it until we get
684 // to something full.
685 while (CurNode && getCN(CurNode)->getNumPieces() == 0)
686 CurNode = getCN(CurNode)->getNextLeafInOrder();
689 CurPiece = &getCN(CurNode)->getPiece(0);
690 else // Empty tree, this is an end() iterator.
695 void RopePieceBTreeIterator::MoveToNextPiece() {
696 if (CurPiece != &getCN(CurNode)->getPiece(getCN(CurNode)->getNumPieces()-1)) {
702 // Find the next non-empty leaf node.
704 CurNode = getCN(CurNode)->getNextLeafInOrder();
705 while (CurNode && getCN(CurNode)->getNumPieces() == 0);
708 CurPiece = &getCN(CurNode)->getPiece(0);
714 //===----------------------------------------------------------------------===//
715 // RopePieceBTree Implementation
716 //===----------------------------------------------------------------------===//
718 static RopePieceBTreeNode *getRoot(void *P) {
719 return static_cast<RopePieceBTreeNode*>(P);
722 RopePieceBTree::RopePieceBTree() {
723 Root = new RopePieceBTreeLeaf();
726 RopePieceBTree::RopePieceBTree(const RopePieceBTree &RHS) {
727 assert(RHS.empty() && "Can't copy non-empty tree yet");
728 Root = new RopePieceBTreeLeaf();
731 RopePieceBTree::~RopePieceBTree() {
732 getRoot(Root)->Destroy();
735 unsigned RopePieceBTree::size() const {
736 return getRoot(Root)->size();
739 void RopePieceBTree::clear() {
740 if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(getRoot(Root)))
743 getRoot(Root)->Destroy();
744 Root = new RopePieceBTreeLeaf();
748 void RopePieceBTree::insert(unsigned Offset, const RopePiece &R) {
749 // #1. Split at Offset.
750 if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
751 Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
753 // #2. Do the insertion.
754 if (RopePieceBTreeNode *RHS = getRoot(Root)->insert(Offset, R))
755 Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
758 void RopePieceBTree::erase(unsigned Offset, unsigned NumBytes) {
759 // #1. Split at Offset.
760 if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
761 Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
763 // #2. Do the erasing.
764 getRoot(Root)->erase(Offset, NumBytes);
767 //===----------------------------------------------------------------------===//
768 // RewriteRope Implementation
769 //===----------------------------------------------------------------------===//
771 /// MakeRopeString - This copies the specified byte range into some instance of
772 /// RopeRefCountString, and return a RopePiece that represents it. This uses
773 /// the AllocBuffer object to aggregate requests for small strings into one
774 /// allocation instead of doing tons of tiny allocations.
775 RopePiece RewriteRope::MakeRopeString(const char *Start, const char *End) {
776 unsigned Len = End-Start;
777 assert(Len && "Zero length RopePiece is invalid!");
779 // If we have space for this string in the current alloc buffer, use it.
780 if (AllocOffs+Len <= AllocChunkSize) {
781 memcpy(AllocBuffer->Data+AllocOffs, Start, Len);
783 return RopePiece(AllocBuffer, AllocOffs-Len, AllocOffs);
786 // If we don't have enough room because this specific allocation is huge,
787 // just allocate a new rope piece for it alone.
788 if (Len > AllocChunkSize) {
789 unsigned Size = End-Start+sizeof(RopeRefCountString)-1;
790 auto *Res = reinterpret_cast<RopeRefCountString *>(new char[Size]);
792 memcpy(Res->Data, Start, End-Start);
793 return RopePiece(Res, 0, End-Start);
796 // Otherwise, this was a small request but we just don't have space for it
797 // Make a new chunk and share it with later allocations.
799 unsigned AllocSize = offsetof(RopeRefCountString, Data) + AllocChunkSize;
800 auto *Res = reinterpret_cast<RopeRefCountString *>(new char[AllocSize]);
802 memcpy(Res->Data, Start, Len);
806 return RopePiece(AllocBuffer, 0, Len);