]> granicus.if.org Git - python/commitdiff
Accellerate binary readline() a bit.
authorGuido van Rossum <guido@python.org>
Thu, 7 Jun 2007 23:45:37 +0000 (23:45 +0000)
committerGuido van Rossum <guido@python.org>
Thu, 7 Jun 2007 23:45:37 +0000 (23:45 +0000)
Lib/io.py
Lib/test/test_io.py

index f1be881946bd24bfd36bad9ad560deb793c27e48..4d46b477a55b34c8d22fde0f0dda6b7aa4ac2f0d 100644 (file)
--- a/Lib/io.py
+++ b/Lib/io.py
@@ -298,17 +298,23 @@ class IOBase:
 
     ### Readline ###
 
-    def readline(self, sizehint: int = -1) -> bytes:
-        """For backwards compatibility, a (slow) readline()."""
-        if sizehint is None:
-            sizehint = -1
-        res = b""
-        while sizehint < 0 or len(res) < sizehint:
-            b = self.read(1)
+    def readline(self, limit: int = -1) -> bytes:
+        """For backwards compatibility, a (slowish) readline()."""
+        if limit is None:
+            limit = -1
+        res = bytes()
+        while limit < 0 or len(res) < limit:
+            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:
                 break
             res += b
-            if b == b"\n":
+            if res.endswith(b"\n"):
                 break
         return res
 
index c98d61fbd48d79a199f34a561244eea1d4ad5ae1..c5556231e82cea4fc3e5b1b38f48404622ce8174 100644 (file)
@@ -168,6 +168,18 @@ class IOTest(unittest.TestCase):
         self.read_ops(f, True)
         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):
         f = io.BytesIO()
         self.write_ops(f)