gh-129813, PEP 782: Optimize byteswriter_resize() (#139101)

There is no need to copy the small_buffer in PyBytesWriter_Create().
This commit is contained in:
Victor Stinner 2025-09-18 10:52:16 +01:00 committed by GitHub
parent d1904b91cb
commit 9f7bbafffe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3801,7 +3801,7 @@ byteswriter_allocated(PyBytesWriter *writer)
static inline int static inline int
byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int overallocate) byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int resize)
{ {
assert(size >= 0); assert(size >= 0);
@ -3810,7 +3810,7 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int overallocate)
return 0; return 0;
} }
if (overallocate & writer->overallocate) { if (resize & writer->overallocate) {
if (size <= (PY_SSIZE_T_MAX - size / OVERALLOCATE_FACTOR)) { if (size <= (PY_SSIZE_T_MAX - size / OVERALLOCATE_FACTOR)) {
size += size / OVERALLOCATE_FACTOR; size += size / OVERALLOCATE_FACTOR;
} }
@ -3834,25 +3834,29 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t size, int overallocate)
if (writer->obj == NULL) { if (writer->obj == NULL) {
return -1; return -1;
} }
assert((size_t)size > sizeof(writer->small_buffer)); if (resize) {
memcpy(PyByteArray_AS_STRING(writer->obj), assert((size_t)size > sizeof(writer->small_buffer));
writer->small_buffer, memcpy(PyByteArray_AS_STRING(writer->obj),
sizeof(writer->small_buffer)); writer->small_buffer,
sizeof(writer->small_buffer));
}
} }
else { else {
writer->obj = PyBytes_FromStringAndSize(NULL, size); writer->obj = PyBytes_FromStringAndSize(NULL, size);
if (writer->obj == NULL) { if (writer->obj == NULL) {
return -1; return -1;
} }
assert((size_t)size > sizeof(writer->small_buffer)); if (resize) {
memcpy(PyBytes_AS_STRING(writer->obj), assert((size_t)size > sizeof(writer->small_buffer));
writer->small_buffer, memcpy(PyBytes_AS_STRING(writer->obj),
sizeof(writer->small_buffer)); writer->small_buffer,
sizeof(writer->small_buffer));
}
} }
#ifdef Py_DEBUG #ifdef Py_DEBUG
Py_ssize_t allocated = byteswriter_allocated(writer); Py_ssize_t allocated = byteswriter_allocated(writer);
if (overallocate && allocated > old_allocated) { if (resize && allocated > old_allocated) {
memset(byteswriter_data(writer) + old_allocated, 0xff, memset(byteswriter_data(writer) + old_allocated, 0xff,
allocated - old_allocated); allocated - old_allocated);
} }