]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-129813, PEP 782: Use PyBytesWriter in _sha3 (#138923)
authorVictor Stinner <vstinner@python.org>
Mon, 15 Sep 2025 20:53:03 +0000 (21:53 +0100)
committerGitHub <noreply@github.com>
Mon, 15 Sep 2025 20:53:03 +0000 (22:53 +0200)
Replace PyBytes_FromStringAndSize(NULL, size) with the new public
PyBytesWriter API.

Modules/sha3module.c

index 47fe5e57e6ddd99108c5aec846dad519ac2a0f03..14c543b86415d5d28c9be29251345fc208482f88 100644 (file)
@@ -509,14 +509,19 @@ _sha3_shake_128_digest_impl(SHA3object *self, Py_ssize_t length)
     if (length == 0) {
         return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
     }
-
     CHECK_HACL_UINT32_T_LENGTH(length);
-    PyObject *digest = PyBytes_FromStringAndSize(NULL, length);
-    uint8_t *buffer = (uint8_t *)PyBytes_AS_STRING(digest);
+
+    PyBytesWriter *writer = PyBytesWriter_Create(length);
+    if (writer == NULL) {
+        return NULL;
+    }
+    uint8_t *buffer = (uint8_t *)PyBytesWriter_GetData(writer);
+
     HASHLIB_ACQUIRE_LOCK(self);
     (void)Hacl_Hash_SHA3_squeeze(self->hash_state, buffer, (uint32_t)length);
     HASHLIB_RELEASE_LOCK(self);
-    return digest;
+
+    return PyBytesWriter_Finish(writer);
 }
 
 
@@ -540,8 +545,8 @@ _sha3_shake_128_hexdigest_impl(SHA3object *self, Py_ssize_t length)
     if (length == 0) {
         return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
     }
-
     CHECK_HACL_UINT32_T_LENGTH(length);
+
     uint8_t *buffer = PyMem_Malloc(length);
     if (buffer == NULL) {
         return PyErr_NoMemory();
@@ -550,6 +555,7 @@ _sha3_shake_128_hexdigest_impl(SHA3object *self, Py_ssize_t length)
     HASHLIB_ACQUIRE_LOCK(self);
     (void)Hacl_Hash_SHA3_squeeze(self->hash_state, buffer, (uint32_t)length);
     HASHLIB_RELEASE_LOCK(self);
+
     PyObject *digest = _Py_strhex((const char *)buffer, length);
     PyMem_Free(buffer);
     return digest;