gh-129813, PEP 782: Use PyBytesWriter in _sha3 (#138923)

Replace PyBytes_FromStringAndSize(NULL, size) with the new public
PyBytesWriter API.
This commit is contained in:
Victor Stinner 2025-09-15 21:53:03 +01:00 committed by GitHub
parent 71defb6943
commit f62b495f79
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View 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;