From 0084c8717a062f4fb70b033c411871f18276ea79 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 a90e8a4..ace8fd9 100644 --- a/content/posts/2024-07-06-gap-buffer/index.md +++ b/content/posts/2024-07-06-gap-buffer/index.md @@ -99,3 +99,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 +```