[pypy-svn] r75824 - in pypy/branch/interplevel-array/pypy/module/array: . test

hakanardo at codespeak.net hakanardo at codespeak.net
Sun Jul 4 21:06:22 CEST 2010


Author: hakanardo
Date: Sun Jul  4 21:05:58 2010
New Revision: 75824

Added:
   pypy/branch/interplevel-array/pypy/module/array/interp_array_multiclass.py
   pypy/branch/interplevel-array/pypy/module/array/test/imtst.py
   pypy/branch/interplevel-array/pypy/module/array/test/sumtst.py
Modified:
   pypy/branch/interplevel-array/pypy/module/array/__init__.py
   pypy/branch/interplevel-array/pypy/module/array/interp_array.py
   pypy/branch/interplevel-array/pypy/module/array/test/test_array.py
Log:
Array constructor in place except for fromXXX initiators.

Modified: pypy/branch/interplevel-array/pypy/module/array/__init__.py
==============================================================================
--- pypy/branch/interplevel-array/pypy/module/array/__init__.py	(original)
+++ pypy/branch/interplevel-array/pypy/module/array/__init__.py	Sun Jul  4 21:05:58 2010
@@ -7,6 +7,7 @@
     }
     
     interpleveldefs = {
-        'array'    : 'interp_array.array',
+        'array'          : 'interp_array.array',
+        'sized_array'    : 'interp_array.sized_array',
     }
 

Modified: pypy/branch/interplevel-array/pypy/module/array/interp_array.py
==============================================================================
--- pypy/branch/interplevel-array/pypy/module/array/interp_array.py	(original)
+++ pypy/branch/interplevel-array/pypy/module/array/interp_array.py	Sun Jul  4 21:05:58 2010
@@ -1,13 +1,14 @@
 from pypy.interpreter.baseobjspace import Wrappable
+from pypy.interpreter.error import OperationError
 from pypy.interpreter.typedef import TypeDef
 from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.interpreter.gateway import interp2app, ObjSpace
+from pypy.interpreter.gateway import interp2app, ObjSpace, W_Root
 from pypy.rlib.jit import dont_look_inside
 from pypy.rlib import rgc
 
 FloatArray=lltype.GcArray(lltype.Float)
 
-class W_Array(Wrappable):
+class W_SizedFloatArray(Wrappable):
     @dont_look_inside
     def __init__(self, space, size):
         self.space=space
@@ -30,15 +31,183 @@
         self.buffer[idx]=val
     descr_setitem.unwrap_spec = ['self', int, float]
 
