[pypy-commit] pypy refactor-str-types: hg merge default
Manuel Jacob
noreply at buildbot.pypy.org
Thu Jun 27 16:11:58 CEST 2013
Author: Manuel Jacob
Branch: refactor-str-types
Changeset: r65037:4cfd5cc8928e
Date: 2013-06-27 16:09 +0200
http://bitbucket.org/pypy/pypy/changeset/4cfd5cc8928e/
Log: hg merge default
diff too long, truncating to 2000 out of 4528 lines
diff --git a/.hgignore b/.hgignore
--- a/.hgignore
+++ b/.hgignore
@@ -6,6 +6,7 @@
.idea
.project
.pydevproject
+__pycache__
syntax: regexp
^testresult$
diff --git a/lib_pypy/_ctypes/structure.py b/lib_pypy/_ctypes/structure.py
--- a/lib_pypy/_ctypes/structure.py
+++ b/lib_pypy/_ctypes/structure.py
@@ -20,7 +20,7 @@
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__)
diff --git a/lib_pypy/cffi/backend_ctypes.py b/lib_pypy/cffi/backend_ctypes.py
--- a/lib_pypy/cffi/backend_ctypes.py
+++ b/lib_pypy/cffi/backend_ctypes.py
@@ -707,7 +707,7 @@
class CTypesStructOrUnion(CTypesBaseStructOrUnion):
__slots__ = ['_blob']
_ctype = struct_or_union
- _reftypename = '%s %s &' % (kind, name)
+ _reftypename = '%s &' % (name,)
_kind = kind
#
CTypesStructOrUnion._fix_class()
@@ -934,7 +934,7 @@
#
class CTypesEnum(CTypesInt):
__slots__ = []
- _reftypename = 'enum %s &' % name
+ _reftypename = '%s &' % name
def _get_own_repr(self):
value = self._value
diff --git a/lib_pypy/cffi/model.py b/lib_pypy/cffi/model.py
--- a/lib_pypy/cffi/model.py
+++ b/lib_pypy/cffi/model.py
@@ -244,6 +244,10 @@
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
@@ -357,7 +361,9 @@
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):
@@ -365,7 +371,8 @@
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):
@@ -388,7 +395,8 @@
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)
diff --git a/pypy/doc/how-to-contribute.rst b/pypy/doc/how-to-contribute.rst
--- a/pypy/doc/how-to-contribute.rst
+++ b/pypy/doc/how-to-contribute.rst
@@ -76,4 +76,4 @@
The rest of directories serve specific niche goal and are unlikely a good
entry point.
-.. _`introduction to RPython`: getting-started-dev.rst
+.. _`introduction to RPython`: getting-started-dev.html
diff --git a/pypy/doc/whatsnew-head.rst b/pypy/doc/whatsnew-head.rst
--- a/pypy/doc/whatsnew-head.rst
+++ b/pypy/doc/whatsnew-head.rst
@@ -57,3 +57,7 @@
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).
diff --git a/pypy/interpreter/error.py b/pypy/interpreter/error.py
--- a/pypy/interpreter/error.py
+++ b/pypy/interpreter/error.py
@@ -29,12 +29,12 @@
_application_traceback = None
def __init__(self, w_type, w_value, tb=None):
- assert w_type is not None
self.setup(w_type)
self._w_value = w_value
self._application_traceback = tb
def setup(self, w_type):
+ assert w_type is not None
self.w_type = w_type
if not we_are_translated():
self.debug_excs = []
@@ -347,7 +347,6 @@
self.xstrings = strings
for i, _, attr in entries:
setattr(self, attr, args[i])
- assert w_type is not None
def _compute_value(self, space):
lst = [None] * (len(formats) + len(formats) + 1)
@@ -369,6 +368,18 @@
_fmtcache2[formats] = OpErrFmt
return OpErrFmt, strings
+class OpErrFmtNoArgs(OperationError):
+
+ def __init__(self, w_type, value):
+ self.setup(w_type)
+ self._value = value
+
+ def get_w_value(self, space):
+ w_value = self._w_value
+ if w_value is None:
+ self._w_value = w_value = space.wrap(self._value)
+ return w_value
+
def get_operationerr_class(valuefmt):
try:
result = _fmtcache[valuefmt]
@@ -389,6 +400,8 @@
%T - The result of space.type(w_arg).getname(space)
"""
+ if not len(args):
+ return OpErrFmtNoArgs(w_type, valuefmt)
OpErrFmt, strings = get_operationerr_class(valuefmt)
return OpErrFmt(w_type, strings, *args)
operationerrfmt._annspecialcase_ = 'specialize:arg(1)'
diff --git a/pypy/interpreter/test/test_error.py b/pypy/interpreter/test/test_error.py
--- a/pypy/interpreter/test/test_error.py
+++ b/pypy/interpreter/test/test_error.py
@@ -33,6 +33,14 @@
operr3 = operationerrfmt("w_type2", "a %s b %s c", "bar", "4b")
assert operr3.__class__ is not operr.__class__
+def test_operationerrfmt_noargs(space):
+ operr = operationerrfmt(space.w_AttributeError, "no attribute 'foo'")
+ operr.normalize_exception(space)
+ val = operr.get_w_value(space)
+ assert space.isinstance_w(val, space.w_AttributeError)
+ w_repr = space.repr(val)
+ assert space.str_w(w_repr) == "AttributeError(\"no attribute 'foo'\",)"
+
def test_operationerrfmt_T(space):
operr = operationerrfmt(space.w_AttributeError,
"'%T' object has no attribute '%s'",
diff --git a/pypy/module/__pypy__/interp_dict.py b/pypy/module/__pypy__/interp_dict.py
--- a/pypy/module/__pypy__/interp_dict.py
+++ b/pypy/module/__pypy__/interp_dict.py
@@ -5,6 +5,22 @@
@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':
@@ -18,6 +34,10 @@
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"))
diff --git a/pypy/module/_cffi_backend/ctypeenum.py b/pypy/module/_cffi_backend/ctypeenum.py
--- a/pypy/module/_cffi_backend/ctypeenum.py
+++ b/pypy/module/_cffi_backend/ctypeenum.py
@@ -13,7 +13,6 @@
_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
diff --git a/pypy/module/_cffi_backend/ctypeptr.py b/pypy/module/_cffi_backend/ctypeptr.py
--- a/pypy/module/_cffi_backend/ctypeptr.py
+++ b/pypy/module/_cffi_backend/ctypeptr.py
@@ -185,7 +185,7 @@
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)
diff --git a/pypy/module/_cffi_backend/ctypestruct.py b/pypy/module/_cffi_backend/ctypestruct.py
--- a/pypy/module/_cffi_backend/ctypestruct.py
+++ b/pypy/module/_cffi_backend/ctypestruct.py
@@ -25,7 +25,6 @@
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):
diff --git a/pypy/module/_cffi_backend/test/_backend_test_c.py b/pypy/module/_cffi_backend/test/_backend_test_c.py
--- a/pypy/module/_cffi_backend/test/_backend_test_c.py
+++ b/pypy/module/_cffi_backend/test/_backend_test_c.py
@@ -641,6 +641,8 @@
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 *'>"
@@ -648,7 +650,7 @@
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 *'>"
@@ -657,7 +659,7 @@
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
@@ -689,7 +691,7 @@
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
@@ -708,7 +710,7 @@
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
@@ -728,7 +730,7 @@
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()))
@@ -744,7 +746,7 @@
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)])
@@ -758,7 +760,7 @@
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),
@@ -792,7 +794,7 @@
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]])
@@ -803,7 +805,7 @@
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)])
@@ -832,7 +834,7 @@
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)
@@ -937,7 +939,7 @@
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)])
@@ -953,7 +955,7 @@
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)])
@@ -965,7 +967,7 @@
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),
@@ -985,7 +987,7 @@
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)
@@ -1023,7 +1025,7 @@
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)
@@ -1048,7 +1050,7 @@
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),
@@ -1221,7 +1223,7 @@
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)])
@@ -1238,7 +1240,7 @@
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),
@@ -1275,26 +1277,27 @@
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>"
@@ -1308,27 +1311,27 @@
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])
@@ -1432,7 +1435,7 @@
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),
@@ -1455,7 +1458,7 @@
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)])
@@ -1485,14 +1488,14 @@
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
@@ -1561,7 +1564,7 @@
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'])
@@ -1601,7 +1604,7 @@
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])
@@ -1619,7 +1622,7 @@
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])
@@ -1697,7 +1700,7 @@
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)
@@ -1714,7 +1717,7 @@
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)
@@ -1725,7 +1728,7 @@
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)
@@ -1735,7 +1738,7 @@
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)
@@ -1745,7 +1748,7 @@
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)
@@ -1754,7 +1757,7 @@
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)])
@@ -1766,7 +1769,7 @@
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)
@@ -1775,7 +1778,7 @@
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)
@@ -1785,7 +1788,7 @@
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)
@@ -1795,7 +1798,7 @@
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)
@@ -1818,7 +1821,7 @@
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)])
@@ -1845,7 +1848,7 @@
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)])
@@ -1957,7 +1960,7 @@
# 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),
@@ -1977,7 +1980,7 @@
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)])
@@ -2164,7 +2167,7 @@
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]
@@ -2183,7 +2186,7 @@
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")
@@ -2192,7 +2195,7 @@
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)])
@@ -2308,7 +2311,7 @@
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)
@@ -2320,8 +2323,8 @@
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),
@@ -2353,12 +2356,12 @@
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
@@ -2366,7 +2369,7 @@
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)
@@ -2424,7 +2427,7 @@
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),
@@ -2440,14 +2443,14 @@
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),
@@ -2508,7 +2511,7 @@
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)
@@ -2540,7 +2543,7 @@
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)
@@ -2563,7 +2566,7 @@
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)
@@ -2762,7 +2765,7 @@
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),
@@ -2775,7 +2778,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)
@@ -2790,7 +2793,7 @@
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),
diff --git a/pypy/module/_rawffi/array.py b/pypy/module/_rawffi/array.py
--- a/pypy/module/_rawffi/array.py
+++ b/pypy/module/_rawffi/array.py
@@ -13,19 +13,9 @@
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):
@@ -57,7 +47,7 @@
" 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)
@@ -118,7 +108,7 @@
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):
@@ -136,7 +126,7 @@
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):
diff --git a/pypy/module/_rawffi/callback.py b/pypy/module/_rawffi/callback.py
--- a/pypy/module/_rawffi/callback.py
+++ b/pypy/module/_rawffi/callback.py
@@ -2,7 +2,7 @@
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)
@@ -40,7 +40,7 @@
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()),
diff --git a/pypy/module/_rawffi/interp_rawffi.py b/pypy/module/_rawffi/interp_rawffi.py
--- a/pypy/module/_rawffi/interp_rawffi.py
+++ b/pypy/module/_rawffi/interp_rawffi.py
@@ -5,6 +5,7 @@
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
@@ -43,6 +44,8 @@
}
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
@@ -239,6 +242,52 @@
)
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")
diff --git a/pypy/module/_rawffi/structure.py b/pypy/module/_rawffi/structure.py
--- a/pypy/module/_rawffi/structure.py
+++ b/pypy/module/_rawffi/structure.py
@@ -12,10 +12,13 @@
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)
@@ -260,10 +263,17 @@
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])
@@ -279,20 +289,20 @@
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:
@@ -301,13 +311,16 @@
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
diff --git a/pypy/module/_rawffi/test/test__rawffi.py b/pypy/module/_rawffi/test/test__rawffi.py
--- a/pypy/module/_rawffi/test/test__rawffi.py
+++ b/pypy/module/_rawffi/test/test__rawffi.py
@@ -1,6 +1,6 @@
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
@@ -48,12 +48,12 @@
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;
@@ -175,7 +175,7 @@
inp.y = inp.x * 100;
return inp;
}
-
+
'''))
symbols = """get_char char_check get_raw_pointer
add_shorts
@@ -194,7 +194,7 @@
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
@@ -211,6 +211,7 @@
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
@@ -438,7 +439,7 @@
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):
@@ -464,6 +465,20 @@
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),
@@ -486,6 +501,60 @@
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)])
@@ -571,7 +640,7 @@
res = pass_ll(arg1)
assert res[0] == 1<<42
arg1.free()
-
+
def test_callback(self):
import _rawffi
import struct
@@ -680,9 +749,20 @@
def test_sizes_and_alignments(self):
import _rawffi
for k, (s, a) in self.sizes_and_alignments.iteritems():
+ print k,s,a
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)
@@ -970,7 +1050,7 @@
assert res.y == 33
assert s2h.x == 7
assert s2h.y == 11
-
+
s2h.free()
def test_ret_struct_containing_array(self):
@@ -1029,7 +1109,7 @@
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()]))
diff --git a/pypy/module/cpyext/unicodeobject.py b/pypy/module/cpyext/unicodeobject.py
--- a/pypy/module/cpyext/unicodeobject.py
+++ b/pypy/module/cpyext/unicodeobject.py
@@ -13,7 +13,7 @@
from pypy.module.sys.interp_encoding import setdefaultencoding
from pypy.module._codecs.interp_codecs import CodecState
from pypy.objspace.std import unicodeobject
-from rpython.rlib import runicode
+from rpython.rlib import rstring, runicode
from rpython.tool.sourcetools import func_renamer
import sys
@@ -684,12 +684,9 @@
str = space.unicode_w(w_str)
substr = space.unicode_w(w_substr)
if rffi.cast(lltype.Signed, direction) <= 0:
- w_ret = space.call_method(w_str, "startswith", w_substr,
- space.wrap(start), space.wrap(end))
+ return rstring.startswith(str, substr, start, end)
else:
- w_ret = space.call_method(w_str, "endswith", w_substr,
- space.wrap(start), space.wrap(end))
- return space.int_w(w_ret)
+ return rstring.endswith(str, substr, start, end)
@cpython_api([PyObject, PyObject, Py_ssize_t, Py_ssize_t], Py_ssize_t, error=-1)
def PyUnicode_Count(space, w_str, w_substr, start, end):
diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py
--- a/pypy/module/micronumpy/interp_boxes.py
+++ b/pypy/module/micronumpy/interp_boxes.py
@@ -235,6 +235,11 @@
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")
@@ -501,6 +506,7 @@
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,
diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py
--- a/pypy/module/micronumpy/interp_numarray.py
+++ b/pypy/module/micronumpy/interp_numarray.py
@@ -558,9 +558,27 @@
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(
@@ -975,6 +993,7 @@
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),
diff --git a/pypy/module/micronumpy/loop.py b/pypy/module/micronumpy/loop.py
--- a/pypy/module/micronumpy/loop.py
+++ b/pypy/module/micronumpy/loop.py
@@ -173,7 +173,7 @@
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):
@@ -188,7 +188,7 @@
return out
axis_reduce__driver = jit.JitDriver(name='numpy_axis_reduce',
- greens=['shapelen',
+ greens=['shapelen',
'func', 'dtype',
'identity'],
reds='auto')
@@ -228,7 +228,7 @@
arg_driver = jit.JitDriver(name='numpy_' + op_name,
greens = ['shapelen', 'dtype'],
reds = 'auto')
-
+
def argmin_argmax(arr):
result = 0
idx = 1
@@ -265,7 +265,7 @@
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)
@@ -283,9 +283,9 @@
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)
@@ -355,7 +355,7 @@
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()
@@ -572,6 +572,21 @@
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')
@@ -613,4 +628,4 @@
out_iter.setitem(arr.getitem_index(space, indexes))
iter.next()
out_iter.next()
-
+
diff --git a/pypy/module/micronumpy/test/test_scalar.py b/pypy/module/micronumpy/test/test_scalar.py
--- a/pypy/module/micronumpy/test/test_scalar.py
+++ b/pypy/module/micronumpy/test/test_scalar.py
@@ -21,3 +21,19 @@
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'"
+
diff --git a/pypy/module/micronumpy/test/test_ufuncs.py b/pypy/module/micronumpy/test/test_ufuncs.py
--- a/pypy/module/micronumpy/test/test_ufuncs.py
+++ b/pypy/module/micronumpy/test/test_ufuncs.py
@@ -286,7 +286,7 @@
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
@@ -334,6 +334,23 @@
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
@@ -364,7 +381,7 @@
assert b[i] == res
def test_exp2(self):
- import math
+ import math
from numpypy import array, exp2
inf = float('inf')
ninf = -float('inf')
@@ -759,8 +776,8 @@
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
@@ -864,7 +881,7 @@
#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.
diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py
--- a/pypy/module/micronumpy/types.py
+++ b/pypy/module/micronumpy/types.py
@@ -37,7 +37,7 @@
return self.box(
func(
self,
- self.for_computation(raw)
+ self.for_computation(raw),
)
)
return dispatcher
@@ -521,6 +521,23 @@
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
@@ -798,6 +815,16 @@
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:
@@ -1354,6 +1381,15 @@
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):
diff --git a/pypy/module/mmap/interp_mmap.py b/pypy/module/mmap/interp_mmap.py
--- a/pypy/module/mmap/interp_mmap.py
+++ b/pypy/module/mmap/interp_mmap.py
@@ -2,8 +2,9 @@
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.typedef import TypeDef
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
@@ -20,13 +21,14 @@
self.mmap.close()
def read_byte(self):
+ self.check_valid()
try:
return self.space.wrap(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.wrap(self.mmap.readline())
@unwrap_spec(num=int)
@@ -36,6 +38,7 @@
@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
@@ -49,6 +52,7 @@
@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
@@ -62,16 +66,18 @@
@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:
@@ -79,41 +85,40 @@
@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=str)
def write_byte(self, byte):
+ self.check_valid()
+ self.check_writeable()
try:
self.mmap.write_byte(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):
@@ -136,28 +141,19 @@
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()
@@ -166,6 +162,8 @@
start, stop, step = space.decode_index(w_index, self.mmap.size)
if step == 0: # index only
return space.wrap(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)])
@@ -189,15 +187,16 @@
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))
if rmmap._POSIX:
@@ -213,10 +212,8 @@
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:
@@ -232,10 +229,8 @@
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",
@@ -275,5 +270,64 @@
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)
diff --git a/pypy/module/mmap/test/test_mmap.py b/pypy/module/mmap/test/test_mmap.py
--- a/pypy/module/mmap/test/test_mmap.py
+++ b/pypy/module/mmap/test/test_mmap.py
@@ -550,6 +550,24 @@
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", "w+")
diff --git a/pypy/module/sys/initpath.py b/pypy/module/sys/initpath.py
--- a/pypy/module/sys/initpath.py
+++ b/pypy/module/sys/initpath.py
@@ -45,10 +45,7 @@
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:
diff --git a/pypy/module/test_lib_pypy/cffi_tests/backend_tests.py b/pypy/module/test_lib_pypy/cffi_tests/backend_tests.py
--- a/pypy/module/test_lib_pypy/cffi_tests/backend_tests.py
+++ b/pypy/module/test_lib_pypy/cffi_tests/backend_tests.py
@@ -990,7 +990,7 @@
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
@@ -1300,9 +1300,9 @@
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())
diff --git a/pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py b/pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py
--- a/pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py
+++ b/pypy/module/test_lib_pypy/cffi_tests/test_ffi_backend.py
@@ -179,3 +179,9 @@
'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 *' ")
diff --git a/pypy/module/test_lib_pypy/cffi_tests/test_verify.py b/pypy/module/test_lib_pypy/cffi_tests/test_verify.py
--- a/pypy/module/test_lib_pypy/cffi_tests/test_verify.py
+++ b/pypy/module/test_lib_pypy/cffi_tests/test_verify.py
@@ -1442,7 +1442,7 @@
"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()
diff --git a/pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py b/pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
--- a/pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
+++ b/pypy/module/test_lib_pypy/ctypes_tests/test_bitfields.py
@@ -66,6 +66,10 @@
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),
@@ -75,8 +79,8 @@
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:
diff --git a/pypy/objspace/std/boolobject.py b/pypy/objspace/std/boolobject.py
--- a/pypy/objspace/std/boolobject.py
+++ b/pypy/objspace/std/boolobject.py
@@ -50,10 +50,6 @@
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
-
More information about the pypy-commit
mailing list