]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-129813, PEP 782: Use PyBytesWriter in memoryview (#138836)
authorVictor Stinner <vstinner@python.org>
Sat, 13 Sep 2025 16:36:05 +0000 (18:36 +0200)
committerGitHub <noreply@github.com>
Sat, 13 Sep 2025 16:36:05 +0000 (18:36 +0200)
Replace PyBytes_FromStringAndSize(NULL, size) with the new public
PyBytesWriter API.

Objects/memoryobject.c

index 94ff0fe624e61e20fef2a66d560a236ba627b173..f1232f389210eabb8acd8bc8aa7b829ddf593bf9 100644 (file)
@@ -2285,7 +2285,6 @@ memoryview_tobytes_impl(PyMemoryViewObject *self, const char *order)
 {
     Py_buffer *src = VIEW_ADDR(self);
     char ord = 'C';
-    PyObject *bytes;
 
     CHECK_RELEASED(self);
 
@@ -2303,16 +2302,18 @@ memoryview_tobytes_impl(PyMemoryViewObject *self, const char *order)
         }
     }
 
-    bytes = PyBytes_FromStringAndSize(NULL, src->len);
-    if (bytes == NULL)
+    PyBytesWriter *writer = PyBytesWriter_Create(src->len);
+    if (writer == NULL) {
         return NULL;
+    }
 
-    if (PyBuffer_ToContiguous(PyBytes_AS_STRING(bytes), src, src->len, ord) < 0) {
-        Py_DECREF(bytes);
+    if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
+                              src, src->len, ord) < 0) {
+        PyBytesWriter_Discard(writer);
         return NULL;
     }
 
-    return bytes;
+    return PyBytesWriter_Finish(writer);
 }
 
 /*[clinic input]
@@ -2344,8 +2345,6 @@ memoryview_hex_impl(PyMemoryViewObject *self, PyObject *sep,
 /*[clinic end generated code: output=430ca760f94f3ca7 input=539f6a3a5fb56946]*/
 {
     Py_buffer *src = VIEW_ADDR(self);
-    PyObject *bytes;
-    PyObject *ret;
 
     CHECK_RELEASED(self);
 
@@ -2353,19 +2352,22 @@ memoryview_hex_impl(PyMemoryViewObject *self, PyObject *sep,
         return _Py_strhex_with_sep(src->buf, src->len, sep, bytes_per_sep);
     }
 
-    bytes = PyBytes_FromStringAndSize(NULL, src->len);
-    if (bytes == NULL)
+    PyBytesWriter *writer = PyBytesWriter_Create(src->len);
+    if (writer == NULL) {
         return NULL;
+    }
 
-    if (PyBuffer_ToContiguous(PyBytes_AS_STRING(bytes), src, src->len, 'C') < 0) {
-        Py_DECREF(bytes);
+    if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
+                              src, src->len, 'C') < 0) {
+        PyBytesWriter_Discard(writer);
         return NULL;
     }
 
-    ret = _Py_strhex_with_sep(
-            PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes),
-            sep, bytes_per_sep);
-    Py_DECREF(bytes);
+    PyObject *ret = _Py_strhex_with_sep(
+        PyBytesWriter_GetData(writer),
+        PyBytesWriter_GetSize(writer),
+        sep, bytes_per_sep);
+    PyBytesWriter_Discard(writer);
 
     return ret;
 }