Commits

Manuel Jacob committed 8a53d0a Merge

hg merge default

Comments (0)

Files changed (59)

 .idea
 .project
 .pydevproject
+__pycache__
 
 syntax: regexp
 ^testresult$

lib_pypy/_ctypes/structure.py

                 or tp._type_ not in "iIhHbBlLqQ"):
                 #XXX: are those all types?
                 #     we just dont get the type name
-                #     in the interp levle thrown TypeError
+                #     in the interp level thrown TypeError
                 #     from rawffi if there are more
                 raise TypeError('bit fields not allowed for type ' + tp.__name__)
 

lib_pypy/cffi/backend_ctypes.py

         class CTypesStructOrUnion(CTypesBaseStructOrUnion):
             __slots__ = ['_blob']
             _ctype = struct_or_union
-            _reftypename = '%s %s &' % (kind, name)
+            _reftypename = '%s &' % (name,)
             _kind = kind
         #
         CTypesStructOrUnion._fix_class()
         #
         class CTypesEnum(CTypesInt):
             __slots__ = []
-            _reftypename = 'enum %s &' % name
+            _reftypename = '%s &' % name
 
             def _get_own_repr(self):
                 value = self._value

lib_pypy/cffi/model.py

         self.forcename = forcename
         self.build_c_name_with_marker()
 
+    def get_official_name(self):
+        assert self.c_name_with_marker.endswith('&')
+        return self.c_name_with_marker[:-1]
+
 
 class StructOrUnion(StructOrUnionOrEnum):
     fixedlayout = None
     def build_backend_type(self, ffi, finishlist):
         self.check_not_partial()
         finishlist.append(self)
-        return global_cache(self, ffi, 'new_struct_type', self.name, key=self)
+        
+        return global_cache(self, ffi, 'new_struct_type',
+                            self.get_official_name(), key=self)
 
 
 class UnionType(StructOrUnion):
 
     def build_backend_type(self, ffi, finishlist):
         finishlist.append(self)
-        return global_cache(self, ffi, 'new_union_type', self.name, key=self)
+        return global_cache(self, ffi, 'new_union_type',
+                            self.get_official_name(), key=self)
 
 
 class EnumType(StructOrUnionOrEnum):
     def build_backend_type(self, ffi, finishlist):
         self.check_not_partial()
         base_btype = self.build_baseinttype(ffi, finishlist)
-        return global_cache(self, ffi, 'new_enum_type', self.name,
+        return global_cache(self, ffi, 'new_enum_type',
+                            self.get_official_name(),
                             self.enumerators, self.enumvalues,
                             base_btype, key=self)
 

pypy/doc/whatsnew-head.rst

 Fix a segfault in argsort when sorting by chunks on multidim numpypy arrays (mikefc)
 
 .. branch: dtype-isnative
+.. branch: ndarray-round
+
+.. branch: faster-str-of-bigint
+Improve performance of str(long).

pypy/module/__pypy__/interp_dict.py

 
 @unwrap_spec(type=str)
 def newdict(space, type):
+    """ newdict(type)
+
+    Create a normal dict with a special implementation strategy.
+
+    type is a string and can be:
+
+    * "module" - equivalent to some_module.__dict__
+
+    * "instance" - equivalent to an instance dict with a not-changing-much
+                   set of keys
+
+    * "kwargs" - keyword args dict equivalent of what you get from **kwargs
+                 in a function, optimized for passing around
+
+    * "strdict" - string-key only dict. This one should be chosen automatically
+    """
     if type == 'module':
         return space.newdict(module=True)
     elif type == 'instance':
                               type)
 
 def dictstrategy(space, w_obj):
+    """ dictstrategy(dict)
+
+    show the underlaying strategy used by a dict object
+    """
     if not isinstance(w_obj, W_DictMultiObject):
         raise OperationError(space.w_TypeError,
                              space.wrap("expecting dict object"))

pypy/module/_cffi_backend/ctypeenum.py

     _mixin_ = True
 
     def __init__(self, space, name, size, align, enumerators, enumvalues):
-        name = "enum " + name
         self._super.__init__(self, space, size, name, len(name), align)
         self.enumerators2values = {}   # str -> int
         self.enumvalues2erators = {}   # int -> str

pypy/module/_cffi_backend/ctypeptr.py

         else:
             extra = " *"
         self.is_file = (ctitem.name == "struct _IO_FILE" or
-                        ctitem.name == "struct $FILE")
+                        ctitem.name == "FILE")
         self.is_void_ptr = isinstance(ctitem, ctypevoid.W_CTypeVoid)
         W_CTypePtrBase.__init__(self, space, size, extra, 2, ctitem)
 

pypy/module/_cffi_backend/ctypestruct.py

     custom_field_pos = False
 
     def __init__(self, space, name):
-        name = '%s %s' % (self.kind, name)
         W_CType.__init__(self, space, -1, name, len(name))
 
     def check_complete(self, w_errorcls=None):

pypy/module/_cffi_backend/test/_backend_test_c.py

 
 def test_new_struct_type():
     BStruct = new_struct_type("foo")
+    assert repr(BStruct) == "<ctype 'foo'>"
+    BStruct = new_struct_type("struct foo")
     assert repr(BStruct) == "<ctype 'struct foo'>"
     BPtr = new_pointer_type(BStruct)
     assert repr(BPtr) == "<ctype 'struct foo *'>"
     py.test.raises(ValueError, alignof, BStruct)
 
 def test_new_union_type():
-    BUnion = new_union_type("foo")
+    BUnion = new_union_type("union foo")
     assert repr(BUnion) == "<ctype 'union foo'>"
     BPtr = new_pointer_type(BUnion)
     assert repr(BPtr) == "<ctype 'union foo *'>"
     BLong = new_primitive_type("long")
     BChar = new_primitive_type("char")
     BShort = new_primitive_type("short")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     assert BStruct.kind == "struct"
     assert BStruct.cname == "struct foo"
     assert BStruct.fields is None
 def test_complete_union():
     BLong = new_primitive_type("long")
     BChar = new_primitive_type("char")
-    BUnion = new_union_type("foo")
+    BUnion = new_union_type("union foo")
     assert BUnion.kind == "union"
     assert BUnion.cname == "union foo"
     assert BUnion.fields is None
 
 def test_struct_instance():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     p = cast(BStructPtr, 0)
     py.test.raises(AttributeError, "p.a1")    # opaque
 def test_union_instance():
     BInt = new_primitive_type("int")
     BUInt = new_primitive_type("unsigned int")
