Skip to content
Prev Previous commit
Next Next commit
Simplify with gotos
  • Loading branch information
cmaloney committed Nov 13, 2025
commit 63ceed7fae8257af9e5946663537180227c94c79
19 changes: 9 additions & 10 deletions Modules/_io/iobase.c
Original file line number Diff line number Diff line change
Expand Up @@ -928,41 +928,40 @@ _io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
}

b = PyByteArray_FromStringAndSize(NULL, n);
if (b == NULL)
if (b == NULL) {
return NULL;
}

res = PyObject_CallMethodObjArgs(self, &_Py_ID(readinto), b, NULL);
if (res == NULL || res == Py_None) {
Py_DECREF(b);
return res;
goto cleanup;
}

Py_ssize_t bytes_filled = PyNumber_AsSsize_t(res, PyExc_ValueError);
Py_DECREF(res);
Py_CLEAR(res);
if (bytes_filled == -1 && PyErr_Occurred()) {
Py_DECREF(b);
return NULL;
goto cleanup;
}
if (bytes_filled < 0 || bytes_filled > n) {
Py_DECREF(b);
PyErr_Format(PyExc_ValueError,
"readinto returned %zd outside buffer size %zd",
bytes_filled, n);
return NULL;
goto cleanup;
}

res = PyObject_CallMethod(b, "resize", "i", bytes_filled);
if (res != Py_None) {
Py_DECREF(b);
if (res != NULL) {
PyErr_Format(PyExc_ValueError,
"resize returned unexpected value %R",
res);
Py_CLEAR(res);
}
return res;
goto cleanup;
}
res = PyObject_CallMethod(b, "take_bytes", NULL);

@cmaloney cmaloney Nov 13, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vstinner : Not sure how common this "resize/discard then take_bytes" is going to be; might make sense to change to take_bytes(n=None, /, *, discard=False)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for now planning to keep that in back pocket until need many ways (ba.resize(n) or del ba[:n] gives the same capability)

Comment thread
cmaloney marked this conversation as resolved.
Outdated

cleanup:
Py_DECREF(b);
return res;
}
Expand Down
Loading