-W_Array.typedef = TypeDef(
+W_SizedFloatArray.typedef = TypeDef(
+     'SizedFloatArray',
+     __getitem__ = interp2app(W_SizedFloatArray.descr_getitem),
+     __setitem__ = interp2app(W_SizedFloatArray.descr_setitem),
+)
+        
+def sized_array(space,size):
+    return W_SizedFloatArray(space, size)
+sized_array.unwrap_spec=(ObjSpace, int)
+
+types = {
+    'c': lltype.GcArray(lltype.Char),
+    'u': lltype.GcArray(lltype.UniChar),
+    'b': lltype.GcArray(rffi.SIGNEDCHAR),
+    'B': lltype.GcArray(rffi.UCHAR),
+    'h': lltype.GcArray(rffi.SHORT),
+    'H': lltype.GcArray(rffi.USHORT),
+    'i': lltype.GcArray(lltype.Signed),
+    'I': lltype.GcArray(lltype.Unsigned),
+    'l': lltype.GcArray(lltype.Signed),
+    'L': lltype.GcArray(lltype.Unsigned),
+    'f': lltype.GcArray(lltype.SingleFloat),
+    'd': lltype.GcArray(lltype.Float),
+    }
+## def array(space, typecode, w_initializer=None):
+##     if 
+##     self.len=0
+##     self.buffer=None
+##     if w_initializer is not None and not space.is_w(w_size, space.w_None):
+##         self.extend(w_initializer) #FIXME: use fromlist, fromstring, ...
+        
+##     return W_SizedFloatArray(space, size)
+
+class W_Array(Wrappable):
+    def __init__(self, space, typecode):
+        if len(typecode) != 1:
+            msg='array() argument 1 must be char, not str'
+            raise OperationError(space.w_TypeError,space.wrap(msg))
+        if typecode not in  'cbBuhHiIlLfd':
+            msg='bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)'
+            raise OperationError(space.w_ValueError,space.wrap(msg))
+        self.space=space
+        self.typecode=typecode
+        self.len=0
+        self.buffer=None
+
+    def item_w(self, w_item):
+        space=self.space
+        if self.typecode == 'c':
+            return self.space.str_w(w_item)
+        elif self.typecode == 'u':
+            return self.space.unicode_w(w_item)
+        
+        elif self.typecode == 'b':
+            item=self.space.int_w(w_item)
+            if item<-128:
+                msg='signed char is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>127:
+                msg='signed char is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(rffi.SIGNEDCHAR, item)
+        elif self.typecode == 'B':
+            item=self.space.int_w(w_item)
+            if item<0:
+                msg='unsigned byte integer is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>255:
+                msg='unsigned byte integer is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(rffi.UCHAR, item)
+
+        elif self.typecode == 'h':
+            item=self.space.int_w(w_item)
+            if item<-32768:
+                msg='signed short integer is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>32767:
+                msg='signed short integer is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(rffi.SHORT, item)
+        elif self.typecode == 'H':
+            item=self.space.int_w(w_item)
+            if item<0:
+                msg='unsigned short integer is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>65535:
+                msg='unsigned short integer is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(rffi.USHORT, item)
+
+        elif self.typecode in ('i', 'l'):
+            item=self.space.int_w(w_item)
+            if item<-2147483648:
+                msg='signed integer is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>2147483647:
+                msg='signed integer is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(lltype.Signed, item)
+        elif self.typecode in ('I', 'L'):
+            item=self.space.int_w(w_item)
+            if item<0:
+                msg='unsigned integer is less than minimum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            elif item>4294967295:
+                msg='unsigned integer is greater than maximum'
+                raise OperationError(space.w_OverflowError, space.wrap(msg))
+            return rffi.cast(lltype.Unsigned, item)
+
+        elif self.typecode == 'f':
+            item=self.space.float_w(w_item)
+            return rffi.cast(lltype.SingleFloat, item)
+        elif self.typecode == 'd':
+            return self.space.float_w(w_item)
+
+    def setlen(self, size):
+        new_buffer=lltype.malloc(types[self.typecode], size, zero=True)
+        for i in range(self.len):
+            new_buffer[i]=self.buffer[i]
+        self.buffer=new_buffer
+        self.len=size
+
+    def descr_append(self,w_x):
+        x=self.item_w(w_x)
+        self.setlen(self.len+1)
+        self.buffer[self.len-1]=x
+    descr_append.unwrap_spec = ['self', W_Root]
+
+    def descr_extend(self, w_initializer):
+        space = self.space
+        w_iterator = space.iter(w_initializer)
+        while True:
+            try:
+                w_item = space.next(w_iterator)
+            except OperationError, e:
+                if not e.match(space, space.w_StopIteration):
+                    raise
+                break
+            self.descr_append(w_item)
+    descr_extend.unwrap_spec = ['self', W_Root]
+        
+
+    def descr_getitem(self, idx):
+        item = self.buffer[idx]
+        if self.typecode in ('b', 'B', 'h', 'H', 'i', 'l'):
+            item=rffi.cast(lltype.Signed, item)
+        if self.typecode == 'f':
+            item=float(item)
+        return self.space.wrap(item)
+    descr_getitem.unwrap_spec = ['self', int]
+
+    def descr_setitem(self, idx, w_item):
+        item=self.item_w(w_item)
+        self.buffer[idx]=item
+    descr_setitem.unwrap_spec = ['self', int, W_Root]
+    
+    def descr_len(self):
+        return self.space.wrap(self.len)
+    descr_len.unwrap_spec = ['self']
+
+W_Array.typedef=TypeDef(
     'Array',
+    append      = interp2app(W_Array.descr_append),
+    extend      = interp2app(W_Array.descr_extend),
+    __len__     = interp2app(W_Array.descr_len),
     __getitem__ = interp2app(W_Array.descr_getitem),
     __setitem__ = interp2app(W_Array.descr_setitem),
 )
-        
-        
 
+def array(space, typecode, w_initializer=None):
+    a=W_Array(space, typecode)
+    if w_initializer is not None:
+        if not space.is_w(w_initializer, space.w_None):
+            a.descr_extend(w_initializer) #FIXME: use fromlist, fromstring, ...
 
-def array(space,size):
-    return W_Array(space, size)
-array.unwrap_spec=(ObjSpace, int)
+    return a
+    
+array.unwrap_spec=(ObjSpace, str, W_Root)
+    

Added: pypy/branch/interplevel-array/pypy/module/array/interp_array_multiclass.py
==============================================================================
--- (empty file)
+++ pypy/branch/interplevel-array/pypy/module/array/interp_array_multiclass.py	Sun Jul  4 21:05:58 2010
@@ -0,0 +1,175 @@
+from pypy.interpreter.baseobjspace import Wrappable
+from pypy.interpreter.error import OperationError
+from pypy.interpreter.typedef import TypeDef
+from pypy.rpython.lltypesystem import lltype, rffi
+from pypy.interpreter.gateway import interp2app, ObjSpace, W_Root
+from pypy.rlib.jit import dont_look_inside
+from pypy.rlib import rgc
+
+FloatArray=lltype.GcArray(lltype.Float)
+
+class W_SizedFloatArray(Wrappable):
+    @dont_look_inside
+    def __init__(self, space, size):
+        self.space=space
+        self.size=size
+        print "malloc"
+        #self.buffer = lltype.malloc(rffi.DOUBLEP.TO, size, flavor='raw', zero=True)
+        #self.buffer = rgc.malloc_nonmovable(lltype.GcArray(lltype.Float), size)
+        self.buffer = lltype.malloc(FloatArray, size, zero=True)
+        print "buf: ", self.buffer
+
+    def __del__(self):
+        print "free"
+        #lltype.free(self.buffer, flavor='raw')
+
+    def descr_getitem(self, idx):
+        return self.space.wrap(self.buffer[idx])
+    descr_getitem.unwrap_spec = ['self', int]
+    
+    def descr_setitem(self, idx, val):
+        self.buffer[idx]=val
+    descr_setitem.unwrap_spec = ['self', int, float]
+
+W_SizedFloatArray.typedef = TypeDef(
+     'SizedFloatArray',
+     __getitem__ = interp2app(W_SizedFloatArray.descr_getitem),
+     __setitem__ = interp2app(W_SizedFloatArray.descr_setitem),
+)
+        
+def sized_array(space,size):
+    return W_SizedFloatArray(space, size)
+sized_array.unwrap_spec=(ObjSpace, int)
+
+types = {
+    'c': lltype.GcArray(lltype.Char),
+    'u': lltype.GcArray(lltype.UniChar),
+    'f': lltype.GcArray(lltype.SingleFloat),
+    'd': lltype.GcArray(lltype.Float),
+    }
+## def array(space, typecode, w_initializer=None):
+##     if 
+##     self.len=0
+##     self.buffer=None
+##     if w_initializer is not None and not space.is_w(w_size, space.w_None):
+##         self.extend(w_initializer) #FIXME: use fromlist, fromstring, ...
+        
+##     return W_SizedFloatArray(space, size)
+
+class W_Array(Wrappable):
+    def __init__(self, space, typecode):
+        self.space=space
+        self.typecode=typecode
+        self.len=0
+        self.buffer=None
+
+    def item_w(self, w_item):
+        if self.typecode == 'c':
+            return self.space.str_w(w_item)
+        elif self.typecode == 'u':
+            self.space.unicode_w(w_item)
+        elif self.typecode in ('b', 'B', 'h', 'H', 'i', 'l'):
+            self.space.int_w(w_item)
+        elif self.typecode in ('I', 'L'):
+            self.space.long_w(w_item)
+        elif self.typecode in ('f', 'd'):
+            self.space.float_w(w_item)
+
+
+    def setlen(self, size):
+        new_buffer=lltype.malloc(types[self.typecode], size, zero=True)
+        for i in range(self.len):
+            new_buffer[i]=self.buffer[i]
+        self.buffer=new_buffer
+        self.len=size
+
+    def descr_extend(self, w_initializer):
+        space = self.space
+        w_iterator = space.iter(w_initializer)
+        while True:
+            try:
+                w_item = space.next(w_iterator)
+            except OperationError, e:
+                if not e.match(space, space.w_StopIteration):
+                    raise
+                break
+            print w_item
+            self.descr_append(space.str_w(w_item))
+    descr_extend.unwrap_spec = ['self', W_Root]
+        
+
+    def descr_getitem(self, idx):
+        return self.space.wrap(self.buffer[idx])
+    descr_getitem.unwrap_spec = ['self', int]
+
+class W_CharArray(W_Array):
+    def descr_append(self,x):
+        print x
+        self.setlen(self.len+1)
+        self.buffer[self.len-1]=x
+    descr_append.unwrap_spec = ['self', str]
+
+    def descr_setitem(self, idx, val):
+        self.buffer[idx]=val
+    descr_setitem.unwrap_spec = ['self', int, float]
+
+    
+class W_UnicodeArray(W_Array):
+    def descr_append(self, x):
+        self.setlen(self.len+1)
+        self.buffer[self.len-1]=x
+    descr_append.unwrap_spec = ['self', unicode]
+
+class W_IntArray(W_Array):
+    def descr_append():
+        pass
+    descr_append.unwrap_spec = ['self', int]
+
+class W_LongArray(W_Array):
+    def descr_append():
+        pass
+    descr_append.unwrap_spec = ['self', long]
+
+class W_FloatArray(W_Array):
+    def descr_append():
+        pass
+    descr_append.unwrap_spec = ['self', float]
+
+def mktypedef(name, cls):
+    methods={
+        'append': interp2app(cls.descr_append),
+        'extend': interp2app(cls.descr_extend),
+        '__getitem__': interp2app(cls.descr_getitem),
+        }
+    cls.typedef = TypeDef(name, **methods)
+
+mktypedef('CharArray', W_CharArray)
+mktypedef('UnicodeArray', W_UnicodeArray)
+    
+
+def array(space, typecode, w_initializer=None):
+    if len(typecode) != 1:
+        msg='array() argument 1 must be char, not str'
+        raise OperationError(space.w_TypeError,space.wrap(msg))
+    if typecode == 'c':
+        a=W_CharArray(space, typecode)
+    elif typecode == 'u':
+        a=W_UnicodeArray(space, typecode)
+    elif typecode in ('b', 'B', 'h', 'H', 'i', 'l'):
+        a=W_IntArray(space, typecode)
+    elif typecode in ('I', 'L'):
+        a=W_LongArray(space, typecode)
+    elif typecode in ('f', 'd'):
+        a=W_FloatArray(space, typecode)
+    else:
+        msg='bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)'
+        raise OperationError(space.w_ValueError,space.wrap(msg))
+
+    if w_initializer is not None:
+        if not space.is_w(w_initializer, space.w_None):
+            a.descr_extend(w_initializer) #FIXME: use fromlist, fromstring, ...
+
+    return a
+    
+array.unwrap_spec=(ObjSpace, str, W_Root)
+    

Added: pypy/branch/interplevel-array/pypy/module/array/test/imtst.py
==============================================================================
--- (empty file)
+++ pypy/branch/interplevel-array/pypy/module/array/test/imtst.py	Sun Jul  4 21:05:58 2010
@@ -0,0 +1,41 @@
+def f():
+    a=(1,2,3)
+    s=0
+    while s<1000:
+        s+=a[0]
+        
+def g():
+    s=0
+    while s<1000:
+        s+=1
+    return s
+        
+
+def h():
+    s=0
+    i=0
+    a=7
+    while i<100000:
+        s+=i
+        i+=1
+    return s
+
+def h2():
+    s=0
+    i=0
+    a=(1,7,42)
+    while i<100000:
+        s+=a[1]
+        i+=1
+    return s
+
+def ff():
+    s=0
+    i=0
+    while i<100000:
+        s+=i
+        i+=1
+        if i>50000:
+            i=float(i)
+
+print ff()

Added: pypy/branch/interplevel-array/pypy/module/array/test/sumtst.py
==============================================================================
--- (empty file)
+++ pypy/branch/interplevel-array/pypy/module/array/test/sumtst.py	Sun Jul  4 21:05:58 2010
@@ -0,0 +1,15 @@
+#!/usr/bin/python
+from array import array
+
+img=array(640*480);
+def f():
+    l=0
+    i=0;
+    while i<640*480:
+        l+=img[i]
+        i+=1
+    return l
+
+
+#for l in range(500): f()
+print f()

Modified: pypy/branch/interplevel-array/pypy/module/array/test/test_array.py
==============================================================================
--- pypy/branch/interplevel-array/pypy/module/array/test/test_array.py	(original)
+++ pypy/branch/interplevel-array/pypy/module/array/test/test_array.py	Sun Jul  4 21:05:58 2010
@@ -1,18 +1,101 @@
 from pypy.conftest import gettestobjspace
 
-class AppTestcArray:
+class AppTestSizedArray:
     def setup_class(cls):
         cls.space = gettestobjspace(usemodules=('array',))
-        cls.w_array = cls.space.appexec([], """():
+        cls.w_sized_array = cls.space.appexec([], """():
             import array
-            return array.array
+            return array.sized_array
         """)
 
     def test_simple(self):
-        a=self.array(10)
+        a=self.sized_array(10)
         a[5]=7.42
         assert a[5]==7.42
 
+class AppTestArray:
+    def setup_class(cls):
+        cls.space = gettestobjspace(usemodules=('array',))
+        cls.w_array = cls.space.appexec([], """():
+            import array
+            return array.array
+        """)
+
+    def test_ctor(self):
+        raises(TypeError, self.array, 'hi')
+        raises(TypeError, self.array, 1)
+        raises(ValueError, self.array, 'q')
+
+        a=self.array('c')
+        raises(TypeError, a.append, 7)
+        a.append('h')
+        assert a[0] == 'h'
+        assert type(a[0]) is str
+        assert len(a) == 1
+
+        a=self.array('u')
+        raises(TypeError, a.append, 7)
+        a.append(unicode('h'))
+        assert a[0] == unicode('h')
+        assert type(a[0]) is unicode
+        assert len(a) == 1
+
+        a=self.array('c', ('a', 'b', 'c'))
+        assert a[0]=='a'
+        assert a[1]=='b'
+        assert a[2]=='c'
+        assert len(a) == 3
+
+    def test_value_range(self):
+        values=(-129, 128, -128, 127, 0, 255, -1, 256,
+                -32768, 32767, -32769, 32768, 65535, 65536,
+                -2147483647, -2147483648, 2147483647, 4294967295, 4294967296,
+                )
+        for tc,ok,pt in (('b',(  -128,    34,   127),  int),
+                         ('B',(     0,    23,   255),  int),
+                         ('h',(-32768, 30535, 32767),  int),
+                         ('H',(     0, 56783, 65535),  int),
+                         ('i',(-32768, 30535, 32767),  int),
+                         ('I',(     0, 56783, 65535), long),
+                         ('l',(-2**32/2, 34, 2**32/2-1),  int),
+                         ('L',(0, 3523532, 2**32-1), long),
+                         ):
+            a=self.array(tc, ok)
+            assert len(a) == len(ok)
+            for v in ok:
+                a.append(v)
+            for i,v in enumerate(ok*2):
+                assert a[i]==v
+                assert type(a[i]) is pt
+            for v in ok:
+                a[1]=v
+                assert a[0]==ok[0]
+                assert a[1]==v
+                assert a[2]==ok[2]
+            assert len(a) == 2*len(ok)
+            for v in values:
+                try:
+                    a[1]=v
+                    assert a[0]==ok[0]
+                    assert a[1]==v
+                    assert a[2]==ok[2]
+                except OverflowError:
+                    pass
+
+    def test_float(self):
+        values=[0, 1, 2.5, -4.25]
+        for tc in 'fd':
+            a=self.array(tc, values)
+            assert len(a)==len(values)
+            for i,v in enumerate(values):
+                assert a[i]==v
+                assert type(a[i]) is float
+            a[1]=10.125
+            assert a[0]==0
+            assert a[1]==10.125
+            assert a[2]==2.5
+            assert len(a)==len(values)
+
 
 ## space.sys.get('modules')
 



More information about the Pypy-commit mailing list