From e05ed1cc4aac43a8c266bbff31a3919b672225e9 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 6 Jul 2024 23:36:46 +0100 Subject: [PATCH] posts: gap-buffer: add deletion --- content/posts/2024-07-06-gap-buffer/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/content/posts/2024-07-06-gap-buffer/index.md b/content/posts/2024-07-06-gap-buffer/index.md index b23f21a..9ca44ea 100644 --- a/content/posts/2024-07-06-gap-buffer/index.md +++ b/content/posts/2024-07-06-gap-buffer/index.md @@ -140,3 +140,22 @@ def insert(self, val: str) -> None: self._buf[self._gap_start : self._gap_start + len(val)] = val self._gap_start += len(val) ``` + +### Deletion + +Removing text from the buffer simply expands the gap in the corresponding +direction, shortening the string's prefix/suffix. This makes it very cheap. + +The methods are named after the `backspace` and `delete` keys on the keyboard. + +```python +def backspace(self, dist: int = 1) -> None: + assert dist <= self.prefix_length + # Extend gap to the left + self._gap_start -= dist + +def delete(self, dist: int = 1) -> None: + assert dist <= self.suffix_length + # Extend gap to the right + self._gap_end += dist +```