From 2b0c8c89a0063e226dce9a025d70f424d8b25b11 Mon Sep 17 00:00:00 2001 From: Vitaliy Mysak Date: Wed, 7 Aug 2024 17:00:10 -0700 Subject: [PATCH] Do not rewrite base io unecessarily in subtextio --- src/multicsv/subtextio.py | 11 +++++++++-- tests/test_subtextio.py | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/multicsv/subtextio.py b/src/multicsv/subtextio.py index 2fdff40..bf40408 100644 --- a/src/multicsv/subtextio.py +++ b/src/multicsv/subtextio.py @@ -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 @@ -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 @@ -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: @@ -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: @@ -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) diff --git a/tests/test_subtextio.py b/tests/test_subtextio.py index a56d17c..52f3a19 100644 --- a/tests/test_subtextio.py +++ b/tests/test_subtextio.py @@ -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.