Skip to content

Commit 61d8c54

Browse files
authored
bpo-42924: Fix incorrect copy in bytearray_repeat (GH-24208)
Before, using the * operator to repeat a bytearray would copy data from the start of the internal buffer (ob_bytes) and not from the start of the actual data (ob_start).
1 parent 1659ad1 commit 61d8c54

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

Lib/test/test_bytes.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1666,6 +1666,16 @@ def test_iterator_length_hint(self):
16661666
# Shouldn't raise an error
16671667
self.assertEqual(list(it), [])
16681668

1669+
def test_repeat_after_setslice(self):
1670+
# bpo-42924: * used to copy from the wrong memory location
1671+
b = bytearray(b'abc')
1672+
b[:2] = b'x'
1673+
b1 = b * 1
1674+
b3 = b * 3
1675+
self.assertEqual(b1, b'xc')
1676+
self.assertEqual(b1, b)
1677+
self.assertEqual(b3, b'xcxcxc')
1678+
16691679

16701680
class AssortedBytesTest(unittest.TestCase):
16711681
#
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``bytearray`` repetition incorrectly copying data from the start of the buffer, even if the data is offset within the buffer (e.g. after reassigning a slice at the start of the ``bytearray`` to a shorter byte string).

Objects/bytearrayobject.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
321321
PyByteArrayObject *result;
322322
Py_ssize_t mysize;
323323
Py_ssize_t size;
324+
const char *buf;
324325

325326
if (count < 0)
326327
count = 0;
@@ -329,13 +330,14 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
329330
return PyErr_NoMemory();
330331
size = mysize * count;
331332
result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
333+
buf = PyByteArray_AS_STRING(self);
332334
if (result != NULL && size != 0) {
333335
if (mysize == 1)
334-
memset(result->ob_bytes, self->ob_bytes[0], size);
336+
memset(result->ob_bytes, buf[0], size);
335337
else {
336338
Py_ssize_t i;
337339
for (i = 0; i < count; i++)
338-
memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
340+
memcpy(result->ob_bytes + i*mysize, buf, mysize);
339341
}
340342
}
341343
return (PyObject *)result;

0 commit comments

Comments
 (0)