Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0663ca1

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 89c3601 commit 0663ca1

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/test/test_zipfile.py

+9
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
@@ -1117,6 +1118,14 @@ def test_write_after_close(self):
11171118
self.assertRaises(ValueError, w.write, b'')
11181119
self.assertEqual(zipf.read('test'), data)
11191120

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

Lib/zipfile.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1120,8 +1120,15 @@ def writable(self):
11201120
def write(self, data):
11211121
if self.closed:
11221122
raise ValueError('I/O operation on closed file.')
1123-
nbytes = len(data)
1123+
1124+
# Accept any data that supports the buffer protocol
1125+
if isinstance(data, (bytes, bytearray)):
1126+
nbytes = len(data)
1127+
else:
1128+
data = memoryview(data)
1129+
nbytes = data.nbytes
11241130
self._file_size += nbytes
1131+
11251132
self._crc = crc32(data, self._crc)
11261133
if self._compressor:
11271134
data = self._compressor.compress(data)
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)