From 63795c813518f6f5065415e2dd6c5c187ba2ca8e Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Wed, 5 Feb 2025 12:39:24 -0800 Subject: [PATCH 1/3] gh-129005: Update _pyio.BytesIO to use bytearray.resize on write --- Lib/_pyio.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 023478aa78c6a0..c649fca1338b77 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -937,10 +937,8 @@ def write(self, b): return 0 pos = self._pos if pos > len(self._buffer): - # Inserts null bytes between the current end of the file - # and the new write position. - padding = b'\x00' * (pos - len(self._buffer)) - self._buffer += padding + # Expand the buffer to be able to hold the new bytes. + self._buffer.resize(pos + n) self._buffer[pos:pos + n] = b self._pos += n return n From 7d30781fce07e41a264642746e390ab6ca87b9c3 Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Wed, 5 Feb 2025 14:42:07 -0800 Subject: [PATCH 2/3] Update Lib/_pyio.py Co-authored-by: Victor Stinner --- Lib/_pyio.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/_pyio.py b/Lib/_pyio.py index c649fca1338b77..0b86024919c1bc 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -938,7 +938,7 @@ def write(self, b): pos = self._pos if pos > len(self._buffer): # Expand the buffer to be able to hold the new bytes. - self._buffer.resize(pos + n) + self._buffer.resize(pos) self._buffer[pos:pos + n] = b self._pos += n return n From e1929030ff11fb05ea7d3b2b3b59ac6db945c66e Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Wed, 5 Feb 2025 15:03:26 -0800 Subject: [PATCH 3/3] Update comment --- Lib/_pyio.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 0b86024919c1bc..b3a8f37d68acdb 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -937,7 +937,7 @@ def write(self, b): return 0 pos = self._pos if pos > len(self._buffer): - # Expand the buffer to be able to hold the new bytes. + # Pad buffer to pos with null bytes. self._buffer.resize(pos) self._buffer[pos:pos + n] = b self._pos += n