Skip to content

Commit d0698c6

Browse files
bpo-42924: Fix incorrect copy in bytearray_repeat (GH-24208) (#24211)
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). (cherry picked from commit 61d8c54) Co-authored-by: Tobias Holl <TobiasHoll@users.noreply.github.com>
1 parent c9c1dbd commit d0698c6

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
@@ -1664,6 +1664,16 @@ def test_iterator_length_hint(self):
16641664
# Shouldn't raise an error
16651665
self.assertEqual(list(it), [])
16661666

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

16681678
class AssortedBytesTest(unittest.TestCase):
16691679
#
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
@@ -329,6 +329,7 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
329329
PyByteArrayObject *result;
330330
Py_ssize_t mysize;
331331
Py_ssize_t size;
332+
const char *buf;
332333

333334
if (count < 0)
334335
count = 0;
@@ -337,13 +338,14 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
337338
return PyErr_NoMemory();
338339
size = mysize * count;
339340
result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
341+
buf = PyByteArray_AS_STRING(self);
340342
if (result != NULL && size != 0) {
341343
if (mysize == 1)
342-
memset(result->ob_bytes, self->ob_bytes[0], size);
344+
memset(result->ob_bytes, buf[0], size);
343345
else {
344346
Py_ssize_t i;
345347
for (i = 0; i < count; i++)
346-
memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
348+
memcpy(result->ob_bytes + i*mysize, buf, mysize);
347349
}
348350
}
349351
return (PyObject *)result;

0 commit comments

Comments
 (0)