Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
8 changes: 4 additions & 4 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2845,10 +2845,10 @@ objects.

Resize the :class:`bytearray` using :ref:`Memory Management <memory>` APIs
to contain *size* bytes. Data from the existing :class:`bytearray` will be
kept up to *size*. Any new bytes (the :class:`bytearray` grew) will be
unchanged from the memory allocator except one byte beyond the requested
*size* which will be set to NULL to ensure the :class:`bytearray` is
always NULL terminated.
kept up to *size*. If :class:`bytearray` needs to grow, all new bytes will
be zeroed / set to the NULL byte (``b"\0"``). One byte beyond *size* will
always be set to NULL to ensure the :class:`bytearray` is always NULL
terminated regardless of contents.

.. versionadded:: next

Expand Down
14 changes: 9 additions & 5 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1365,15 +1365,19 @@ def test_resize(self):
self.assertEqual(ba, bytearray(b'abc'))
self.assertIsNone(ba.resize(10))
self.assertEqual(len(ba), 10)
# Check bytes are intact after resize including the NULL from .resize(3)
self.assertEqual(ba[:4], bytearray(b'abc\0'))
# Bytes beyond set values must be cleared.
self.assertEqual(ba, bytearray(b'abc\0\0\0\0\0\0\0'))
expected_bytearray = bytearray(b'abcdeabcde')
ba[3:10] = b'deabcde'
self.assertEqual(ba, expected_bytearray)
self.assertIsNone(ba.resize(2**20))
self.assertEqual(len(ba), 2**20)
self.assertEqual(ba[:4], bytearray(b'abc\0'))
# Check for NULL from .resize(10)
self.assertEqual(ba[10], 0)
self.assertEqual(ba[:10], expected_bytearray)
self.assertEqual(ba[10:], bytearray(b'\0' * (2 ** 20 - 10)))
self.assertIsNone(ba.resize(0))
self.assertEqual(ba, bytearray())
self.assertIsNone(ba.resize(10))
self.assertEqual(ba, bytearray(b'\0' * 10))

ba = ByteArraySubclass(b'abcdef')
self.assertIsNone(ba.resize(3))
Expand Down
5 changes: 5 additions & 0 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1405,10 +1405,15 @@ static PyObject *
bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size)
/*[clinic end generated code: output=f73524922990b2d9 input=75fd4d17c4aa47d3]*/
{
Py_ssize_t start_size = PyByteArray_GET_SIZE(self);
int result = PyByteArray_Resize((PyObject *)self, size);
if (result == -1) {
return NULL;
}
// Set new bytes to provide consistent / safer behavior in Python version.
if (size > start_size) {
memset(PyByteArray_AS_STRING(self) + start_size, 0, size-start_size);
}
Py_RETURN_NONE;
}

Expand Down
Loading