]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-129813, PEP 782: Use PyBytesWriter in _ssl (#138929)
authorVictor Stinner <vstinner@python.org>
Thu, 18 Sep 2025 14:54:18 +0000 (15:54 +0100)
committerGitHub <noreply@github.com>
Thu, 18 Sep 2025 14:54:18 +0000 (16:54 +0200)
Replace PyBytes_FromStringAndSize(NULL, size) and _PyBytes_Resize()
with the new public PyBytesWriter API.

Modules/_ssl.c

index 1f31c2fee5b8e974ef315b371d4399547456070f..0731c48b460105a57a3220e19432f7a40d30766c 100644 (file)
@@ -2891,7 +2891,7 @@ _ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
                           int group_right_1, Py_buffer *buffer)
 /*[clinic end generated code: output=49b16e6406023734 input=80ed30436df01a71]*/
 {
-    PyObject *dest = NULL;
+    PyBytesWriter *writer = NULL;
     char *mem;
     size_t count = 0;
     int retval;
@@ -2918,14 +2918,16 @@ _ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
     }
 
     if (!group_right_1) {
-        dest = PyBytes_FromStringAndSize(NULL, len);
-        if (dest == NULL)
-            goto error;
         if (len == 0) {
             Py_XDECREF(sock);
-            return dest;
+            return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
+        }
+
+        writer = PyBytesWriter_Create(len);
+        if (writer == NULL) {
+            goto error;
         }
-        mem = PyBytes_AS_STRING(dest);
+        mem = PyBytesWriter_GetData(writer);
     }
     else {
         mem = buffer->buf;
@@ -3003,8 +3005,7 @@ _ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
 done:
     Py_XDECREF(sock);
     if (!group_right_1) {
-        _PyBytes_Resize(&dest, count);
-        return dest;
+        return PyBytesWriter_FinishWithSize(writer, count);
     }
     else {
         return PyLong_FromSize_t(count);
@@ -3013,8 +3014,9 @@ done:
 error:
     PySSL_ChainExceptions(self);
     Py_XDECREF(sock);
-    if (!group_right_1)
-        Py_XDECREF(dest);
+    if (!group_right_1) {
+        PyBytesWriter_Discard(writer);
+    }
     return NULL;
 }