Commit 6653a7b5 authored by Guido van Rossum's avatar Guido van Rossum

Accellerate binary readline() a bit.

parent 41d7934a
...@@ -298,17 +298,23 @@ class IOBase: ...@@ -298,17 +298,23 @@ class IOBase:
### Readline ### ### Readline ###
def readline(self, sizehint: int = -1) -> bytes: def readline(self, limit: int = -1) -> bytes:
"""For backwards compatibility, a (slow) readline().""" """For backwards compatibility, a (slowish) readline()."""
if sizehint is None: if limit is None:
sizehint = -1 limit = -1
res = b"" res = bytes()
while sizehint < 0 or len(res) < sizehint: while limit < 0 or len(res) < limit:
b = self.read(1) readahead = self.peek(1, unsafe=True)
if not readahead:
break
n = (readahead.find(b"\n") + 1) or len(readahead)
if limit >= 0:
n = min(n, limit)
b = self.read(n)
if not b: if not b:
break break
res += b res += b
if b == b"\n": if res.endswith(b"\n"):
break break
return res return res
......
...@@ -168,6 +168,18 @@ class IOTest(unittest.TestCase): ...@@ -168,6 +168,18 @@ class IOTest(unittest.TestCase):
self.read_ops(f, True) self.read_ops(f, True)
f.close() f.close()
def test_readline(self):
f = io.open(test_support.TESTFN, "wb")
f.write(b"abc\ndef\nxyzzy\nfoo")
f.close()
f = io.open(test_support.TESTFN, "rb")
self.assertEqual(f.readline(), b"abc\n")
self.assertEqual(f.readline(10), b"def\n")
self.assertEqual(f.readline(2), b"xy")
self.assertEqual(f.readline(4), b"zzy\n")
self.assertEqual(f.readline(), b"foo")
f.close()
def test_raw_bytes_io(self): def test_raw_bytes_io(self):
f = io.BytesIO() f = io.BytesIO()
self.write_ops(f) self.write_ops(f)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment