Skip to content

Commit e1203e8

Browse files
bpo-42924: Fix incorrect copy in bytearray_repeat (GH-24208) (#24212)
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 081bfe4 commit e1203e8

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

1595+
def test_repeat_after_setslice(self):
1596+
# bpo-42924: * used to copy from the wrong memory location
1597+
b = bytearray(b'abc')
1598+
b[:2] = b'x'
1599+
b1 = b * 1
1600+
b3 = b * 3
1601+
self.assertEqual(b1, b'xc')
1602+
self.assertEqual(b1, b)
1603+
self.assertEqual(b3, b'xcxcxc')
1604+
15951605

15961606
class AssortedBytesTest(unittest.TestCase):
15971607
#
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
@@ -332,6 +332,7 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
332332
PyByteArrayObject *result;
333333
Py_ssize_t mysize;
334334
Py_ssize_t size;
335+
const char *buf;
335336

336337
if (count < 0)
337338
count = 0;
@@ -340,13 +341,14 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
340341
return PyErr_NoMemory();
341342
size = mysize * count;
342343
result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
344+
buf = PyByteArray_AS_STRING(self);
343345
if (result != NULL && size != 0) {
344346
if (mysize == 1)
345-
memset(result->ob_bytes, self->ob_bytes[0], size);
347+
memset(result->ob_bytes, buf[0], size);
346348
else {
347349
Py_ssize_t i;
348350
for (i = 0; i < count; i++)
349-
memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
351+
memcpy(result->ob_bytes + i*mysize, buf, mysize);
350352
}
351353
}
352354
return (PyObject *)result;

0 commit comments

Comments
 (0)