Skip to content

Commit 148d2f7

Browse files
committed
gh-129205: Add os.readinto API
Add a new OS api which will read data directly into a caller provided writeable buffer protocol object.
1 parent 298dda5 commit 148d2f7

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

Modules/clinic/posixmodule.c.h

Lines changed: 52 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Modules/posixmodule.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11433,6 +11433,29 @@ os_read_impl(PyObject *module, int fd, Py_ssize_t length)
1143311433
return buffer;
1143411434
}
1143511435

11436+
/*[clinic input]
11437+
os.readinto -> Py_ssize_t
11438+
fd: int
11439+
buffer: Py_buffer(accept={rwbuffer})
11440+
/
11441+
11442+
Read into a :ref:`buffer protocol <bufferobjects>` object from a file descriptor.
11443+
11444+
The buffer should be mutable and accept bytes. On success, returns the number of
11445+
bytes read. Less bytes may be read than the size of the buffer. Will retry the
11446+
underlying system call when interrupted by a signal. For other errors, the
11447+
system call will not be retried.
11448+
[clinic start generated code]*/
11449+
11450+
static Py_ssize_t
11451+
os_readinto_impl(PyObject *module, int fd, Py_buffer *buffer)
11452+
/*[clinic end generated code: output=8091a3513c683a80 input=810c820f4d9b1c6b]*/
11453+
{
11454+
// Cap to max read size to prevent overflow in cast to size_t for _Py_read.
11455+
size_t length = Py_MIN(buffer->len, _PY_READ_MAX);
11456+
return _Py_read(fd, buffer->buf, length);
11457+
}
11458+
1143611459
#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
1143711460
|| defined(__APPLE__))) \
1143811461
|| defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
@@ -16973,6 +16996,7 @@ static PyMethodDef posix_methods[] = {
1697316996
OS_LOCKF_METHODDEF
1697416997
OS_LSEEK_METHODDEF
1697516998
OS_READ_METHODDEF
16999+
OS_READINTO_METHODDEF
1697617000
OS_READV_METHODDEF
1697717001
OS_PREAD_METHODDEF
1697817002
OS_PREADV_METHODDEF

0 commit comments

Comments
 (0)