Gap Buffer: Procedure If Procedure If
Gap Buffer: Procedure If Procedure If
A gap buffer is a data structure for the implementation of text editors, which can efficiently move the
cursor, as well add and delete characters.
The idea is simple: the editor’s content is represented as a character array a of length n, which
has a gap of unused entries a[l], . . . , a[r − 1], with respect to two indices l ≤ r. The data it represents
is composed as a[0], . . . , a[l − 1], a[r], ..., a[n − 1].
The current cursor position is at the left index l, and if we type a character, it is written to a[l]
and l is increased. When the gap becomes empty, the array is enlarged and the data from r is shifted
to the right.
Implementation task. Implement the following four operations in the language of your tool: Pro-
cedures left() and right() move the cursor by one character; insert() places a character at the
beginning of the gap a[l]; delete() removes the character at a[l] from the range of text.
Verification task. Specify the intended behavior of the buffer in terms of a contiguous representa-
tion of the editor content. This can for example be based on strings, functional arrays, sequences, or
lists. Verify that the gap buffer implementation satisfies this specification, and that every access to
the array is within bounds.
Hint: For this task you may assume that insert() has the precondition l < r and remove the call
to grow(). Alternatively, assume a contract for grow() that ensures that this call does not change the
abstract representation.
Extended verification task. Implement the operation grow(), specify its behavior in a way that
lets you verify insert() in a modular way (i.e. not by referring to the implementation of grow()),
and verify that grow() satisfies this specification.
Hint: You may assume that the allocation of the new buffer always succeeds. If your tool/lan-
guage supports copying array ranges (such as System.arraycopy() in Java), consider using these
primitives instead of the loops in the pseudo-code below.
1
procedure grow()
var b := new char[a.length + K]
// b[0..l] := a[0..l]
for i = 0 to l - 1 do
b[i] := a[i]
end-for
r := r + K
a := b
end-procedure
Resources
• https://en.wikipedia.org/wiki/Gap_buffer
• http://scienceblogs.com/goodmath/2009/02/18/gap-buffers-or-why-bother-with-1