Coalesce sequential typing into the tail piece, guard CRLF/UTF-16 split boundaries, and save via atomic .tmp streaming.
TL;DR30-second simplified summary▾
Storing a 100 MB log or source file in a naive flat string or gap buffer breaks down under modern IDE workloads: inserting 1 character near offset 50 in a flat array forces an O(N) memmove of 100 million bytes (~80 ms UI freeze on every keystroke), while a gap buffer stalls whenever multi-cursor edits jump across distant lines.
A Piece Table (evolved by VS Code into a Red-Black Piece Tree) keeps the 100 MB original file completely immutable (e.g. memory-mapped or chunked 64 KB blocks) and appends all new keystrokes into a small, append-only Add Buffer. The document itself is represented as a Red-Black balanced binary tree of lightweight Piece Descriptors [buffer_id, start_offset, length, line_feeds]. Editing at any offset simply splits 1-2 piece nodes in O(log P) (<0.1 ms), and O(log P) line-number lookups use cached left-subtree size and lf_count metadata.
Because both the Original Buffer and Add Buffer are append-only/immutable, Undo/Redo stacks store tiny inverse piece commands without copying megabytes of text, and multi-cursor edits compose cleanly within a 16 ms 60fps frame budget.
Why Flat Arrays & Gap Buffers Stall on 100 MB Multi-Cursor Edits.
Why this matters: Contrast O(N) flat-array shifting and single-gap stalls against immutable Piece Table descriptors.
In a 100 MB file, a flat byte[] or UTF-16 string must shift up to 100M bytes on a single insert at line 1—taking ~80 ms and dropping frames past the 16 ms 60fps budget.
Gap buffers move a single cursor gap efficiently for sequential typing, but multi-cursor editing (1,000 cursors across a file) or random Find-and-Replace forces O(N) gap relocations on every cursor jump.
Why Flat Arrays & Gap Buffers Stall on 100 MB Multi-Cursor Edits
1.Zero-Copy File Open: Opening a 100 MB file creates 1 root Piece pointing at the original buffer—no eager splitting.
2.Multi-Cursor Friendly: Piece trees handle edits at 1,000 arbitrary offsets without relocating a single contiguous gap.
3.UTF-16 / UTF-8 Agnostic: Pieces work identically over UTF-8 byte buffers or UTF-16 code-unit chunks.
Immutable Original + Append-Only Add buffers indexed by Piece descriptors eliminate O(N) byte shifts on 100 MB files.
Balancing Pieces & Augmenting Subtrees with Byte & Line-Feed Counts.
Why this matters: Augment a Red-Black tree of Pieces with left-subtree byte and newline counts for O(log P) random access.
A plain array-backed Piece Table degrades to O(P) after 100,000 edits because inserting a split piece shifts the descriptor array.
VS Code's Piece Tree stores Pieces in a Red-Black balanced binary tree where each node caches left_len (total bytes/chars in its left subtree) and left_lf (total \n line breaks in its left subtree).
Balancing Pieces & Augmenting Subtrees with Byte & Line-Feed Counts
1.No Separate Line Array: Storing left_lf directly inside tree nodes avoids O(L) line-offset array shifts on newline edits.
2.Coalesced Sequential Typing: If the user types 'abc' sequentially at the end of the Add Buffer, extend the last piece's len in O(1)!
3.64 KB Chunking: Splitting 100 MB files into 64 KB chunks caps worst-case per-piece line-offset scanning.
Augmenting Red-Black Piece Tree nodes with left_len and left_lf makes both edits and line lookups O(log P).
Piece Table Insert, Delete & Coalesced Append Implementation.
Why this matters: Implement bounds-checked Piece Table insert/delete with adjacent-piece coalescing for sequential keystrokes.
Validate offsets [0, total_len] strictly and handle boundary splits cleanly when an edit lands inside an existing Piece.
class Piece:
__slots__ = ('buf', 'start', 'length')
def __init__(self, buf: int, start: int, length: int) -> None:
self.buf = buf # 0 = original, 1 = add
self.start = start
self.length = length
class PieceTable:
def __init__(self, original: str) -> None:
self.buffers = [original, []]
self.pieces = [Piece(0, 0, len(original))] if original else []
self.total_len = len(original)
def insert(self, offset: int, text: str) -> None:
if offset < 0 or offset > self.total_len:
raise IndexError('Insert offset out of bounds')
if not text:
return
add_start = len(self.buffers[1])
self.buffers[1].extend(text)
# Split piece at offset or coalesce if appending at Add Buffer tail
self.total_len += len(text)Piece Table Insert, Delete & Coalesced Append Implementation
1.Sequential Typing Fast Path: Extending an existing Add-Buffer piece in place keeps P tiny during normal prose/code typing.
2.Strict Bounds Checking: Raise IndexError before mutating buffers[1] so failed calls never leak orphan characters.
3.Empty-Piece Pruning: Drop zero-length pieces immediately after deletions to keep tree height minimal.
Bounds-checked offsets, Add-Buffer appending, and contiguous piece coalescing keep Piece Tables fast and compact.
O(1) Undo/Redo Stacks & Immutable Piece Snapshots.
Why this matters: Support instant Undo/Redo and background-thread snapshots without copying the 100 MB document.
Storing full-document strings on an Undo stack would consume 10 GB of RAM after 100 edits to a 100 MB file.
Because Original and Add buffers are append-only, an Undo entry only stores the replaced Piece range (offset, old_pieces, new_pieces)—a few dozen bytes!
O(1) Undo/Redo Stacks & Immutable Piece Snapshots
1.64-Byte Undo Entries: 10,000 undo steps consume <1 MB RAM even on a 100 MB file.
2.Edit Grouping: Coalesce rapid keystrokes within 300 ms into one logical Undo step.
3.Lock-Free Read Snapshots: Persistent path-copying lets language servers tokenize a frozen snapshot while the user keeps typing.
Append-only buffers shrink Undo entries to ~64 bytes and enable O(log P) immutable snapshots for background workers.
Preventing Piece Fragmentation & CRLF/UTF-16 Surrogate Splits.
Why this matters: Avoid splitting UTF-16 surrogate pairs or CRLF newlines across pieces and compact fragmented trees.
Splitting a piece right between \r and \n (CRLF) or between a UTF-16 high/low surrogate pair breaks line counts and corrupts emoji!
Always snap piece split boundaries away from \r|\n and UTF-16 surrogate boundaries, and normalize lf_count explicitly when \r is followed by \n across adjacent pieces.
Preventing Piece Fragmentation & CRLF/UTF-16 Surrogate Splits
1.CRLF Edge Case: If Piece A ends with \r and Piece B starts with \n, count them as 1 line break—not 2!
2.Surrogate Pair Guard: Validate cursor offsets before splitting UTF-16 code units so emojis never tear.
3.Background Defrag: Compact fragmented pieces during idle frames or on file Save.
CRLF/surrogate-safe split boundaries and idle piece compaction keep line counts accurate and tree height small.
Streaming Dirty Buffers to Disk & Append-Only Crash Recovery Journals.
Why this matters: Save 100 MB edited files safely via atomic temp-file streaming and recover unsaved keystrokes from WAL journals.
Overwriting a 100 MB mmap'd file in place while the Piece Tree still points into it would corrupt the editor's own Original Buffer!
Stream an in-order tree traversal to a temporary file (file.tmp), fsync(), atomically rename() over the target, and then re-open the new mmap as a clean 1-piece Original Buffer.
Streaming Dirty Buffers to Disk & Append-Only Crash Recovery Journals
1.Never Mutate Active mmap: Always write to a staging temp file and rename atomically before swapping the Original Buffer.
2.Fast Recovery Replay: Replaying 500 unsaved edit deltas on top of the disk file takes <5 ms on editor restart.
3.Memory Cap on Add Buffer: Resetting the Add Buffer on Save reclaims deleted/overwritten edit history.
Temp-file atomic saves and 2s edit WAL journals protect mmap'd Original Buffers from corruption and data loss.
Tracking Frame-Time p99, Piece Count & Tree-sitter Parse Lag.
Why this matters: Instrument keystroke-to-paint latency (<16 ms), piece-tree depth, and incremental syntax parse time.
Even a fast buffer feels sluggish if downstream syntax highlighting or viewport layout blocks the 16 ms main UI thread.
Track keystroke_buffer_edit_us (target < 100 us), piece_tree_node_count, piece_tree_depth, and treesitter_reparse_ms.
Tracking Frame-Time p99, Piece Count & Tree-sitter Parse Lag
1.Sub-100us Buffer Edits: Keeping buffer mutations under 0.1 ms leaves 15.9 ms for layout, syntax, and GPU paint.
2.Auto-Compaction Trigger: Piece count telemetry drives background compaction before tree depth degrades.
3.Incremental Tree-sitter: Pass exact byte/point edit ranges from the Piece Tree directly to Tree-sitter.
Sub-100us edit telemetry, >50K-piece compaction triggers, and incremental Tree-sitter keep 100 MB editing at 60fps.
Practice: Make the trade-off yourself.
Why did VS Code replace an array of line strings (`string[]`) with a Red-Black Piece Tree for large files?