Skip to content

Commit e814e6b

Browse files
authored
gh-129813, PEP 782: Use PyBytesWriter in FileIO.read() (#138955)
Replace PyBytes_FromStringAndSize(NULL, size) and _PyBytes_Resize() with the new public PyBytesWriter API.
1 parent f62b495 commit e814e6b

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

Modules/_io/fileio.c

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -862,10 +862,6 @@ static PyObject *
862862
_io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
863863
/*[clinic end generated code: output=bbd749c7c224143e input=752d1ad3db8564a5]*/
864864
{
865-
char *ptr;
866-
Py_ssize_t n;
867-
PyObject *bytes;
868-
869865
if (self->fd < 0)
870866
return err_closed();
871867
if (!self->readable) {
@@ -880,31 +876,25 @@ _io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
880876
size = _PY_READ_MAX;
881877
}
882878

883-
bytes = PyBytes_FromStringAndSize(NULL, size);
884-
if (bytes == NULL)
879+
PyBytesWriter *writer = PyBytesWriter_Create(size);
880+
if (writer == NULL) {
885881
return NULL;
886-
ptr = PyBytes_AS_STRING(bytes);
882+
}
883+
char *ptr = PyBytesWriter_GetData(writer);
887884

888-
n = _Py_read(self->fd, ptr, size);
885+
Py_ssize_t n = _Py_read(self->fd, ptr, size);
889886
if (n == -1) {
890-
/* copy errno because Py_DECREF() can indirectly modify it */
887+
// copy errno because PyBytesWriter_Discard() can indirectly modify it
891888
int err = errno;
892-
Py_DECREF(bytes);
889+
PyBytesWriter_Discard(writer);
893890
if (err == EAGAIN) {
894891
PyErr_Clear();
895892
Py_RETURN_NONE;
896893
}
897894
return NULL;
898895
}
899896

900-
if (n != size) {
901-
if (_PyBytes_Resize(&bytes, n) < 0) {
902-
Py_CLEAR(bytes);
903-
return NULL;
904-
}
905-
}
906-
907-
return (PyObject *) bytes;
897+
return PyBytesWriter_FinishWithSize(writer, n);
908898
}
909899

910900
/*[clinic input]

0 commit comments

Comments
 (0)