Skip to content

Commit f62b495

Browse files
authored
gh-129813, PEP 782: Use PyBytesWriter in _sha3 (#138923)
Replace PyBytes_FromStringAndSize(NULL, size) with the new public PyBytesWriter API.
1 parent 71defb6 commit f62b495

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

Modules/sha3module.c

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -509,14 +509,19 @@ _sha3_shake_128_digest_impl(SHA3object *self, Py_ssize_t length)
509509
if (length == 0) {
510510
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
511511
}
512-
513512
CHECK_HACL_UINT32_T_LENGTH(length);
514-
PyObject *digest = PyBytes_FromStringAndSize(NULL, length);
515-
uint8_t *buffer = (uint8_t *)PyBytes_AS_STRING(digest);
513+
514+
PyBytesWriter *writer = PyBytesWriter_Create(length);
515+
if (writer == NULL) {
516+
return NULL;
517+
}
518+
uint8_t *buffer = (uint8_t *)PyBytesWriter_GetData(writer);
519+
516520
HASHLIB_ACQUIRE_LOCK(self);
517521
(void)Hacl_Hash_SHA3_squeeze(self->hash_state, buffer, (uint32_t)length);
518522
HASHLIB_RELEASE_LOCK(self);
519-
return digest;
523+
524+
return PyBytesWriter_Finish(writer);
520525
}
521526

522527

@@ -540,8 +545,8 @@ _sha3_shake_128_hexdigest_impl(SHA3object *self, Py_ssize_t length)
540545
if (length == 0) {
541546
return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
542547
}
543-
544548
CHECK_HACL_UINT32_T_LENGTH(length);
549+
545550
uint8_t *buffer = PyMem_Malloc(length);
546551
if (buffer == NULL) {
547552
return PyErr_NoMemory();
@@ -550,6 +555,7 @@ _sha3_shake_128_hexdigest_impl(SHA3object *self, Py_ssize_t length)
550555
HASHLIB_ACQUIRE_LOCK(self);
551556
(void)Hacl_Hash_SHA3_squeeze(self->hash_state, buffer, (uint32_t)length);
552557
HASHLIB_RELEASE_LOCK(self);
558+
553559
PyObject *digest = _Py_strhex((const char *)buffer, length);
554560
PyMem_Free(buffer);
555561
return digest;

0 commit comments

Comments
 (0)