Skip to content

Commit

Permalink
Do not rewrite base io unecessarily in subtextio
Browse files Browse the repository at this point in the history
  • Loading branch information
Donaim committed Aug 8, 2024
1 parent cb55fbe commit 2b0c8c8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/multicsv/subtextio.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ class allows for convenient and isolated operations within a given

def __init__(self, base_io: TextIO, start: int, end: int):
self._initialized = False
self._need_flush = False
self._base_io = base_io
self._start = start
self._end = end
Expand Down Expand Up @@ -241,10 +242,11 @@ def write(self, s: str) -> int:

pre = self._buffer[:self._position]
post = self._buffer[self._position + len(s):]
self._buffer = pre + s + post

written = len(s)

self._buffer = pre + s + post
self._position += written
self._need_flush = True

return written

Expand All @@ -261,6 +263,7 @@ def truncate(self, size: Optional[int] = None) -> int:
end = size

self._buffer = self._buffer[:end]
self._need_flush = True
return self.buffer_length

def close(self) -> None:
Expand Down Expand Up @@ -294,6 +297,9 @@ def flush(self) -> None:
if self._base_io.closed:
raise BaseIOClosed("Base io is closed in flush.")

if not self._need_flush:
return

if not self._closed:
base_initial_position = self._base_io.tell()
try:
Expand All @@ -309,6 +315,7 @@ def flush(self) -> None:
self._base_io.write(self._buffer + content_after)

self._base_io.flush()
self._need_flush = False
finally:
self._base_io.seek(base_initial_position)

Expand Down
14 changes: 14 additions & 0 deletions tests/test_subtextio.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,3 +454,17 @@ def test_not_readable():
with tempfile.NamedTemporaryFile(mode="w") as file:
with pytest.raises(BaseMustBeReadable):
SubTextIO(file, start=0, end=10)

def test_not_writable(tmp_path):
path = tmp_path / "example.csv"

with path.open("w") as writer:
writer.write("hello")

with path.open("r") as file:
with SubTextIO(file, start=2, end=4) as sub_text:
assert sub_text.read() == "ll"
assert sub_text.read() == ""
assert sub_text.read() == ""
sub_text.flush() # should be a noop.
sub_text.flush() # should be a noop.

0 comments on commit 2b0c8c8

Please sign in to comment.