gh-129005: Avoid copy in _pyio.FileIO.readinto() (#129324)

`os.read()` allocated and filled a buffer by calling `read(2)`, than that
data was copied into the user provied buffer. Read directly into the
caller's buffer instead by using `os.readinto()`.

`os.readinto()` uses `PyObject_GetBuffer()` to make sure the passed
in buffer is writeable and bytes-like, drop the manual check.
This commit is contained in:
Cody Maloney 2025-01-28 03:40:44 -08:00 committed by GitHub
parent 4d0d24f6e3
commit 180ee43bde
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 8 additions and 6 deletions

View file

@ -1692,13 +1692,14 @@ class FileIO(RawIOBase):
return bytes(result)
def readinto(self, b):
def readinto(self, buffer):
"""Same as RawIOBase.readinto()."""
m = memoryview(b).cast('B')
data = self.read(len(m))
n = len(data)
m[:n] = data
return n
self._checkClosed()
self._checkReadable()
try:
return os.readinto(self._fd, buffer)
except BlockingIOError:
return None
def write(self, b):
"""Write bytes b to file, return number written.

View file

@ -0,0 +1 @@
Optimize ``_pyio.FileIO.readinto`` by avoiding unnecessary objects and copies using :func:`os.readinto`.