From 18b7787a31ff0971a97d6de17c06ecb02f9f13c3 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 6 Jul 2024 23:36:20 +0100 Subject: [PATCH] posts: gap-buffer: add growth --- content/posts/2024-07-06-gap-buffer/index.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/content/posts/2024-07-06-gap-buffer/index.md b/content/posts/2024-07-06-gap-buffer/index.md index 87dd315..fc8cffc 100644 --- a/content/posts/2024-07-06-gap-buffer/index.md +++ b/content/posts/2024-07-06-gap-buffer/index.md @@ -98,3 +98,25 @@ def prefix_length(self) -> int: def suffix_length(self) -> int: return self.capacity - self._gap_end ``` + +### Growing the buffer + +I've written this method in a somewhat non-idiomatic manner, to make it closer +to how it would look in C using `realloc` instead. + +It would be more efficient to use slicing to insert the needed extra capacity +directly, instead of making a new buffer and copying characters over. + +```python +def grow(self, capacity: int) -> None: + assert capacity >= self.capacity + # Create a new buffer with the new capacity + new_buf = [""] * capacity + # Move the prefix/suffix to their place in the new buffer + added_capacity = capacity - len(self._buf) + new_buf[: self._gap_start] = self._buf[: self._gap_start] + new_buf[self._gap_end + added_capacity :] = self._buf[self._gap_end :] + # Use the new buffer, account for added capacity + self._buf = new_buf + self._gap_end += added_capacity +```