mirror of
https://github.com/python/cpython.git
synced 2025-12-08 06:10:17 +00:00
gh-129813, PEP 782: Use PyBytesWriter in FileIO.read() (#138955)
Replace PyBytes_FromStringAndSize(NULL, size) and _PyBytes_Resize() with the new public PyBytesWriter API.
This commit is contained in:
parent
f62b495f79
commit
e814e6b38b
1 changed files with 8 additions and 18 deletions
|
|
@ -862,10 +862,6 @@ static PyObject *
|
||||||
_io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
|
_io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
|
||||||
/*[clinic end generated code: output=bbd749c7c224143e input=752d1ad3db8564a5]*/
|
/*[clinic end generated code: output=bbd749c7c224143e input=752d1ad3db8564a5]*/
|
||||||
{
|
{
|
||||||
char *ptr;
|
|
||||||
Py_ssize_t n;
|
|
||||||
PyObject *bytes;
|
|
||||||
|
|
||||||
if (self->fd < 0)
|
if (self->fd < 0)
|
||||||
return err_closed();
|
return err_closed();
|
||||||
if (!self->readable) {
|
if (!self->readable) {
|
||||||
|
|
@ -880,16 +876,17 @@ _io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
|
||||||
size = _PY_READ_MAX;
|
size = _PY_READ_MAX;
|
||||||
}
|
}
|
||||||
|
|
||||||
bytes = PyBytes_FromStringAndSize(NULL, size);
|
PyBytesWriter *writer = PyBytesWriter_Create(size);
|
||||||
if (bytes == NULL)
|
if (writer == NULL) {
|
||||||
return NULL;
|
return NULL;
|
||||||
ptr = PyBytes_AS_STRING(bytes);
|
}
|
||||||
|
char *ptr = PyBytesWriter_GetData(writer);
|
||||||
|
|
||||||
n = _Py_read(self->fd, ptr, size);
|
Py_ssize_t n = _Py_read(self->fd, ptr, size);
|
||||||
if (n == -1) {
|
if (n == -1) {
|
||||||
/* copy errno because Py_DECREF() can indirectly modify it */
|
// copy errno because PyBytesWriter_Discard() can indirectly modify it
|
||||||
int err = errno;
|
int err = errno;
|
||||||
Py_DECREF(bytes);
|
PyBytesWriter_Discard(writer);
|
||||||
if (err == EAGAIN) {
|
if (err == EAGAIN) {
|
||||||
PyErr_Clear();
|
PyErr_Clear();
|
||||||
Py_RETURN_NONE;
|
Py_RETURN_NONE;
|
||||||
|
|
@ -897,14 +894,7 @@ _io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (n != size) {
|
return PyBytesWriter_FinishWithSize(writer, n);
|
||||||
if (_PyBytes_Resize(&bytes, n) < 0) {
|
|
||||||
Py_CLEAR(bytes);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (PyObject *) bytes;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*[clinic input]
|
/*[clinic input]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue