Author: Alex Gaynor <[email protected]>
Branch: 
Changeset: r64692:7587887ac0e2
Date: 2013-05-31 13:19 -0700
http://bitbucket.org/pypy/pypy/changeset/7587887ac0e2/

Log:    Optimize truncating an rStringIO (used in io.BytesIO) to empty.

diff --git a/rpython/rlib/rStringIO.py b/rpython/rlib/rStringIO.py
--- a/rpython/rlib/rStringIO.py
+++ b/rpython/rlib/rStringIO.py
@@ -101,7 +101,11 @@
         self.__pos = endp
 
     def seek(self, position, mode=0):
-        if mode == 1:
+        if mode == 0:
+            if position == self.getsize():
+                self.__pos = AT_END
+                return
+        elif mode == 1:
             if self.__pos == AT_END:
                 self.__pos = self.getsize()
             position += self.__pos
@@ -168,15 +172,19 @@
         Python 2.7's cStringIO module: it will not enlarge the file,
         and it will always seek to the (new) end of the file."""
         assert size >= 0
-        if self.__bigbuffer is None or size > len(self.__bigbuffer):
-            self.__copy_into_bigbuffer()
+        if size == 0:
+            self.__bigbuffer = None
+            self.__strings = None
         else:
-            # we can drop all extra strings
-            if self.__strings is not None:
-                self.__strings = None
-        if size < len(self.__bigbuffer):
-            del self.__bigbuffer[size:]
-        if len(self.__bigbuffer) == 0:
-            self.__bigbuffer = None
+            if self.__bigbuffer is None or size > len(self.__bigbuffer):
+                self.__copy_into_bigbuffer()
+            else:
+                # we can drop all extra strings
+                if self.__strings is not None:
+                    self.__strings = None
+            if size < len(self.__bigbuffer):
+                del self.__bigbuffer[size:]
+            if len(self.__bigbuffer) == 0:
+                self.__bigbuffer = None
         # it always has the effect of seeking at the new end
         self.__pos = AT_END
diff --git a/rpython/rlib/test/test_rStringIO.py 
b/rpython/rlib/test/test_rStringIO.py
--- a/rpython/rlib/test/test_rStringIO.py
+++ b/rpython/rlib/test/test_rStringIO.py
@@ -117,6 +117,13 @@
     assert f.getvalue() == '\x00' * 3
     assert f.tell() == 3
 
+def test_truncate_end():
+    f = RStringIO()
+    f.write("abc")
+    f.seek(0)
+    f.truncate(0)
+    assert f.getvalue() == ""
+
 def test_bug():
     f = RStringIO()
     f.write('0')
_______________________________________________
pypy-commit mailing list
[email protected]
http://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to