]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42924: Fix incorrect copy in bytearray_repeat (GH-24208)
authorTobias Holl <TobiasHoll@users.noreply.github.com>
Wed, 13 Jan 2021 16:16:40 +0000 (17:16 +0100)
committerGitHub <noreply@github.com>
Wed, 13 Jan 2021 16:16:40 +0000 (18:16 +0200)
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).

Lib/test/test_bytes.py
Misc/NEWS.d/next/Core and Builtins/2021-01-13-14-06-01.bpo-42924._WS1Ok.rst [new file with mode: 0644]
Objects/bytearrayobject.c

index d550abfc65640d77ae55e1682794107833333841..381030fe0e838302b5044543173471e543d1308d 100644 (file)
@@ -1666,6 +1666,16 @@ class ByteArrayTest(BaseBytesTest, unittest.TestCase):
         # Shouldn't raise an error
         self.assertEqual(list(it), [])
 
+    def test_repeat_after_setslice(self):
+        # bpo-42924: * used to copy from the wrong memory location
+        b = bytearray(b'abc')
+        b[:2] = b'x'
+        b1 = b * 1
+        b3 = b * 3
+        self.assertEqual(b1, b'xc')
+        self.assertEqual(b1, b)
+        self.assertEqual(b3, b'xcxcxc')
+
 
 class AssortedBytesTest(unittest.TestCase):
     #
diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-01-13-14-06-01.bpo-42924._WS1Ok.rst b/Misc/NEWS.d/next/Core and Builtins/2021-01-13-14-06-01.bpo-42924._WS1Ok.rst
new file mode 100644 (file)
index 0000000..33fbb52
--- /dev/null
@@ -0,0 +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).
index 7cb2b1478cf9c113e6f1ab0f486b3b8bbf1c54db..2eaca5cec42908b70afd1ba9949aa76d7ac6d731 100644 (file)
@@ -321,6 +321,7 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
     PyByteArrayObject *result;
     Py_ssize_t mysize;
     Py_ssize_t size;
+    const char *buf;
 
     if (count < 0)
         count = 0;
@@ -329,13 +330,14 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
         return PyErr_NoMemory();
     size = mysize * count;
     result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
+    buf = PyByteArray_AS_STRING(self);
     if (result != NULL && size != 0) {
         if (mysize == 1)
-            memset(result->ob_bytes, self->ob_bytes[0], size);
+            memset(result->ob_bytes, buf[0], size);
         else {
             Py_ssize_t i;
             for (i = 0; i < count; i++)
-                memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize);
+                memcpy(result->ob_bytes + i*mysize, buf, mysize);
         }
     }
     return (PyObject *)result;