-    BUnion = new_union_type("bar")
+    BUnion = new_union_type("union bar")
     complete_struct_or_union(BUnion, [('a1', BInt, -1), ('a2', BUInt, -1)])
     p = newp(new_pointer_type(BUnion), [-42])
     bigval = -42 + (1 << (8*size_of_int()))
 
 def test_struct_pointer():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BInt, -1),
                                        ('a2', BInt, -1)])
     BVoidP = new_pointer_type(new_void_type())
     BInt = new_primitive_type("int")
     BIntPtr = new_pointer_type(BInt)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BInt, -1),
                                        ('a2', BInt, -1),
 
 def test_array_in_struct():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BArrayInt5 = new_array_type(new_pointer_type(BInt), 5)
     complete_struct_or_union(BStruct, [('a1', BArrayInt5, -1)])
     s = newp(new_pointer_type(BStruct), [[20, 24, 27, 29, 30]])
     def offsetof(BType, fieldname):
         return typeoffsetof(BType, fieldname)[1]
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     py.test.raises(TypeError, offsetof, BInt, "abc")
     py.test.raises(TypeError, offsetof, BStruct, "abc")
     complete_struct_or_union(BStruct, [('abc', BInt, -1), ('def', BInt, -1)])
 def test_function_type_taking_struct():
     BChar = new_primitive_type("char")
     BShort = new_primitive_type("short")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BShort, -1)])
     BFunc = new_function_type((BStruct,), BShort, False)
 def test_call_function_7():
     BChar = new_primitive_type("char")
     BShort = new_primitive_type("short")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BShort, -1)])
 def test_call_function_20():
     BChar = new_primitive_type("char")
     BShort = new_primitive_type("short")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BShort, -1)])
 
 def test_call_function_21():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a', BInt, -1),
                                        ('b', BInt, -1),
                                        ('c', BInt, -1),
 def test_call_function_22():
     BInt = new_primitive_type("int")
     BArray10 = new_array_type(new_pointer_type(BInt), 10)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructP = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a', BArray10, -1)])
     BFunc22 = new_function_type((BStruct, BStruct), BStruct, False)
 def test_cannot_pass_struct_with_array_of_length_0():
     BInt = new_primitive_type("int")
     BArray0 = new_array_type(new_pointer_type(BInt), 0)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a', BArray0)])
     py.test.raises(NotImplementedError, new_function_type,
                    (BStruct,), BInt, False)
 def test_cannot_call_with_a_autocompleted_struct():
     BSChar = new_primitive_type("signed char")
     BDouble = new_primitive_type("double")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('c', BDouble, -1, 8),
                                        ('a', BSChar, -1, 2),
     BSChar = new_primitive_type("signed char")
     BInt = new_primitive_type("int")
     BDouble = new_primitive_type("double")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a', BSChar, -1),
                                        ('b', BDouble, -1)])
 
 def test_callback_returning_big_struct():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a', BInt, -1),
                                        ('b', BInt, -1),
 def test_enum_type():
     BUInt = new_primitive_type("unsigned int")
     BEnum = new_enum_type("foo", (), (), BUInt)
-    assert repr(BEnum) == "<ctype 'enum foo'>"
+    assert repr(BEnum) == "<ctype 'foo'>"
     assert BEnum.kind == "enum"
-    assert BEnum.cname == "enum foo"
+    assert BEnum.cname == "foo"
     assert BEnum.elements == {}
     #
     BInt = new_primitive_type("int")
-    BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
+    BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
     assert BEnum.kind == "enum"
+    assert BEnum.cname == "enum foo"
     assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
     # 'elements' is not the real dict, but merely a copy
     BEnum.elements[2] = '??'
     assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
     #
-    BEnum = new_enum_type("bar", ('ab', 'cd'), (5, 5), BUInt)
+    BEnum = new_enum_type("enum bar", ('ab', 'cd'), (5, 5), BUInt)
     assert BEnum.elements == {5: 'ab'}
     assert BEnum.relements == {'ab': 5, 'cd': 5}
 
 def test_cast_to_enum():
     BInt = new_primitive_type("int")
-    BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
+    BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
     assert sizeof(BEnum) == sizeof(BInt)
     e = cast(BEnum, 0)
     assert repr(e) == "<cdata 'enum foo' 0: def>"
     assert string(cast(BEnum, -242 + 2**128)) == '-242'
     #
     BUInt = new_primitive_type("unsigned int")
-    BEnum = new_enum_type("bar", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
+    BEnum = new_enum_type("enum bar", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
     e = cast(BEnum, -1)
     assert repr(e) == "<cdata 'enum bar' 4294967295>"     # unsigned int
     #
     BLong = new_primitive_type("long")
-    BEnum = new_enum_type("baz", (), (), BLong)
+    BEnum = new_enum_type("enum baz", (), (), BLong)
     assert sizeof(BEnum) == sizeof(BLong)
     e = cast(BEnum, -1)
     assert repr(e) == "<cdata 'enum baz' -1>"
 
 def test_enum_with_non_injective_mapping():
     BInt = new_primitive_type("int")
-    BEnum = new_enum_type("foo", ('ab', 'cd'), (7, 7), BInt)
+    BEnum = new_enum_type("enum foo", ('ab', 'cd'), (7, 7), BInt)
     e = cast(BEnum, 7)
     assert repr(e) == "<cdata 'enum foo' 7: ab>"
     assert string(e) == 'ab'
 
 def test_enum_in_struct():
     BInt = new_primitive_type("int")
-    BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
-    BStruct = new_struct_type("bar")
+    BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
+    BStruct = new_struct_type("struct bar")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BEnum, -1)])
     p = newp(BStructPtr, [-20])
 
 def test_struct_with_bitfields():
     BLong = new_primitive_type("long")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     LONGBITS = 8 * sizeof(BLong)
     complete_struct_or_union(BStruct, [('a1', BLong, 1),
                                        ('a2', BLong, 2),
 def test_bitfield_instance():
     BInt = new_primitive_type("int")
     BUnsignedInt = new_primitive_type("unsigned int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BInt, 1),
                                        ('a2', BUnsignedInt, 2),
                                        ('a3', BInt, 3)])
 
 def test_bitfield_instance_init():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BInt, 1)])
     p = newp(new_pointer_type(BStruct), [-1])
     assert p.a1 == -1
     p = newp(new_pointer_type(BStruct), {'a1': -1})
     assert p.a1 == -1
     #
-    BUnion = new_union_type("bar")
+    BUnion = new_union_type("union bar")
     complete_struct_or_union(BUnion, [('a1', BInt, 1)])
     p = newp(new_pointer_type(BUnion), [-1])
     assert p.a1 == -1
     py.test.raises(IndexError, newp, BArray, tuple(b'123456'))
     py.test.raises(IndexError, newp, BArray, list(b'123456'))
     py.test.raises(IndexError, newp, BArray, b'123456')
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [])
     py.test.raises(TypeError, newp, new_pointer_type(BStruct), b'')
     py.test.raises(ValueError, newp, new_pointer_type(BStruct), [b'1'])
     p = newp(new_pointer_type(BFloat), cast(BFloat, 12.25))
     assert p[0] == 12.25
     #
-    BStruct = new_struct_type("foo_s")
+    BStruct = new_struct_type("struct foo_s")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BInt, -1)])
     s1 = newp(BStructPtr, [42])
     s2 = newp(BStructPtr, s1[0])
     assert s2.a1 == 42
     #
-    BUnion = new_union_type("foo_u")
+    BUnion = new_union_type("union foo_u")
     BUnionPtr = new_pointer_type(BUnion)
     complete_struct_or_union(BUnion, [('a1', BInt, -1)])
     u1 = newp(BUnionPtr, [42])
     BChar = new_primitive_type("char")
     BCharP = new_pointer_type(BChar)
     BCharArray10 = new_array_type(BCharP, 10)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BCharArray10, -1)])
     p = newp(BStructPtr, None)
     new_function_type((), BFunc)    # works
     new_function_type((), new_primitive_type("int"))
     new_function_type((), new_pointer_type(BFunc))
-    BUnion = new_union_type("foo_u")
+    BUnion = new_union_type("union foo_u")
     complete_struct_or_union(BUnion, [])
     py.test.raises(NotImplementedError, new_function_type, (), BUnion)
     py.test.raises(TypeError, new_function_type, (), BArray)
     BFloat = new_primitive_type("float")
     BDouble = new_primitive_type("double")
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo_s")
+    BStruct = new_struct_type("struct foo_s")
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BShort, -1)])
     BFunc10 = new_function_type((BInt,), BStruct)
     assert s.a1 == bytechr(40)
     assert s.a2 == 40 * 40
     #
-    BStruct11 = new_struct_type("test11")
+    BStruct11 = new_struct_type("struct test11")
     complete_struct_or_union(BStruct11, [('a1', BInt, -1),
                                          ('a2', BInt, -1)])
     BFunc11 = new_function_type((BInt,), BStruct11)
     assert s.a1 == 40
     assert s.a2 == 40 * 40
     #
-    BStruct12 = new_struct_type("test12")
+    BStruct12 = new_struct_type("struct test12")
     complete_struct_or_union(BStruct12, [('a1', BDouble, -1),
                                          ])
     BFunc12 = new_function_type((BInt,), BStruct12)
     assert repr(s) == "<cdata 'struct test12' owning 8 bytes>"
     assert s.a1 == 40.0
     #
-    BStruct13 = new_struct_type("test13")
+    BStruct13 = new_struct_type("struct test13")
     complete_struct_or_union(BStruct13, [('a1', BInt, -1),
                                          ('a2', BInt, -1),
                                          ('a3', BInt, -1)])
     assert s.a2 == 40 * 40
     assert s.a3 == 40 * 40 * 40
     #
-    BStruct14 = new_struct_type("test14")
+    BStruct14 = new_struct_type("struct test14")
     complete_struct_or_union(BStruct14, [('a1', BFloat, -1),
                                          ])
     BFunc14 = new_function_type((BInt,), BStruct14)
     assert repr(s) == "<cdata 'struct test14' owning 4 bytes>"
     assert s.a1 == 40.0
     #
-    BStruct15 = new_struct_type("test15")
+    BStruct15 = new_struct_type("struct test15")
     complete_struct_or_union(BStruct15, [('a1', BFloat, -1),
                                          ('a2', BInt, -1)])
     BFunc15 = new_function_type((BInt,), BStruct15)
     assert s.a1 == 40.0
     assert s.a2 == 40 * 40
     #
-    BStruct16 = new_struct_type("test16")
+    BStruct16 = new_struct_type("struct test16")
     complete_struct_or_union(BStruct16, [('a1', BFloat, -1),
                                          ('a2', BFloat, -1)])
     BFunc16 = new_function_type((BInt,), BStruct16)
     assert s.a1 == 40.0
     assert s.a2 == -40.0
     #
-    BStruct17 = new_struct_type("test17")
+    BStruct17 = new_struct_type("struct test17")
     complete_struct_or_union(BStruct17, [('a1', BInt, -1),
                                          ('a2', BFloat, -1)])
     BFunc17 = new_function_type((BInt,), BStruct17)
     BFunc2 = new_function_type((), new_primitive_type("short"))
     BCharP = new_pointer_type(new_primitive_type("char"))
     BIntP = new_pointer_type(new_primitive_type("int"))
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BFunc, -1)])
     newp(BStructPtr, [cast(BFunc, 0)])
         assert not pyuni4
     #
     BWCharP = new_pointer_type(BWChar)
-    BStruct = new_struct_type("foo_s")
+    BStruct = new_struct_type("struct foo_s")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BWChar, -1),
                                        ('a2', BWCharP, -1)])
     # exception to the no-keepalive rule: p=newp(BStructPtr) returns a
     # pointer owning the memory, and p[0] returns a pointer to the
     # struct that *also* owns the memory
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1),
                                        ('a2', new_primitive_type("int"), -1),
     assert q.a1 == 123456
 
 def test_nokeepalive_struct():
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     BStructPtrPtr = new_pointer_type(BStructPtr)
     complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1)])
     assert repr(x) == "<cdata 'int[3]' NULL>"
 
 def test_cast_invalid():
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [])
     p = cast(new_pointer_type(BStruct), 123456)
     s = p[0]
 
 def test_bug_delattr():
     BLong = new_primitive_type("long")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BLong, -1)])
     x = newp(new_pointer_type(BStruct))
     py.test.raises(AttributeError, "del x.a1")
     py.test.skip("later")
     BLong = new_primitive_type("long")
     BArray = new_array_type(new_pointer_type(BLong), None)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructP = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BLong, -1),
                                        ('a2', BArray, -1)])
         BLong = new_primitive_type("long")
         BLongP = new_pointer_type(BLong)
         BArray0 = new_array_type(BLongP, length)
-        BStruct = new_struct_type("foo")
+        BStruct = new_struct_type("struct foo")
         BStructPtr = new_pointer_type(BStruct)
         complete_struct_or_union(BStruct, [('a1', BArray0, -1)])
         p = newp(BStructPtr, None)
 def test_nested_anonymous_struct():
     BInt = new_primitive_type("int")
     BChar = new_primitive_type("char")
-    BStruct = new_struct_type("foo")
-    BInnerStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
+    BInnerStruct = new_struct_type("struct foo")
     complete_struct_or_union(BInnerStruct, [('a1', BInt, -1),
                                             ('a2', BChar, -1)])
     complete_struct_or_union(BStruct, [('', BInnerStruct, -1),
     BChar = new_primitive_type("char")
     BShort = new_primitive_type("short")
     assert sizeof(BShort) == alignof(BShort) == 2
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BChar),
                                        ('a2', BChar),
                                        ('a3', BChar)])
     assert sizeof(BStruct) == 3 and alignof(BStruct) == 1
-    BUnion = new_union_type("u")
+    BUnion = new_union_type("union u")
     complete_struct_or_union(BUnion, [('s', BStruct),
                                       ('i', BShort)])
     assert sizeof(BUnion) == 4
 
 def test_unaligned_struct():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('b', BInt, -1, 1)],
                              None, 5, 1)
 
 
 def test_typeoffsetof():
     BChar = new_primitive_type("char")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BChar, -1),
 
 def test_typeoffsetof_no_bitfield():
     BInt = new_primitive_type("int")
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     complete_struct_or_union(BStruct, [('a1', BInt, 4)])
     py.test.raises(TypeError, typeoffsetof, BStruct, 'a1')
 
 def test_rawaddressof():
     BChar = new_primitive_type("char")
     BCharP = new_pointer_type(BChar)
