8000 [3.9] bpo-44439: _ZipWriteFile.write() handle buffer protocol correctly (GH-29468) by miss-islington · Pull Request #31755 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

[3.9] bpo-44439: _ZipWriteFile.write() handle buffer protocol correctly (GH-29468) #31755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_zipfile.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import array
import contextlib
import importlib.util
import io
Expand Down Expand Up @@ -1117,6 +1118,14 @@ def test_write_after_close(self):
self.assertRaises(ValueError, w.write, b'')
self.assertEqual(zipf.read('test'), data)

def test_issue44439(self):
q = array.array('Q', [1, 2, 3, 4, 5])
LENGTH = len(q) * q.itemsize
with zipfile.ZipFile(io.BytesIO(), 'w', self.compression) as zip:
with zip.open('data', 'w') as data:
self.assertEqual(data.write(q), LENGTH)
self.assertEqual(zip.getinfo('data').file_size, LENGTH)

class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_STORED

Expand Down
9 changes: 8 additions & 1 deletion Lib/zipfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1120,8 +1120,15 @@ def writable(self):
def write(self, data):
if self.closed:
raise ValueError('I/O operation on closed file.')
nbytes = len(data)

# Accept any data that supports the buffer protocol
if isinstance(data, (bytes, bytearray)):
nbytes = len(data)
else:
data = memoryview(data)
nbytes = data.nbytes
self._file_size += nbytes

self._crc = crc32(data, self._crc)
if self._compressor:
data = self._compressor.compress(data)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix ``.write()`` method of a member file in ``ZipFile``, when the input data is
an object that supports the buffer protocol, the file length may be wrong.
0