[pypy-svn] pypy bytearray: (mfoord) implement bytearray.insert

mfoord commits-noreply at bitbucket.org
Tue Jan 18 15:52:49 CET 2011


Author: Michael Foord <michael at voidspace.org.uk>
Branch: bytearray
Changeset: r40865:4421112ed497
Date: 2011-01-18 15:25 +0100
http://bitbucket.org/pypy/pypy/changeset/4421112ed497/

Log:	(mfoord) implement bytearray.insert

diff --git a/pypy/objspace/std/bytearrayobject.py b/pypy/objspace/std/bytearrayobject.py
--- a/pypy/objspace/std/bytearrayobject.py
+++ b/pypy/objspace/std/bytearrayobject.py
@@ -15,7 +15,7 @@
 from pypy.objspace.std import slicetype
 from pypy.interpreter import gateway
 from pypy.interpreter.buffer import RWBuffer
-from pypy.objspace.std.bytearraytype import makebytearraydata_w
+from pypy.objspace.std.bytearraytype import makebytearraydata_w, getbytevalue
 from pypy.tool.sourcetools import func_with_new_name
 
 
@@ -261,6 +261,12 @@
         newdata.extend([c for c in space.str_w(list_w[i])])
     return W_BytearrayObject(newdata)
 
+def bytearray_insert__Bytearray_Int_ANY(space, w_bytearray, w_idx, w_other):
+    index = w_idx.intval
+    val = getbytevalue(space, w_other)
+    w_bytearray.data.insert(index, val)
+    return space.w_None
+
 # These methods could just delegate to the string implementation,
 # but they have to return a bytearray.
 def str_replace__Bytearray_ANY_ANY_ANY(space, w_bytearray, w_str1, w_str2, w_max):

diff --git a/pypy/objspace/std/test/test_bytes.py b/pypy/objspace/std/test/test_bytes.py
--- a/pypy/objspace/std/test/test_bytes.py
+++ b/pypy/objspace/std/test/test_bytes.py
@@ -172,6 +172,26 @@
         b.append(ord('e'))
         assert b == 'abcde'
 
+    def test_insert(self):
+        b = bytearray('abc')
+        b.insert(0, 'd')
+        assert b == bytearray('dabc')
+
+        b.insert(-1, ord('e'))
+        assert b == bytearray('dabec')
+
+        b.insert(6, 'f')
+        assert b == bytearray('dabecf')
+
+        b.insert(1, 'g')
+        assert b == bytearray('dgabecf')
+
+        b.insert(-12, 'h')
+        assert b == bytearray('hdgabecf')
+
+        raises(ValueError, b.insert, 1, 'go')
+        raises(TypeError, b.insert, 'g', 'o')
+
     def test_delitem(self):
         b = bytearray('abc')
         del b[1]

diff --git a/pypy/objspace/std/bytearraytype.py b/pypy/objspace/std/bytearraytype.py
--- a/pypy/objspace/std/bytearraytype.py
+++ b/pypy/objspace/std/bytearraytype.py
@@ -19,6 +19,11 @@
     list_append, list_extend)
 
 
+bytearray_insert  = SMM('insert',3,
+                    doc="B.insert(index, int) -> None\n\n"
+                    "Insert a single item into the bytearray before "
+                    "the given index.")
+
 def getbytevalue(space, w_value):
     if space.isinstance_w(w_value, space.w_str):
         string = space.str_w(w_value)


More information about the Pypy-commit mailing list