The Mighty Piece Table
There is a lot of options when it comes to text data structures, and ultimately there’s a tradeoff between speed of editing, lookup and simplicity. Another aspect to consider is how “undo-friendly” it is, or if the data structure supports multiple cursors reasonably.
I will not ellaborate much here, here’s how I’d classify it:
| Data structure | Simplicity | Scalability | Multi Cursor | Undo Friendly | Notes |
|---|---|---|---|---|---|
| Nothing, bare buffer | 5 / 5 | 0 / 5 | 0 / 5 | 2 / 5 | Chokes very easily, you can think of this as being the “baseline” |
| Array of lines | 3 / 5 | 3 / 5 | 3 / 5 | 2 / 5 | Requires a lot extra work to avoid bad memory allocation patterns and waste |
| Gap Buffer | 5 / 5 | 1 / 5 | 2 / 5 | 2 / 5 | Bang for your buck, suffers on non local edits (multi-cursor) |
| Piece Table | 4 / 5 | 4 / 5 | 4 / 5 | 5 / 5 | Solid workhorse, the topic of this article. |
| Rope | 2 / 5 | 5 / 5 | 4 / 5 | 5 / 5 | Great choice, but can be quite complex and have high memory overhead |
Metrics:
- Simplicity: how simple is it? does it require very complex datastructures and algorithms?
- Scalability: can it handle big text corpus (up to 1GB or so) without having to add significant helpers?
- Multi Cursor: is multiple sparse edits a pathological case? is it hard to add multi cursor functionality?
- Undo Friendly: can it be made persistent? does the undo buffer require a lot of metadata?
Important: These metrics are not scientific and I don’t care!
2 Buffers, 1 Table
A piece table is composed of 2 buffers, the append buffer is an append-only buffer where all inserted text goes. The original buffer is a read-only buffer that has the original text (or nothing, if we’re dealing with a totally new file).
Piece_Table :: struct {
original: []u8,
append: [dynamic]u8,
pieces: [dynamic]Piece
}
The pieces themselves, just contains ranges and to which buffer they belong.
Piece :: struct {
start: u32,
size: u32,
original: bool,
}
Inserting
For inserting text, it is simple, you just append to the append buffer and create a piece pointing to the recently
appended content.
So if we start with Hello world and no edits yet, there is a single piece covering the whole original buffer:
Now we insert beautiful at index 6. The text goes to the end of the append buffer, the piece that contained the
insertion point is split in two, and a new piece pointing at the appended text goes between them.
Interactively
Knowing this process is nice and all, however, this only applies for inserting text “chunks”, not really char by char as humans type. So how can we take this original idea, but make it so it isn’t completely rendered useless by creating a piece per character? We create a simple check, if a piece is appendable, we can just append to it without making up new pieces
Definition: A piece is appendable if, and only if, it is an append buffer piece and the end of its data slice coincides with the end of the append buffer. Here, we have highlighted in a orange tone the appendable pieces.
This case is trivial though, so can we convert the harder cases into this one? It’s quite simple actually. If the current piece is not appendable, we split it at the insertion index and add a new piece that is appendable in the middle. Any subsequent insertions (i.e. regular typing) will simply grow that piece instead of creating pointless splits.
Here the cursor sits in the middle of the original text, so there is no appendable piece to grow. The first character splits the piece and puts a new, appendable one between the halves. Every character after that just grows it:
Deleting
Deleting a range of text is quite similar to insertion, we perform splits and adjust the lenghts of both ends of the deletion range, whatever pieces are fully covered by the range are totally removed.
Here we delete lo big wor from Hello big world. The first and last pieces just get trimmed, and the small big
piece in the middle is fully covered by the range, so it is removed altogether. The buffers are never touched, only the
piece list changes:
Interactively
Just like we introduced the appendable concept to simplify interactive insertions, for deletions we use the the term shrinkable.
Definition: A piece is shrinkable if and only if the deletion of the character coincides with the end of its data slice, it then can have its length reduced. A piece of length equal to zero is deleted.
The trivial case: the cursor sits right after big, which is the end of that piece’s slice. Every backspace just
reduces its size, and when it reaches zero the piece is gone:
Just like insertion, if the shrinkable constraint is not met, we just split the piece so that it does.
Here the cursor is in the middle of the original piece, after Hello wor. The first backspace splits it, and the left
half it leaves behind ends exactly at the cursor, so it is shrinkable. The next backspaces simply shrink it:
Lookup
There’s 3 main types of textual lookup a text editor performs.
- Offset: Jump to a particular offset of text, this is the “primitive” to place the cursor anywhere
- Line/Column: Go to a visual position within the text, this is particularly important for humans
- Pattern: Scan things to find a regex or do a fuzzy search. This is a distinct concern, as it deals with textual search itself.
For offset lookup, we can simply iterate all the pieces, thus making it O(n), while that seems bad, in practice
the pieces chunk text so it is faster, this can be mitigated however to get an average of O(log n) access by storing
our table not as a plain vector but as a tree of pieces, where each node knows the combined length of its left subtree.
This can be done with your tree of choice, you can use a RB-Tree
Appendix: Small implementation in Odin
This is not meant to be a clean API nor the most optimized implementation, use this as an educational baseline. Overflow checks and more sophisticated optimizations with vectorized instructions are left to the reader as a challenge. I have added basic UTF-8 snapping as that is a concern that is common in text editors, although this example implementation can definetely be made more robust.
package piece_table
import "core:mem"
import "core:unicode/utf8"
Piece :: struct {
start: u32,
size: u32,
original: bool,
}
Piece_Table :: struct {
original: []u8,
append: [dynamic]u8,
pieces: [dynamic]Piece,
}
init :: proc(tbl: ^Piece_Table, original: []u8, allocator := context.allocator) -> (err: mem.Allocator_Error) {
tbl.original = original
tbl.append = make([dynamic]u8, allocator) or_return
tbl.pieces = make([dynamic]Piece, allocator) or_return
if len(original) > 0 {
append(&tbl.pieces, Piece{start = 0, size = u32(len(original)), original = true}) or_return
}
return
}
destroy :: proc(table: ^Piece_Table) {
delete(table.append)
delete(table.pieces)
}
piece_bytes :: proc(table: ^Piece_Table, piece: Piece) -> []u8 {
buffer := table.original if piece.original else table.append[:]
return buffer[piece.start:][:piece.size]
}
length :: proc(table: ^Piece_Table) -> int {
total := 0
for piece in table.pieces {
total += int(piece.size)
}
return total
}
find_piece :: proc(table: ^Piece_Table, offset: int) -> (index, inside: int) {
start := 0
for piece, piece_index in table.pieces {
if offset < start + int(piece.size) {
return piece_index, offset - start
}
start += int(piece.size)
}
return len(table.pieces), 0
}
byte_at :: proc(table: ^Piece_Table, offset: int, loc := #caller_location) -> u8 {
assert(0 <= offset && offset < length(table), "invalid byte offset", loc)
index, inside := find_piece(table, offset)
return piece_bytes(table, table.pieces[index])[inside]
}
line_offset :: proc(table: ^Piece_Table, line: int) -> (offset: int, ok: bool) {
if line == 0 {
return 0, true
}
newlines, position := 0, 0
for piece in table.pieces {
for character in piece_bytes(table, piece) {
position += 1
if character == '\n' {
newlines += 1
if newlines == line {
return position, true
}
}
}
}
return 0, false
}
build_string :: proc(table: ^Piece_Table, allocator := context.allocator) -> (text: string, err: mem.Allocator_Error) {
buf := make([dynamic]u8, 0, length(table), allocator) or_return
for piece in table.pieces {
append(&buf, ..piece_bytes(table, piece))
}
return string(buf[:]), nil
}
split_at :: proc(table: ^Piece_Table, offset: int) -> (new_piece_pos: int) {
index, inside := find_piece(table, offset)
if inside == 0 {
return index
}
piece := table.pieces[index]
table.pieces[index] = Piece{piece.start, u32(inside), piece.original}
inject_at(&table.pieces, index + 1, Piece{piece.start + u32(inside), piece.size - u32(inside), piece.original})
return index + 1
}
insert_new_text_piece :: proc(table: ^Piece_Table, offset: int, text: string) {
assert(0 <= offset && offset <= length(table))
if len(text) == 0 {
return
}
start := u32(len(table.append))
append_string(&table.append, text)
inject_at(&table.pieces, split_at(table, offset), Piece{start, u32(len(text)), false})
}
appendable :: proc(table: ^Piece_Table, index: int) -> bool {
piece := table.pieces[index]
return !piece.original && int(piece.start + piece.size) == len(table.append)
}
insert_text :: proc(table: ^Piece_Table, offset: int, text: string) {
assert(0 <= offset && offset <= length(table))
if offset > 0 {
index, inside := find_piece(table, offset - 1)
end_of_piece := inside == int(table.pieces[index].size) - 1
if appendable(table, index) && end_of_piece {
append_string(&table.append, text)
table.pieces[index].size += u32(len(text))
return
}
}
insert_new_text_piece(table, offset, text)
}
delete_range_raw :: proc(table: ^Piece_Table, offset, count: int) {
assert(0 <= offset && 0 <= count && offset + count <= length(table))
if count == 0 {
return
}
first := split_at(table, offset)
last := split_at(table, offset + count)
remove_range(&table.pieces, first, last)
}
// Snap `offset` back to the first byte of the UTF-8 code point it is in, snaps at most 4 bytes
snap_codepoint_backward :: proc(table: ^Piece_Table, offset: int) -> int {
start := offset
for steps := 0; steps < 3 && 0 < start && start < length(table) && !utf8.rune_start(byte_at(table, start)); steps += 1 {
start -= 1
}
return start
}
snap_codepoint_forward :: proc(table: ^Piece_Table, offset: int) -> int {
end := offset
for steps := 0; steps < 3 && end < length(table) && !utf8.rune_start(byte_at(table, end)); steps += 1 {
end += 1
}
return end
}
delete_text :: proc(table: ^Piece_Table, offset, count: int) {
assert(0 <= offset && 0 <= count && offset + count <= length(table))
if count == 0 {
return
}
start := snap_codepoint_backward(table, offset)
end := snap_codepoint_forward(table, offset + count)
delete_range_raw(table, start, end - start)
}
backspace :: proc(table: ^Piece_Table, cursor: int, loc := #caller_location) {
assert(0 < cursor && cursor <= length(table), "invalid cursor", loc)
start := snap_codepoint_backward(table, cursor - 1)
count := cursor - start
index, inside := find_piece(table, start)
piece := &table.pieces[index]
shrinkable := (inside + count) == int(piece.size)
if shrinkable {
piece.size -= u32(count)
if piece.size == 0 {
ordered_remove(&table.pieces, index)
}
return
}
delete_range_raw(table, start, count)
}