[pypy-svn] r39987 - pypy/dist/pypy/module/_file

arigo at codespeak.net arigo at codespeak.net
Tue Mar 6 16:46:47 CET 2007


Author: arigo
Date: Tue Mar  6 16:46:46 2007
New Revision: 39987

Modified:
   pypy/dist/pypy/module/_file/app_file.py
Log:
Fix the last "XXX slow" of app_file.


Modified: pypy/dist/pypy/module/_file/app_file.py
==============================================================================
--- pypy/dist/pypy/module/_file/app_file.py	(original)
+++ pypy/dist/pypy/module/_file/app_file.py	Tue Mar  6 16:46:46 2007
@@ -115,14 +115,23 @@
         if size < 0:
             return self.stream.readline()
         else:
-            # XXX slow
-            chars = []
-            for i in xrange(size):
-                char = self.stream.read(1)
-                chars.append(char)
-                if char == '' or char == '\n':
+            # very inefficient unless there is a peek()
+            result = []
+            while size > 0:
+                # "peeks" on the underlying stream to see how many characters
+                # we can safely read without reading past an end-of-line
+                peeked = self.stream.peek()
+                pn = peeked.find("\n", 0, size)
+                if pn < 0:
+                    pn = min(size-1, len(peeked))
+                c = self.stream.read(pn + 1)
+                if not c:
+                    break
+                result.append(c)
+                if c.endswith('\n'):
                     break
-            return ''.join(chars)
+                size -= len(c)
+            return ''.join(result)
 
     def readlines(self, size=-1):
         """readlines([size]) -> list of strings, each a line from the file.



More information about the Pypy-commit mailing list