Skip to content

Commit 21c5b3f

Browse files
miss-islingtonMa Lin
and
Ma Lin
authored
bpo-44439: _ZipWriteFile.write() handle buffer protocol correctly (GH-29468)
Co-authored-by: Marco Ribeiro <[email protected]> (cherry picked from commit 36dd739) Co-authored-by: Ma Lin <[email protected]>
1 parent b099363 commit 21c5b3f

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/test/test_zipfile.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import array
12
import contextlib
23
import importlib.util
34
import io
@@ -1119,6 +1120,14 @@ def test_write_after_close(self):
11191120
self.assertRaises(ValueError, w.write, b'')
11201121
self.assertEqual(zipf.read('test'), data)
11211122

1123+
def test_issue44439(self):
1124+
q = array.array('Q', [1, 2, 3, 4, 5])
1125+
LENGTH = len(q) * q.itemsize
1126+
with zipfile.ZipFile(io.BytesIO(), 'w', self.compression) as zip:
1127+
with zip.open('data', 'w') as data:
1128+
self.assertEqual(data.write(q), LENGTH)
1129+
self.assertEqual(zip.getinfo('data').file_size, LENGTH)
1130+
11221131
class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
11231132
compression = zipfile.ZIP_STORED
11241133

Lib/zipfile.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1121,8 +1121,15 @@ def writable(self):
11211121
def write(self, data):
11221122
if self.closed:
11231123
raise ValueError('I/O operation on closed file.')
1124-
nbytes = len(data)
1124+
1125+
# Accept any data that supports the buffer protocol
1126+
if isinstance(data, (bytes, bytearray)):
1127+
nbytes = len(data)
1128+
else:
1129+
data = memoryview(data)
1130+
nbytes = data.nbytes
11251131
self._file_size += nbytes
1132+
11261133
self._crc = crc32(data, self._crc)
11271134
if self._compressor:
11281135
data = self._compressor.compress(data)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``.write()`` method of a member file in ``ZipFile``, when the input data is
2+
an object that supports the buffer protocol, the file length may be wrong.

0 commit comments

Comments
 (0)