[Python-3000-checkins] r55820 - in python/branches/py3k-struni/Lib: io.py test/test_io.py

guido.van.rossum python-3000-checkins at python.org
Fri Jun 8 01:45:43 CEST 2007


Author: guido.van.rossum
Date: Fri Jun  8 01:45:37 2007
New Revision: 55820

Modified:
   python/branches/py3k-struni/Lib/io.py
   python/branches/py3k-struni/Lib/test/test_io.py
Log:
Accellerate binary readline() a bit.


Modified: python/branches/py3k-struni/Lib/io.py
==============================================================================
--- python/branches/py3k-struni/Lib/io.py	(original)
+++ python/branches/py3k-struni/Lib/io.py	Fri Jun  8 01:45:37 2007
@@ -298,17 +298,23 @@
 
     ### 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
 

Modified: python/branches/py3k-struni/Lib/test/test_io.py
==============================================================================
--- python/branches/py3k-struni/Lib/test/test_io.py	(original)
+++ python/branches/py3k-struni/Lib/test/test_io.py	Fri Jun  8 01:45:37 2007
@@ -168,6 +168,18 @@
         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)


More information about the Python-3000-checkins mailing list