https://github.com/python/cpython/commit/4554486f156ee399d14a3324a2e214e6527b0b2b
commit: 4554486f156ee399d14a3324a2e214e6527b0b2b
branch: main
author: Victor Stinner <[email protected]>
committer: vstinner <[email protected]>
date: 2025-09-15T21:50:09Z
summary:
gh-129813, PEP 782: Use PyBytesWriter in bufferedio.c (#138954)
Replace PyBytes_FromStringAndSize(NULL, size) and _PyBytes_Resize()
with the new public PyBytesWriter API.
files:
M Modules/_io/bufferedio.c
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index 25be21111b95ee..d0fe7ad61547da 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -1026,9 +1026,6 @@ static PyObject *
_io__Buffered_read1_impl(buffered *self, Py_ssize_t n)
/*[clinic end generated code: output=bcc4fb4e54d103a3 input=3d0ad241aa52b36c]*/
{
- Py_ssize_t have, r;
- PyObject *res = NULL;
-
CHECK_INITIALIZED(self)
if (n < 0) {
n = self->buffer_size;
@@ -1036,48 +1033,53 @@ _io__Buffered_read1_impl(buffered *self, Py_ssize_t n)
CHECK_CLOSED(self, "read of closed file")
- if (n == 0)
- return PyBytes_FromStringAndSize(NULL, 0);
+ if (n == 0) {
+ return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
+ }
/* Return up to n bytes. If at least one byte is buffered, we
only return buffered bytes. Otherwise, we do one raw read. */
- have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
+ Py_ssize_t have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
if (have > 0) {
n = Py_MIN(have, n);
- res = _bufferedreader_read_fast(self, n);
+ PyObject *res = _bufferedreader_read_fast(self, n);
assert(res != Py_None);
return res;
}
- res = PyBytes_FromStringAndSize(NULL, n);
- if (res == NULL)
- return NULL;
+
if (!ENTER_BUFFERED(self)) {
- Py_DECREF(res);
return NULL;
}
+
/* Flush the write buffer if necessary */
if (self->writable) {
- PyObject *r = buffered_flush_and_rewind_unlocked(self);
- if (r == NULL) {
+ PyObject *res = buffered_flush_and_rewind_unlocked(self);
+ if (res == NULL) {
LEAVE_BUFFERED(self)
- Py_DECREF(res);
return NULL;
}
- Py_DECREF(r);
+ Py_DECREF(res);
}
_bufferedreader_reset_buf(self);
- r = _bufferedreader_raw_read(self, PyBytes_AS_STRING(res), n);
+
+ PyBytesWriter *writer = PyBytesWriter_Create(n);
+ if (writer == NULL) {
+ return NULL;
+ }
+
+ Py_ssize_t r = _bufferedreader_raw_read(self,
+ PyBytesWriter_GetData(writer), n);
LEAVE_BUFFERED(self)
if (r == -1) {
- Py_DECREF(res);
+ PyBytesWriter_Discard(writer);
return NULL;
}
- if (r == -2)
+ if (r == -2) {
r = 0;
- if (n > r)
- _PyBytes_Resize(&res, r);
- return res;
+ }
+
+ return PyBytesWriter_FinishWithSize(writer, r);
}
static PyObject *
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]