-    BStruct = new_struct_type("foo")
+    BStruct = new_struct_type("struct foo")
     BStructPtr = new_pointer_type(BStruct)
     complete_struct_or_union(BStruct, [('a1', BChar, -1),
                                        ('a2', BChar, -1),
     if sys.platform == "win32":
         py.test.skip("testing FILE not implemented")
     #
-    BFILE = new_struct_type("_IO_FILE")
+    BFILE = new_struct_type("struct _IO_FILE")
     BFILEP = new_pointer_type(BFILE)
     BChar = new_primitive_type("char")
     BCharP = new_pointer_type(BChar)
     if sys.platform == "win32":
         py.test.skip("testing FILE not implemented")
     #
-    B_NOT_FILE = new_struct_type("NOT_FILE")
+    B_NOT_FILE = new_struct_type("struct NOT_FILE")
     B_NOT_FILEP = new_pointer_type(B_NOT_FILE)
     BChar = new_primitive_type("char")
     BCharP = new_pointer_type(BChar)
     if sys.platform == "win32":
         py.test.skip("testing FILE not implemented")
     #
-    BFILE = new_struct_type("$FILE")
+    BFILE = new_struct_type("FILE")
     BFILEP = new_pointer_type(BFILE)
     BChar = new_primitive_type("char")
     BCharP = new_pointer_type(BChar)
     BShort = new_primitive_type("short")
     BInt = new_primitive_type("int")
     BUInt = new_primitive_type("unsigned int")
-    BStruct = new_struct_type("foo1")
+    BStruct = new_struct_type("struct foo1")
     complete_struct_or_union(BStruct, [('a', BChar, -1),
                                        ('b1', BInt, 9),
                                        ('b2', BUInt, 7),
         assert sizeof(BStruct) == 12
     assert alignof(BStruct) == 4
     #
-    BStruct = new_struct_type("foo2")
+    BStruct = new_struct_type("struct foo2")
     complete_struct_or_union(BStruct, [('a', BChar, -1),
                                        ('',  BShort, 9),
                                        ('c', BChar, -1)], -1, -1, -1, flag)
         assert sizeof(BStruct) == 6
         assert alignof(BStruct) == 2
     #
-    BStruct = new_struct_type("foo2")
+    BStruct = new_struct_type("struct foo2")
     complete_struct_or_union(BStruct, [('a', BChar, -1),
                                        ('',  BInt, 0),
                                        ('',  BInt, 0),

pypy/module/_rawffi/array.py

 from pypy.module._rawffi.interp_rawffi import TYPEMAP
 from pypy.module._rawffi.interp_rawffi import size_alignment
 from pypy.module._rawffi.interp_rawffi import unpack_shape_with_length
+from pypy.module._rawffi.interp_rawffi import read_ptr, write_ptr
 from rpython.rlib.rarithmetic import r_uint
 
-def push_elem(ll_array, pos, value):
-    TP = lltype.typeOf(value)
-    ll_array = rffi.cast(rffi.CArrayPtr(TP), ll_array)
-    ll_array[pos] = value
-push_elem._annspecialcase_ = 'specialize:argtype(2)'
-
-def get_elem(ll_array, pos, ll_t):
-    ll_array = rffi.cast(rffi.CArrayPtr(ll_t), ll_array)
-    return ll_array[pos]
-get_elem._annspecialcase_ = 'specialize:arg(2)'
-
 
 class W_Array(W_DataShape):
     def __init__(self, basicffitype, size):
                                                 " array length"))
             for num in range(iterlength):
                 w_item = items_w[num]
-                unwrap_value(space, push_elem, result.ll_buffer, num,
+                unwrap_value(space, write_ptr, result.ll_buffer, num,
                              self.itemcode, w_item)
         return space.wrap(result)
 
             raise segfault_exception(space, "setting element of freed array")
         if num >= self.length or num < 0:
             raise OperationError(space.w_IndexError, space.w_None)
-        unwrap_value(space, push_elem, self.ll_buffer, num,
+        unwrap_value(space, write_ptr, self.ll_buffer, num,
                      self.shape.itemcode, w_value)
 
     def descr_setitem(self, space, w_index, w_value):
             raise segfault_exception(space, "accessing elements of freed array")
         if num >= self.length or num < 0:
             raise OperationError(space.w_IndexError, space.w_None)
-        return wrap_value(space, get_elem, self.ll_buffer, num,
+        return wrap_value(space, read_ptr, self.ll_buffer, num,
                           self.shape.itemcode)
 
     def descr_getitem(self, space, w_index):

pypy/module/_rawffi/callback.py

 from pypy.interpreter.gateway import interp2app, unwrap_spec
 from pypy.interpreter.typedef import TypeDef, GetSetProperty
 from rpython.rtyper.lltypesystem import lltype, rffi
-from pypy.module._rawffi.array import push_elem
+from pypy.module._rawffi.interp_rawffi import read_ptr, write_ptr
 from pypy.module._rawffi.structure import W_Structure
 from pypy.module._rawffi.interp_rawffi import (W_DataInstance, letter2tp,
      unwrap_value, unpack_argshapes, got_libffi_error)
                 args_w[i] = space.wrap(rffi.cast(rffi.ULONG, ll_args[i]))
         w_res = space.call(w_callable, space.newtuple(args_w))
         if callback_ptr.result is not None: # don't return void
-            unwrap_value(space, push_elem, ll_res, 0,
+            unwrap_value(space, write_ptr, ll_res, 0,
                          callback_ptr.result, w_res)
     except OperationError, e:
         tbprint(space, space.wrap(e.get_traceback()),

pypy/module/_rawffi/interp_rawffi.py

 
 from rpython.rlib.clibffi import *
 from rpython.rtyper.lltypesystem import lltype, rffi
+from rpython.rtyper.tool import rffi_platform
 from rpython.rlib.unroll import unrolling_iterable
 import rpython.rlib.rposix as rposix
 
 }
 TYPEMAP_PTR_LETTERS = "POszZ"
 TYPEMAP_NUMBER_LETTERS = "bBhHiIlLqQ?"
+TYPEMAP_FLOAT_LETTERS = "fd" # XXX long doubles are not propperly supported in
+                             # rpython, so we ignore then here
 
 if _MS_WINDOWS:
     TYPEMAP['X'] = ffi_type_pointer
 )
 
 unroll_letters_for_numbers = unrolling_iterable(TYPEMAP_NUMBER_LETTERS)
+unroll_letters_for_floats = unrolling_iterable(TYPEMAP_FLOAT_LETTERS)
+
+_ARM = rffi_platform.getdefined('__arm__', '')
+
+def read_ptr(ptr, ofs, TP):
+    T = lltype.Ptr(rffi.CArray(TP))
+    for c in unroll_letters_for_floats:
+        # Note: if we are on ARM and have a float-ish value that is not word
+        # aligned accessing it directly causes a SIGBUS. Instead we use memcpy
+        # to avoid the problem
+        if (_ARM and LL_TYPEMAP[c] is TP
+                    and rffi.cast(lltype.Signed, ptr) & 3 != 0):
+            if ofs != 0:
+                ptr = rffi.ptradd(ptr, ofs*rffi.sizeof(TP))
+            with lltype.scoped_alloc(T.TO, 1) as t_array:
+                rffi.c_memcpy(
+                    rffi.cast(rffi.VOIDP, t_array),
+                    rffi.cast(rffi.VOIDP, ptr),
+                    rffi.sizeof(TP))
+                ptr_val = t_array[0]
+                return ptr_val
+    else:
+        return rffi.cast(T, ptr)[ofs]
+read_ptr._annspecialcase_ = 'specialize:arg(2)'
+
+def write_ptr(ptr, ofs, value):
+    TP = lltype.typeOf(value)
+    T = lltype.Ptr(rffi.CArray(TP))
+    for c in unroll_letters_for_floats:
+        # Note: if we are on ARM and have a float-ish value that is not word
+        # aligned accessing it directly causes a SIGBUS. Instead we use memcpy
+        # to avoid the problem
+        if (_ARM and LL_TYPEMAP[c] is TP
+                    and rffi.cast(lltype.Signed, ptr) & 3 != 0):
+            if ofs != 0:
+                ptr = rffi.ptradd(ptr, ofs*rffi.sizeof(TP))
+            with lltype.scoped_alloc(T.TO, 1) as s_array:
+                s_array[0] = value
+                rffi.c_memcpy(
+                    rffi.cast(rffi.VOIDP, ptr),
+                    rffi.cast(rffi.VOIDP, s_array),
+                    rffi.sizeof(TP))
+                return
+    else:
+        rffi.cast(T, ptr)[ofs] = value
+write_ptr._annspecialcase_ = 'specialize:argtype(2)'
 
 def segfault_exception(space, reason):
     w_mod = space.getbuiltinmodule("_rawffi")

pypy/module/_rawffi/structure.py

 from pypy.module._rawffi.interp_rawffi import W_DataShape, W_DataInstance
 from pypy.module._rawffi.interp_rawffi import wrap_value, unwrap_value
 from pypy.module._rawffi.interp_rawffi import unpack_shape_with_length
-from pypy.module._rawffi.interp_rawffi import size_alignment, LL_TYPEMAP
+from pypy.module._rawffi.interp_rawffi import LL_TYPEMAP
 from pypy.module._rawffi.interp_rawffi import unroll_letters_for_numbers
+from pypy.module._rawffi.interp_rawffi import size_alignment
+from pypy.module._rawffi.interp_rawffi import read_ptr, write_ptr
 from rpython.rlib import clibffi
-from rpython.rlib.rarithmetic import intmask, r_uint, signedtype, widen
+from rpython.rlib.rarithmetic import intmask, signedtype, widen
+from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong
 
 def unpack_fields(space, w_fields):
     fields_w = space.unpackiterable(w_fields)
 
 def LOW_BIT(x):
     return x & 0xFFFF
+
 def NUM_BITS(x):
     return x >> 16
-def BIT_MASK(x):
-    return (1 << x) - 1
+
+def BIT_MASK(x, ll_t):
+    if ll_t is lltype.SignedLongLong:
+        return (r_longlong(1) << x) - 1
+    elif ll_t is lltype.UnsignedLongLong:
+        return (r_ulonglong(1) << x) - 1
+    return (1  << x) -1
+BIT_MASK._annspecialcase_ = 'specialize:arg(1)'
 
 def push_field(self, num, value):
     ptr = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[num])
             lowbit = LOW_BIT(bitsize)
             if numbits:
                 value = widen(value)
-                current = widen(rffi.cast(T, ptr)[0])
-                bitmask = BIT_MASK(numbits)
+                bitmask = BIT_MASK(numbits, TP)
+                #
+                current = widen(read_ptr(ptr, 0, TP))
                 current &= ~ (bitmask << lowbit)
                 current |= (value & bitmask) << lowbit
                 value = rffi.cast(TP, current)
             break
-
-    rffi.cast(T, ptr)[0] = value
+    write_ptr(ptr, 0, value)
 push_field._annspecialcase_ = 'specialize:argtype(2)'
 
 def cast_pos(self, i, ll_t):
     pos = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i])
     TP = lltype.Ptr(rffi.CArray(ll_t))
-    value = rffi.cast(TP, pos)[0]
+    value = read_ptr(pos, 0, ll_t)
 
     # Handle bitfields
     for c in unroll_letters_for_numbers:
             numbits = NUM_BITS(bitsize)
             lowbit = LOW_BIT(bitsize)
             if numbits:
-                value = widen(value)
+                value = widen(rffi.cast(ll_t, value))
+                bitmask = BIT_MASK(numbits, ll_t)
+                #
                 value >>= lowbit
-                value &= BIT_MASK(numbits)
+                value &= bitmask
                 if ll_t is lltype.Bool or signedtype(ll_t._type):
                     sign = (value >> (numbits - 1)) & 1
                     if sign:
-                        value = value - (1 << numbits)
+                        one = r_longlong(1) if ll_t is lltype.SignedLongLong else 1
+                        value = value - (one << numbits)
                 value = rffi.cast(ll_t, value)
             break
 

pypy/module/_rawffi/test/test__rawffi.py

 from rpython.translator.platform import platform
 from rpython.translator.tool.cbuild import ExternalCompilationInfo
-from pypy.module._rawffi.interp_rawffi import TYPEMAP
+from pypy.module._rawffi.interp_rawffi import TYPEMAP, TYPEMAP_FLOAT_LETTERS
 from pypy.module._rawffi.tracker import Tracker
 
 import os, sys, py
             free(x1->next);
             free(x1);
         }
-        
+
         const char *static_str = "xxxxxx";
         long static_int = 42;
         double static_double = 42.42;
         long double static_longdouble = 42.42;
-        
+
         unsigned short add_shorts(short one, short two)
         {
            return one + two;
             inp.y = inp.x * 100;
             return inp;
         }
-        
+
         '''))
         symbols = """get_char char_check get_raw_pointer
                      add_shorts
         eci = ExternalCompilationInfo(export_symbols=symbols)
         return str(platform.compile([c_file], eci, 'x', standalone=False))
     prepare_c_example = staticmethod(prepare_c_example)
-    
+
     def setup_class(cls):
         space = cls.space
         from rpython.rlib.clibffi import get_libc_name
         cls.w_platform = space.wrap(platform.name)
         cls.w_sizes_and_alignments = space.wrap(dict(
             [(k, (v.c_size, v.c_alignment)) for k,v in TYPEMAP.iteritems()]))
+        cls.w_float_typemap = space.wrap(TYPEMAP_FLOAT_LETTERS)
 
     def test_libload(self):
         import _rawffi
         arg.free()
         assert t.tm_year == 70
         assert t.tm_sec == 1
-        assert t.tm_min == 2      
+        assert t.tm_min == 2
         x.free()
 
     def test_nested_structures(self):
         free_double_struct = lib.ptr("free_double_struct", ['P'], None)
         free_double_struct(res)
 
+    def test_structure_bitfields_char(self):
+        import _rawffi
+        X = _rawffi.Structure([('A', 'B', 1),
+                               ('B', 'B', 6),
+                               ('C', 'B', 1)])
+        x = X()
+        x.A = 0xf
+        x.B = 0xff
+        x.C = 0xf
+        assert x.A == 1
+        assert x.B == 63
+        assert x.C == 1
+        x.free()
+
     def test_structure_bitfields(self):
         import _rawffi
         X = _rawffi.Structure([('A', 'I', 1),
         assert (y.a, y.b, y.c) == (-1, -7, 0)
         y.free()
 
+    def test_structure_bitfields_longlong(self):
+        import _rawffi
+        Z = _rawffi.Structure([('a', 'Q', 1),
+                               ('b', 'Q', 62),
+                               ('c', 'Q', 1)])
+        z = Z()
+        z.a, z.b, z.c = 7, 0x1000000000000001, 7
+        assert (z.a, z.b, z.c) == (1, 0x1000000000000001, 1)
+        z.free()
+
+    def test_structure_ulonglong_bitfields(self):
+        import _rawffi
+        X = _rawffi.Structure([('A', 'Q', 1),
+                               ('B', 'Q', 62),
+                               ('C', 'Q', 1)])
+        x = X()
+        x.A, x.B, x.C = 7, 0x1000000000000001, 7
+        assert x.A == 1
+        assert x.B == 0x1000000000000001
+        assert x.C == 1
+        x.free()
+
+    def test_structure_longlong_bitfields(self):
+        import _rawffi
+        Y = _rawffi.Structure([('a', 'q', 1),
+                               ('b', 'q', 61),
+                               ('c', 'q', 1)])
+        y = Y()
+        y.a, y.b, y.c = 0, -7, 0
+        assert (y.a, y.b, y.c) == (0, -7, 0)
+        y.free()
+
+    def test_structure_ulonglong_bitfields(self):
+        import _rawffi
+        X = _rawffi.Structure([('A', 'Q', 1),
+                               ('B', 'Q', 62),
+                               ('C', 'Q', 1)])
+        x = X()
+        x.A, x.B, x.C = 7, 0x1000000000000001, 7
+        assert x.A == 1
+        assert x.B == 0x1000000000000001
+        assert x.C == 1
+        x.free()
+
+    def test_structure_longlong_bitfields(self):
+        import _rawffi
+        Y = _rawffi.Structure([('a', 'q', 1),
+                               ('b', 'q', 61),
+                               ('c', 'q', 1)])
+        y = Y()
+        y.a, y.b, y.c = 0, -7, 0
+        assert (y.a, y.b, y.c) == (0, -7, 0)
+        y.free()
+
     def test_invalid_bitfields(self):
         import _rawffi
         raises(TypeError, _rawffi.Structure, [('A', 'c', 1)])
         res = pass_ll(arg1)
         assert res[0] == 1<<42
         arg1.free()
-    
+
     def test_callback(self):
         import _rawffi
         import struct
             assert _rawffi.sizeof(k) == s
             assert _rawffi.alignment(k) == a
 
+    def test_unaligned(self):
+        import _rawffi
+        for k in self.float_typemap:
+            S = _rawffi.Structure([('pad', 'c'), ('value', k)], pack=1)
+            s = S()
+            s.value = 4
+            assert s.value == 4
+            s.free()
+
+
     def test_array_addressof(self):
         import _rawffi
         lib = _rawffi.CDLL(self.lib_name)
         assert res.y == 33
         assert s2h.x == 7
         assert s2h.y == 11
-        
+
         s2h.free()
 
     def test_ret_struct_containing_array(self):
 
 class AppTestAutoFree:
     spaceconfig = dict(usemodules=['_rawffi', 'struct'])
-    
+
     def setup_class(cls):
         cls.w_sizes_and_alignments = cls.space.wrap(dict(
             [(k, (v.c_size, v.c_alignment)) for k,v in TYPEMAP.iteritems()]))

pypy/module/micronumpy/interp_boxes.py

         w_values = space.newtuple([self])
         return convert_to_array(space, w_values)
 
+    @unwrap_spec(decimals=int)
+    def descr_round(self, space, decimals=0):
+        v = self.convert_to(self.get_dtype(space))
+        return self.get_dtype(space).itemtype.round(v, decimals)
+
 class W_BoolBox(W_GenericBox, PrimitiveBox):
     descr__new__, _get_dtype, descr_reduce = new_dtype_getter("bool")
 
     any = interp2app(W_GenericBox.descr_any),
     all = interp2app(W_GenericBox.descr_all),
     ravel = interp2app(W_GenericBox.descr_ravel),
+    round = interp2app(W_GenericBox.descr_round),
 )
 
 W_BoolBox.typedef = TypeDef("bool_", W_GenericBox.typedef,

pypy/module/micronumpy/interp_numarray.py

         raise OperationError(space.w_NotImplementedError, space.wrap(
             "resize not implemented yet"))
 
-    def descr_round(self, space, w_decimals=0, w_out=None):
-        raise OperationError(space.w_NotImplementedError, space.wrap(
-            "round not implemented yet"))
+    @unwrap_spec(decimals=int)
+    def descr_round(self, space, decimals=0, w_out=None):
+        if space.is_none(w_out):
+            if self.get_dtype().is_bool_type():
+                #numpy promotes bool.round() to float16. Go figure.
+                w_out = W_NDimArray.from_shape(self.get_shape(),
+                       interp_dtype.get_dtype_cache(space).w_float16dtype)
+            else:
+                w_out = None
+        elif not isinstance(w_out, W_NDimArray):
+            raise OperationError(space.w_TypeError, space.wrap(
+                "return arrays must be of ArrayType"))
+        out = interp_dtype.dtype_agreement(space, [self], self.get_shape(),
+                                           w_out)
+        if out.get_dtype().is_bool_type() and self.get_dtype().is_bool_type():
+            calc_dtype = interp_dtype.get_dtype_cache(space).w_longdtype
+        else:
+            calc_dtype = out.get_dtype()
+
+        loop.round(space, self, calc_dtype, self.get_shape(), decimals, out)
+        return out
 
     def descr_searchsorted(self, space, w_v, w_side='left'):
         raise OperationError(space.w_NotImplementedError, space.wrap(
     byteswap = interp2app(W_NDimArray.descr_byteswap),
     choose   = interp2app(W_NDimArray.descr_choose),
     clip     = interp2app(W_NDimArray.descr_clip),
+    round    = interp2app(W_NDimArray.descr_round),
     data     = GetSetProperty(W_NDimArray.descr_get_data),
     diagonal = interp2app(W_NDimArray.descr_diagonal),
 

pypy/module/micronumpy/loop.py

         iter = x_iter
     shapelen = len(shape)
     while not iter.done():
-        where_driver.jit_merge_point(shapelen=shapelen, dtype=dtype, 
+        where_driver.jit_merge_point(shapelen=shapelen, dtype=dtype,
                                         arr_dtype=arr_dtype)
         w_cond = arr_iter.getitem()
         if arr_dtype.itemtype.bool(w_cond):
     return out
 
 axis_reduce__driver = jit.JitDriver(name='numpy_axis_reduce',
-                                    greens=['shapelen', 
+                                    greens=['shapelen',
                                             'func', 'dtype',
                                             'identity'],
                                     reds='auto')
     arg_driver = jit.JitDriver(name='numpy_' + op_name,
                                greens = ['shapelen', 'dtype'],
                                reds = 'auto')
-    
+
     def argmin_argmax(arr):
         result = 0
         idx = 1
      result.shape == [3, 5, 2, 4]
      broadcast shape should be [3, 5, 2, 7, 4]
      result should skip dims 3 which is len(result_shape) - 1
-        (note that if right is 1d, result should 
+        (note that if right is 1d, result should
                   skip len(result_shape))
      left should skip 2, 4 which is a.ndims-1 + range(right.ndims)
           except where it==(right.ndims-2)
     righti = right.create_dot_iter(broadcast_shape, right_skip)
     while not outi.done():
         dot_driver.jit_merge_point(dtype=dtype)
-        lval = lefti.getitem().convert_to(dtype) 
-        rval = righti.getitem().convert_to(dtype) 
-        outval = outi.getitem().convert_to(dtype) 
+        lval = lefti.getitem().convert_to(dtype)
+        rval = righti.getitem().convert_to(dtype)
+        outval = outi.getitem().convert_to(dtype)
         v = dtype.itemtype.mul(lval, rval)
         value = dtype.itemtype.add(v, outval).convert_to(dtype)
         outi.setitem(value)
         setitem_filter_driver.jit_merge_point(shapelen=shapelen,
                                               index_dtype=index_dtype,
                                               arr_dtype=arr_dtype,
-                                             ) 
+                                             )
         if index_iter.getitem_bool():
             arr_iter.setitem(value_iter.getitem())
             value_iter.next()
         out_iter.next()
         min_iter.next()
 
+round_driver = jit.JitDriver(greens = ['shapelen', 'dtype'],
+                                    reds = 'auto')
+
+def round(space, arr, dtype, shape, decimals, out):
+    arr_iter = arr.create_iter(shape)
+    shapelen = len(shape)
+    out_iter = out.create_iter(shape)
+    while not arr_iter.done():
+        round_driver.jit_merge_point(shapelen=shapelen, dtype=dtype)
+        w_v = dtype.itemtype.round(arr_iter.getitem().convert_to(dtype),
+                     decimals)
+        out_iter.setitem(w_v)
+        arr_iter.next()
+        out_iter.next()
+
 diagonal_simple_driver = jit.JitDriver(greens = ['axis1', 'axis2'],
                                        reds = 'auto')
 
         out_iter.setitem(arr.getitem_index(space, indexes))
         iter.next()
         out_iter.next()
-       
+

pypy/module/micronumpy/test/test_scalar.py

 
         a = zeros(3)
         assert loads(dumps(sum(a))) == sum(a)
+
+    def test_round(self):
+        from numpypy import int32, float64, complex128, bool
+        i = int32(1337)
+        f = float64(13.37)
+        c = complex128(13 + 37.j)
+        b = bool(0)
+        assert i.round(decimals=-2) == 1300
+        assert i.round(decimals=1) == 1337
+        assert c.round() == c
+        assert f.round() == 13.
+        assert f.round(decimals=-1) == 10.
+        assert f.round(decimals=1) == 13.4
+        exc = raises(AttributeError, 'b.round()')
+        assert exc.value[0] == "'bool' object has no attribute 'round'"
+

pypy/module/micronumpy/test/test_ufuncs.py

 
         skip('sign of nan is non-determinant')
         assert (signbit([float('nan'), float('-nan'), -float('nan')]) ==
-            [False, True, True]).all()    
+            [False, True, True]).all()
 
     def test_reciprocal(self):
         from numpypy import array, reciprocal, complex64, complex128
         assert all([math.copysign(1, f(abs(float("nan")))) == 1 for f in floor, ceil, trunc])
         assert all([math.copysign(1, f(-abs(float("nan")))) == -1 for f in floor, ceil, trunc])
 
+    def test_round(self):
+        from numpypy import array, dtype
+        ninf, inf = float("-inf"), float("inf")
+        a = array([ninf, -1.4, -1.5, -1.0, 0.0, 1.0, 1.4, 0.5, inf])
+        assert ([ninf, -1.0, -2.0, -1.0, 0.0, 1.0, 1.0, 0.0, inf] == a.round()).all()
+        i = array([-1000, -100, -1, 0, 1, 111, 1111, 11111], dtype=int)
+        assert (i == i.round()).all()
+        assert (i.round(decimals=4) == i).all()
+        assert (i.round(decimals=-4) == [0, 0, 0, 0, 0, 0, 0, 10000]).all()
+        b = array([True, False], dtype=bool)
+        bround = b.round()
+        assert (bround == [1., 0.]).all()
+        assert bround.dtype is dtype('float16')
+        c = array([10.5+11.5j, -15.2-100.3456j, 0.2343+11.123456j])
+        assert (c.round(0) == [10.+12.j, -15-100j, 0+11j]).all()
+
+
     def test_copysign(self):
         from numpypy import array, copysign
 
             assert b[i] == res
 
     def test_exp2(self):
-        import math 
+        import math
         from numpypy import array, exp2
         inf = float('inf')
         ninf = -float('inf')
              complex(inf, inf), complex(inf, ninf), complex(0, inf),
              complex(ninf, ninf), complex(nan, 0), complex(0, nan),
              complex(nan, nan)]
-        assert (isfinite(a) == [True, True, False, False, False, 
-                        False, False, False, False, False]).all() 
+        assert (isfinite(a) == [True, True, False, False, False,
+                        False, False, False, False, False]).all()
 
     def test_logical_ops(self):
         from numpypy import logical_and, logical_or, logical_xor, logical_not
         #numpy returns (a.real*b.real + a.imag*b.imag) / abs(b)**2
         expect = [3., -23., 1.]
         for i in range(len(a)):
-            assert b[i] == expect[i] 
+            assert b[i] == expect[i]
         b = floor_divide(a[0], 0.)
         assert math.isnan(b.real)
         assert b.imag == 0.

pypy/module/micronumpy/types.py

         return self.box(
             func(
                 self,
-                self.for_computation(raw)
+                self.for_computation(raw),
             )
         )
     return dispatcher
             return v
         return 0
 
+    @specialize.argtype(1)
+    def round(self, v, decimals=0):
+        raw = self.for_computation(self.unbox(v))
+        if decimals < 0:
+            # No ** in rpython
+            factor = 1
+            for i in xrange(-decimals):
+                factor *=10
+            #int does floor division, we want toward zero
+            if raw < 0:
+                ans = - (-raw / factor * factor)
+            else:
+                ans = raw / factor * factor
+        else:
+            ans = raw
+        return self.box(ans)
+
     @raw_unary_op
     def signbit(self, v):
         return v < 0
     def ceil(self, v):
         return math.ceil(v)
 
+    @specialize.argtype(1)
+    def round(self, v, decimals=0):
+        raw = self.for_computation(self.unbox(v))
+        if rfloat.isinf(raw):
+            return v
+        elif rfloat.isnan(raw):
+            return v
+        ans = rfloat.round_double(raw, decimals, half_even=True)
+        return self.box(ans)
+
     @simple_unary_op
     def trunc(self, v):
         if v < 0:
         except ZeroDivisionError:
             return rfloat.NAN, rfloat.NAN
 
+    @specialize.argtype(1)
+    def round(self, v, decimals=0):
+        ans = list(self.for_computation(self.unbox(v)))
+        if isfinite(ans[0]):
+            ans[0] = rfloat.round_double(ans[0], decimals,  half_even=True)
+        if isfinite(ans[1]):
+            ans[1] = rfloat.round_double(ans[1], decimals,  half_even=True)
+        return self.box_complex(ans[0], ans[1])
+
     # No floor, ceil, trunc in numpy for complex
     #@simple_unary_op
     #def floor(self, v):

pypy/module/mmap/interp_mmap.py

 from pypy.interpreter.baseobjspace import W_Root
 from pypy.interpreter.typedef import TypeDef, GetSetProperty
 from pypy.interpreter.gateway import interp2app, unwrap_spec
+from pypy.interpreter.buffer import RWBuffer
 from rpython.rlib import rmmap, rarithmetic
-from rpython.rlib.rmmap import RValueError, RTypeError
+from rpython.rlib.rmmap import RValueError, RTypeError, RMMapError
 
 if rmmap.HAVE_LARGEFILE_SUPPORT:
     OFF_T = rarithmetic.r_longlong
         self.mmap.close()
 
     def read_byte(self):
+        self.check_valid()
         try:
             return self.space.wrap(ord(self.mmap.read_byte()))
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
 
     def readline(self):
+        self.check_valid()
         return self.space.wrapbytes(self.mmap.readline())
 
     @unwrap_spec(num=int)
 
     @unwrap_spec(tofind='bufferstr')
     def find(self, tofind, w_start=None, w_end=None):
+        self.check_valid()
         space = self.space
         if w_start is None:
             start = self.mmap.pos
 
     @unwrap_spec(tofind='bufferstr')
     def rfind(self, tofind, w_start=None, w_end=None):
+        self.check_valid()
         space = self.space
         if w_start is None:
             start = self.mmap.pos
 
     @unwrap_spec(pos=OFF_T, whence=int)
     def seek(self, pos, whence=0):
+        self.check_valid()
         try:
             self.mmap.seek(pos, whence)
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
 
     def tell(self):
+        self.check_valid()
         return self.space.wrap(self.mmap.tell())
 
     def descr_size(self):
+        self.check_valid()
         try:
             return self.space.wrap(self.mmap.file_size())
         except OSError, e:
 
     @unwrap_spec(data='bufferstr')
     def write(self, data):
+        self.check_valid()
         self.check_writeable()
         try:
             self.mmap.write(data)
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
 
     @unwrap_spec(byte=int)
     def write_byte(self, byte):
+        self.check_valid()
+        self.check_writeable()
         try:
             self.mmap.write_byte(chr(byte))
-        except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
-        except RTypeError, v:
-            raise OperationError(self.space.w_TypeError,
-                                 self.space.wrap(v.message))
+        except RMMapError, v:
+            raise mmap_error(self.space, v)
 
     @unwrap_spec(offset=int, size=int)
     def flush(self, offset=0, size=0):
+        self.check_valid()
         try:
             return self.space.wrap(self.mmap.flush(offset, size))
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
         except OSError, e:
             raise mmap_error(self.space, e)
 
     @unwrap_spec(dest=int, src=int, count=int)
     def move(self, dest, src, count):
+        self.check_valid()
+        self.check_writeable()
         try:
             self.mmap.move(dest, src, count)
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
 
     @unwrap_spec(newsize=int)
     def resize(self, newsize):
         try:
             self.mmap.check_valid()
         except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
+            raise mmap_error(self.space, v)
 
     def check_writeable(self):
         try:
             self.mmap.check_writeable()
-        except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
-        except RTypeError, v:
-            raise OperationError(self.space.w_TypeError,
-                                 self.space.wrap(v.message))
+        except RMMapError, v:
+            raise mmap_error(self.space, v)
 
     def check_resizeable(self):
         try:
             self.mmap.check_resizeable()
-        except RValueError, v:
-            raise OperationError(self.space.w_ValueError,
-                                 self.space.wrap(v.message))
-        except RTypeError, v:
-            raise OperationError(self.space.w_TypeError,
-                                 self.space.wrap(v.message))
+        except RMMapError, v:
+            raise mmap_error(self.space, v)
 
     def descr_getitem(self, w_index):
         self.check_valid()
         start, stop, step = space.decode_index(w_index, self.mmap.size)
         if step == 0:  # index only
             return space.wrap(ord(self.mmap.getitem(start)))
+        elif step == 1:
+            return space.wrap(self.mmap.getslice(start, stop - start))
         else:
             res = "".join([self.mmap.getitem(i)
                            for i in range(start, stop, step)])
             if len(value) != length:
                 raise OperationError(space.w_ValueError,
                           space.wrap("mmap slice assignment is wrong size"))
-            for i in range(length):
-                self.mmap.setitem(start, value[i])
-                start += step
+            if step == 1:
+                self.mmap.setslice(start, value)
+            else:
+                for i in range(length):
+                    self.mmap.setitem(start, value[i])
+                    start += step
 
     def descr_buffer(self):
-        # XXX improve to work directly on the low-level address
-        from pypy.interpreter.buffer import StringLikeBuffer
-        space = self.space
-        return space.wrap(StringLikeBuffer(space, space.wrap(self)))
+        self.check_valid()
+        return self.space.wrap(MMapBuffer(self.space, self.mmap))
 
     def descr_enter(self, space):
         self.check_valid()
                                        offset))
         except OSError, e:
             raise mmap_error(space, e)
-        except RValueError, e:
-            raise OperationError(space.w_ValueError, space.wrap(e.message))
-        except RTypeError, e:
-            raise OperationError(space.w_TypeError, space.wrap(e.message))
+        except RMMapError, e:
+            raise mmap_error(space, e)
         return space.wrap(self)
 
 elif rmmap._MS_WINDOWS:
                                        offset))
         except OSError, e:
             raise mmap_error(space, e)
-        except RValueError, e:
-            raise OperationError(space.w_ValueError, space.wrap(e.message))
-        except RTypeError, e:
-            raise OperationError(space.w_TypeError, space.wrap(e.message))
+        except RMMapError, e:
+            raise mmap_error(space, e)
         return space.wrap(self)
 
 W_MMap.typedef = TypeDef("mmap",
                                                  space.w_EnvironmentError)
 
 def mmap_error(space, e):
-    w_error = space.fromcache(Cache).w_error
-    return wrap_oserror(space, e, w_exception_class=w_error)
+    if isinstance(e, RValueError):
+        return OperationError(space.w_ValueError,
+                              space.wrap(e.message))
+    elif isinstance(e, RTypeError):
+        return OperationError(space.w_TypeError,
+                              space.wrap(e.message))
+    elif isinstance(e, OSError):
+        w_error = space.fromcache(Cache).w_error
+        return wrap_oserror(space, e, w_exception_class=w_error)
+    else:
+        # bogus 'e'?
+        return OperationError(space.w_SystemError, space.wrap('%s' % e))
+mmap_error._dont_inline_ = True
+
+
+class MMapBuffer(RWBuffer):
+    def __init__(self, space, mmap):
+        self.space = space
+        self.mmap = mmap
+
+    def get_raw_address(self):
+        return self.mmap.data
+
+    def getlength(self):
+        return self.mmap.size
+
+    def getitem(self, index):
+        self.check_valid()
+        return self.mmap.data[index]
+
+    def getslice(self, start, stop, step, size):
+        self.check_valid()
+        if step == 1:
+            return self.mmap.getslice(start, size)
+        else:
+            return RWBuffer.getslice(self, start, stop, step, size)
+
+    def setitem(self, index, char):
+        self.check_valid_writeable()
+        self.mmap.data[index] = char
+
+    def setslice(self, start, string):
+        self.check_valid_writeable()
+        self.mmap.setslice(start, string)
+
+    def get_raw_address(self):
+        self.check_valid()
+        return self.mmap.data
+
+    def check_valid(self):
+        try:
+            self.mmap.check_valid()
+        except RValueError, v:
+            raise mmap_error(self.space, v)
+
+    def check_valid_writeable(self):
+        try:
+            self.mmap.check_valid()
+            self.mmap.check_writeable()
+        except RMMapError, v:
+            raise mmap_error(self.space, v)

pypy/module/mmap/test/test_mmap.py

         m.close()
         f.close()
 
+    def test_buffer_write(self):
+        from mmap import mmap
+        f = open(self.tmpname + "y", "w+")
+        f.write("foobar")
+        f.flush()
+        m = mmap(f.fileno(), 6)
+        m[5] = '?'
+        b = buffer(m)
+        try:
+            b[:3] = "FOO"
+        except TypeError:     # on CPython: "buffer is read-only" :-/
+            skip("on CPython: buffer is read-only")
+        m.close()
+        f.seek(0)
+        got = f.read()
+        assert got == "FOOba?"
+        f.close()
+
     def test_offset(self):
         from mmap import mmap, ALLOCATIONGRANULARITY
         f = open(self.tmpname + "y", "wb+")

pypy/module/sys/initpath.py

     raise NotImplementedError
 
 def resolvedirof(filename):
-    try:
-        filename = rpath.rabspath(filename)
-    except OSError:
-        pass
+    filename = rpath.rabspath(filename)
     dirname = rpath.rabspath(os.path.join(filename, '..'))
     if os.path.islink(filename):
         try:

pypy/module/test_lib_pypy/cffi_tests/backend_tests.py

         assert f.a == 12345
         assert b.b == b"B"
         assert b.c == b"C"
-        assert repr(b).startswith("<cdata 'struct $bar_t *'")
+        assert repr(b).startswith("<cdata 'bar_t *'")
 
     def test_struct_with_two_usages(self):
         for name in ['foo_s', '']:    # anonymous or not
         ffi = FFI(backend=self.Backend())
         ffi.cdef("typedef enum { Value0 = 0 } e, *pe;\n"
                  "typedef enum { Value1 = 1 } e1;")
-        assert ffi.getctype("e*") == 'enum $e *'
-        assert ffi.getctype("pe") == 'enum $e *'
-        assert ffi.getctype("e1*") == 'enum $e1 *'
+        assert ffi.getctype("e*") == 'e *'
+        assert ffi.getctype("pe") == 'e *'
+        assert ffi.getctype("e1*") == 'e1 *'
 
     def test_new_ctype(self):
         ffi = FFI(backend=self.Backend())

pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py

             'ffi.cdef("struct s2 { char x:0; };"); ffi.new("struct s2 *")')
         py.test.raises(TypeError,
             'ffi.cdef("struct s3 { char x:9; };"); ffi.new("struct s3 *")')
+
+    def test_struct_with_typedef(self):
+        ffi = FFI()
+        ffi.cdef("typedef struct { float x; } foo_t;")
+        p = ffi.new("foo_t *", [5.2])
+        assert repr(p).startswith("<cdata 'foo_t *' ")

pypy/module/test_lib_pypy/cffi_tests/test_verify.py

                        "foo_t myfunc(void) { foo_t x = { 42 }; return x; }")
     assert str(e.value) in [
         "function myfunc: 'foo_t' is used as result type, but is opaque",
-        "function myfunc: result type 'struct $foo_t' is opaque"]
+        "function myfunc: result type 'foo_t' is opaque"]
 
 def test_include():
     ffi1 = FFI()

pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py

         x.a, x.b, x.c = -1, 7, -1
         assert (x.a, x.b, x.c) == (-1, 7, -1)
 
+        x = X()
+        x.a, x.b, x.c = -1, -7, -1
+        assert (x.a, x.b, x.c) == (-1, -7, -1)
+
     def test_ulonglong(self):
         class X(Structure):
             _fields_ = [("a", c_ulonglong, 1),
         assert sizeof(X) == sizeof(c_longlong)
         x = X()
         assert (x.a, x.b, x.c) == (0, 0, 0)
-        x.a, x.b, x.c = 7, 7, 7
-        assert (x.a, x.b, x.c) == (1, 7, 1)
+        x.a, x.b, x.c = 7, 2305843009213693953, 7
+        assert (x.a, x.b, x.c) == (1, 2305843009213693953, 1)
 
     def test_signed(self):
         for c_typ in signed_int_types:

pypy/objspace/std/boolobject.py

 def delegate_Bool2IntObject(space, w_bool):
     return W_IntObject(int(w_bool.boolval))
 
-def delegate_Bool2SmallInt(space, w_bool):
-    from pypy.objspace.std.smallintobject import W_SmallIntObject
-    return W_SmallIntObject(int(w_bool.boolval))   # cannot overflow
-
 
 def nonzero__Bool(space, w_bool):
     return w_bool

pypy/objspace/std/intobject.py

 
 #registerimplementation(W_IntObject)
 
-# NB: This code is shared by smallintobject.py, and thus no other Int
-# multimethods should be invoked from these implementations. Instead, add an
-# alias and then teach copy_multimethods in smallintobject.py to override