Beispiel #1
0
def min_max_acc_method(size, signed):
    if signed:
        min = -(2**(8 * size - 1))
        max = (2**(8 * size - 1)) - 1
        if size <= native_int_size:
            accept_method = 'accept_int_arg'
            min = int(min)
            max = int(max)
        else:
            accept_method = 'accept_longlong_arg'
            min = r_longlong(min)
            max = r_longlong(max)
    else:
        min = 0
        max = (2**(8 * size)) - 1
        if size < native_int_size:
            accept_method = 'accept_int_arg'
        elif size == native_int_size:
            accept_method = 'accept_uint_arg'
            min = r_uint(min)
            max = r_uint(max)
        else:
            accept_method = 'accept_ulonglong_arg'
            min = r_ulonglong(min)
            max = r_ulonglong(max)
    return min, max, accept_method
Beispiel #2
0
def min_max_acc_method(size, signed):
    if signed:
        min = -(2 ** (8*size-1))
        max = (2 ** (8*size-1)) - 1
        if size <= native_int_size:
            accept_method = 'accept_int_arg'
            min = int(min)
            max = int(max)
        else:
            accept_method = 'accept_longlong_arg'
            min = r_longlong(min)
            max = r_longlong(max)
    else:
        min = 0
        max = (2 ** (8*size)) - 1
        if size < native_int_size:
            accept_method = 'accept_int_arg'
        elif size == native_int_size:
            accept_method = 'accept_uint_arg'
            min = r_uint(min)
            max = r_uint(max)
        else:
            accept_method = 'accept_ulonglong_arg'
            min = r_ulonglong(min)
            max = r_ulonglong(max)
    return min, max, accept_method
Beispiel #3
0
 def f(n1, n2):
     # n == 30002000000000
     n = (r_ulonglong(n1) << 32) | r_ulonglong(n2)
     compare(n, 6985, 1653437440)
     compare(n < n, 0, 0)
     compare(n <= n, 0, 1)
     compare(n == n, 0, 1)
     compare(n != n, 0, 0)
     compare(n > n, 0, 0)
     compare(n >= n, 0, 1)
     o = (r_ulonglong(n1) << 32) | r_ulonglong(r_uint(n2) + 1000000000)
     compare(o, 6985, -1641529856)
     compare(n < o, 0, 1)  # low word differs
     compare(n <= o, 0, 1)
     compare(o < n, 0, 0)
     compare(o <= n, 0, 0)
     compare(n > o, 0, 0)
     compare(n >= o, 0, 0)
     compare(o > n, 0, 1)
     compare(o >= n, 0, 1)
     compare(n == o, 0, 0)
     compare(n != o, 0, 1)
     p = ~n
     compare(n < p, 0, 1)  # high word differs
     compare(n <= p, 0, 1)
     compare(p < n, 0, 0)
     compare(p <= n, 0, 0)
     compare(n > p, 0, 0)
     compare(n >= p, 0, 0)
     compare(p > n, 0, 1)
     compare(p >= n, 0, 1)
     compare(n == p, 0, 0)
     compare(n != p, 0, 1)
     return 1
Beispiel #4
0
 def malloc_fixedsize_slowpath(size):
     gcref = llop1.do_malloc_fixedsize_clear(llmemory.GCREF, 0, size,
                                             True, False, False)
     res = rffi.cast(lltype.Signed, gcref)
     nurs_free = llop1.gc_adr_of_nursery_free(
         llmemory.Address).signed[0]
     return r_ulonglong(nurs_free) << 32 | r_ulonglong(r_uint(res))
Beispiel #5
0
 def f(n1, n2):
     # n == 30002000000000
     n = (r_ulonglong(n1) << 32) | r_ulonglong(n2)
     compare(n, 6985, 1653437440)
     compare(n < n,  0, 0)
     compare(n <= n, 0, 1)
     compare(n == n, 0, 1)
     compare(n != n, 0, 0)
     compare(n >  n, 0, 0)
     compare(n >= n, 0, 1)
     o = (r_ulonglong(n1) << 32) | r_ulonglong(r_uint(n2) + 1000000000)
     compare(o, 6985, -1641529856)
     compare(n <  o, 0, 1)     # low word differs
     compare(n <= o, 0, 1)
     compare(o <  n, 0, 0)
     compare(o <= n, 0, 0)
     compare(n >  o, 0, 0)
     compare(n >= o, 0, 0)
     compare(o >  n, 0, 1)
     compare(o >= n, 0, 1)
     compare(n == o, 0, 0)
     compare(n != o, 0, 1)
     p = ~n
     compare(n <  p, 0, 1)     # high word differs
     compare(n <= p, 0, 1)
     compare(p <  n, 0, 0)
     compare(p <= n, 0, 0)
     compare(n >  p, 0, 0)
     compare(n >= p, 0, 0)
     compare(p >  n, 0, 1)
     compare(p >= n, 0, 1)
     compare(n == p, 0, 0)
     compare(n != p, 0, 1)
     return 1
Beispiel #6
0
 def malloc_slowpath(size):
     from pypy.rlib.rarithmetic import r_ulonglong
     assert size == 8
     nadr = rffi.cast(lltype.Signed, self.nursery)
     self.addrs[0] = 99999  # should be overridden by the caller
     return ((r_ulonglong(nadr + size) << 32) |  # this part in edx
             r_ulonglong(nadr))  # this part in eax
Beispiel #7
0
 def malloc_slowpath(size):
     from pypy.rlib.rarithmetic import r_ulonglong
     assert size == 8
     nadr = rffi.cast(lltype.Signed, self.nursery)
     self.addrs[0] = 99999    # should be overridden by the caller
     return ((r_ulonglong(nadr + size) << 32) |     # this part in edx
              r_ulonglong(nadr))                    # this part in eax
Beispiel #8
0
 def test_ulonglongmask(self):
     assert rbigint.fromlong(-1).ulonglongmask() == r_ulonglong(-1)
     assert rbigint.fromlong(0).ulonglongmask() == r_ulonglong(0)
     assert (rbigint.fromlong(sys.maxint).ulonglongmask() == r_ulonglong(
         sys.maxint))
     assert (rbigint.fromlong(9**50).ulonglongmask() == r_ulonglong(9**50))
     assert (
         rbigint.fromlong(-9**50).ulonglongmask() == r_ulonglong(-9**50))
Beispiel #9
0
def test_ullongoperations():
    tests = adapt_tests(general_tests, r_ulonglong, UnsignedLongLong, "ullong") + [
        # binary wraparounds
        ("ullong_add", UnsignedLongLong,
                r_ulonglong(r_ulonglong.MASK), r_ulonglong(10)),
    ]
    for t in tests:
        yield optest, t
Beispiel #10
0
 def f(x):
     if x == r_ulonglong(3):
         return 9
     elif x == r_ulonglong(9):
         return 27
     elif x == r_ulonglong(27):
         return 3
     return 0
Beispiel #11
0
 def f(x):
     if x == r_ulonglong(3):
         return 9
     elif x == r_ulonglong(9):
         return 27
     elif x == r_ulonglong(27):
         return 3
     return 0
 def test_ulonglongmask(self):
     assert rbigint.fromlong(-1).ulonglongmask() == r_ulonglong(-1)
     assert rbigint.fromlong(0).ulonglongmask() == r_ulonglong(0)
     assert (rbigint.fromlong(sys.maxint).ulonglongmask() ==
             r_ulonglong(sys.maxint))
     assert (rbigint.fromlong(9**50).ulonglongmask() ==
             r_ulonglong(9**50))
     assert (rbigint.fromlong(-9**50).ulonglongmask() ==
             r_ulonglong(-9**50))
Beispiel #13
0
 def malloc_fixedsize_slowpath(size):
     try:
         gcref = llop1.do_malloc_fixedsize_clear(llmemory.GCREF,
                                     0, size, True, False, False)
     except MemoryError:
         fatalerror("out of memory (from JITted code)")
         return r_ulonglong(0)
     res = rffi.cast(lltype.Signed, gcref)
     nurs_free = llop1.gc_adr_of_nursery_free(llmemory.Address).signed[0]
     return r_ulonglong(nurs_free) << 32 | r_ulonglong(r_uint(res))
Beispiel #14
0
 def f(n1, n2, ii):
     # n == 30002000000000, ii == 42
     n = (r_ulonglong(n1) << 32) | r_ulonglong(n2)
     compare(n << 1, 13970, -988092416)
     compare(r_ulonglong(5) << ii, 5120, 0)
     compare(n >> 1, 3492, -1320764928)
     compare(n >> 42, 0, 6)
     p = ~n
     compare(p >> 1, 2147480155, 1320764927)
     compare(p >> 42, 0, 4194297)
     return 1
Beispiel #15
0
 def malloc_fixedsize_slowpath(size):
     try:
         gcref = llop1.do_malloc_fixedsize_clear(
             llmemory.GCREF, 0, size, True, False, False)
     except MemoryError:
         fatalerror("out of memory (from JITted code)")
         return r_ulonglong(0)
     res = rffi.cast(lltype.Signed, gcref)
     nurs_free = llop1.gc_adr_of_nursery_free(
         llmemory.Address).signed[0]
     return r_ulonglong(nurs_free) << 32 | r_ulonglong(r_uint(res))
Beispiel #16
0
 def f(n1, n2, ii):
     # n == 30002000000000, ii == 42
     n = (r_ulonglong(n1) << 32) | r_ulonglong(n2)
     compare(n << 1, 13970, -988092416)
     compare(r_ulonglong(5) << ii, 5120, 0)
     compare(n >> 1, 3492, -1320764928)
     compare(n >> 42, 0, 6)
     p = ~n
     compare(p >> 1, 2147480155, 1320764927)
     compare(p >> 42, 0, 4194297)
     return 1
Beispiel #17
0
def expose_value_as_rpython(value):
    if intmask(value) == value:
        return value
    if r_uint(value) == value:
        return r_uint(value)
    try:
        if r_longlong(value) == value:
            return r_longlong(value)
    except OverflowError:
        pass
    if r_ulonglong(value) == value:
        return r_ulonglong(value)
    raise OverflowError("value %d does not fit into any RPython integer type" % (value,))
Beispiel #18
0
def expose_value_as_rpython(value):
    if intmask(value) == value:
        return value
    if r_uint(value) == value:
        return r_uint(value)
    try:
        if r_longlong(value) == value:
            return r_longlong(value)
    except OverflowError:
        pass
    if r_ulonglong(value) == value:
        return r_ulonglong(value)
    raise OverflowError("value %d does not fit into any RPython integer type"
                        % (value,))
Beispiel #19
0
 def test_truth_value(self):
     bigzero = r_ulonglong(0)
     big = r_ulonglong(2L**42)
     def func(n, z):
         assert c_int(n)
         assert not c_int(z)
         assert c_int(-1)
         assert not c_byte(z)
         assert not c_char(chr(z))
         # assert not c_float(z)
         assert not c_double(z)
         assert not c_ulonglong(bigzero)
         assert c_ulonglong(big)
     interpret(func, [17, 0])
Beispiel #20
0
def test_cast_float_to_ulonglong():
    f = 12350000000000000000.0
    py.test.raises(OverflowError, r_longlong, f)
    r_longlong(f / 2)   # does not raise OverflowError
    #
    x = llop.cast_float_to_ulonglong(lltype.UnsignedLongLong, f)
    assert x == r_ulonglong(f)
Beispiel #21
0
def test_wraplonglongs():
    space = CPyObjSpace()
    w = space.wrap
    w_res = space.add(w(r_longlong(1)), w(r_ulonglong(1)))
    assert space.eq_w(w_res, w(2))
    res = space.int_w(w_res)
    assert res == 2
def test_wrap():
    def _is(box1, box2):
        return box1.__class__ == box2.__class__ and box1.value == box2.value

    p = lltype.malloc(lltype.GcStruct("S"))
    po = lltype.cast_opaque_ptr(llmemory.GCREF, p)
    assert _is(wrap(None, 42), BoxInt(42))
    assert _is(wrap(None, 42.5), boxfloat(42.5))
    assert _is(wrap(None, p), BoxPtr(po))
    assert _is(wrap(None, 42, in_const_box=True), ConstInt(42))
    assert _is(wrap(None, 42.5, in_const_box=True), constfloat(42.5))
    assert _is(wrap(None, p, in_const_box=True), ConstPtr(po))
    if longlong.supports_longlong:
        import sys
        from pypy.rlib.rarithmetic import r_longlong, r_ulonglong

        value = r_longlong(-sys.maxint * 17)
        assert _is(wrap(None, value), BoxFloat(value))
        assert _is(wrap(None, value, in_const_box=True), ConstFloat(value))
        value_unsigned = r_ulonglong(-sys.maxint * 17)
        assert _is(wrap(None, value_unsigned), BoxFloat(value))
    sfval = r_singlefloat(42.5)
    ival = longlong.singlefloat2int(sfval)
    assert _is(wrap(None, sfval), BoxInt(ival))
    assert _is(wrap(None, sfval, in_const_box=True), ConstInt(ival))
Beispiel #23
0
def test_cast_float_to_ulonglong():
    f = 12350000000000000000.0
    py.test.raises(OverflowError, r_longlong, f)
    r_longlong(f / 2)  # does not raise OverflowError
    #
    x = llop.cast_float_to_ulonglong(lltype.UnsignedLongLong, f)
    assert x == r_ulonglong(f)
Beispiel #24
0
    def test_longlongmask(self):
        def f(x=r_ulonglong):
            try:
                return longlongmask(x)
            except ValueError:
                return 0

        res = self.interpret(f, [r_ulonglong(5)])
        assert type(res) is r_int64 and res == 5
Beispiel #25
0
 def test_struct_fields_longlong(self):
     POINT = lltype.Struct('POINT', ('x', rffi.LONGLONG),
                           ('y', rffi.ULONGLONG))
     y_ofs = 8
     p = lltype.malloc(POINT, flavor='raw')
     p.x = r_longlong(123)
     p.y = r_ulonglong(456)
     addr = rffi.cast(rffi.VOIDP, p)
     assert struct_getfield_longlong(types.slonglong, addr, 0) == 123
     assert struct_getfield_longlong(types.ulonglong, addr, y_ofs) == 456
     #
     v = rffi.cast(lltype.SignedLongLong, r_ulonglong(9223372036854775808))
     struct_setfield_longlong(types.slonglong, addr, 0, v)
     struct_setfield_longlong(types.ulonglong, addr, y_ofs, r_longlong(-1))
     assert p.x == -9223372036854775808
     assert rffi.cast(lltype.UnsignedLongLong, p.y) == 18446744073709551615
     #
     lltype.free(p, flavor='raw')
Beispiel #26
0
    def test_longlongmask(self):
        def f(x=r_ulonglong):
            try:
                return longlongmask(x)
            except ValueError:
                return 0

        res = self.interpret(f, [r_ulonglong(5)])
        assert type(res) is r_int64 and res == 5
Beispiel #27
0
 def test_cast(self):
     def llfn(v):
         return rffi.cast(rffi.VOIDP, v)
     res = self.interpret(llfn, [r_ulonglong(0)])
     assert res == lltype.nullptr(rffi.VOIDP.TO)
     def llfn(v):
         return rffi.cast(rffi.LONGLONG, v)
     res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
     assert res == 0
     assert isinstance(res, r_longlong)
Beispiel #28
0
def _AsULonglong_mask(v):
    x = r_ulonglong(0)
    i = len(v.digits) - 1
    while i >= 0:
        prev = x
        x = (x << SHIFT) + v.digits[i]
        i -= 1
    if v.sign < 0:
        x = -x
    return x
Beispiel #29
0
 def test_ulonglong_args(self):
     """
         unsigned long long sum_xy_ulonglong(unsigned long long x,
                                             unsigned long long y)
         {
             return x+y;
         }
     """
     maxint64 = 9223372036854775807  # maxint64+1 does not fit into a
     # longlong, but it does into a
     # ulonglong
     libfoo = self.get_libfoo()
     func = (libfoo, 'sum_xy_ulonglong', [types.ulonglong,
                                          types.ulonglong], types.ulonglong)
     x = r_ulonglong(maxint64 + 1)
     y = r_ulonglong(2)
     res = self.call(func, [x, y], rffi.ULONGLONG, jitif=["longlong"])
     expected = maxint64 + 3
     assert res == expected
Beispiel #30
0
 def test_ulonglong_args(self):
     """
         unsigned long long sum_xy_ulonglong(unsigned long long x,
                                             unsigned long long y)
         {
             return x+y;
         }
     """
     maxint64 = 9223372036854775807 # maxint64+1 does not fit into a
                                    # longlong, but it does into a
                                    # ulonglong
     libfoo = self.get_libfoo()
     func = (libfoo, 'sum_xy_ulonglong', [types.ulonglong, types.ulonglong],
             types.ulonglong)
     x = r_ulonglong(maxint64+1)
     y = r_ulonglong(2)
     res = self.call(func, [x, y], rffi.ULONGLONG, jitif=["longlong"])
     expected = maxint64 + 3
     assert res == expected
Beispiel #31
0
def _AsULonglong_mask(v):
    x = r_ulonglong(0)
    i = len(v.digits) - 1
    while i >= 0:
        prev = x
        x = (x << SHIFT) + v.digits[i]
        i -= 1
    if v.sign < 0:
        x = -x
    return x
Beispiel #32
0
def _AsULonglong_ignore_sign(v):
    x = r_ulonglong(0)
    i = len(v.digits) - 1
    while i >= 0:
        prev = x
        x = (x << SHIFT) + v.digits[i]
        if (x >> SHIFT) != prev:
            raise OverflowError(
                "long int too large to convert to unsigned long long int")
        i -= 1
    return x
Beispiel #33
0
def _AsULonglong_ignore_sign(v):
    x = r_ulonglong(0)
    i = v._numdigits() - 1
    while i >= 0:
        prev = x
        x = (x << SHIFT) + v._digit(i)
        if (x >> SHIFT) != prev:
                raise OverflowError(
                    "long int too large to convert to unsigned long long int")
        i -= 1
    return x
Beispiel #34
0
    def _init(self):
        "Initialisation."
        self.count = r_ulonglong(0)  # total number of bytes
        self.input = ""  # pending unprocessed data, < 64 bytes

        # Initial 160 bit message digest (5 times 32 bit).
        self.H0 = r_uint(0x67452301L)
        self.H1 = r_uint(0xEFCDAB89L)
        self.H2 = r_uint(0x98BADCFEL)
        self.H3 = r_uint(0x10325476L)
        self.H4 = r_uint(0xC3D2E1F0L)
Beispiel #35
0
    def _init(self):
        """Set this object to an initial empty state.
        """
        self.count = r_ulonglong(0)   # total number of bytes
        self.input = ""   # pending unprocessed data, < 64 bytes

        # Load magic initialization constants.
        self.A = r_uint(0x67452301L)
        self.B = r_uint(0xefcdab89L)
        self.C = r_uint(0x98badcfeL)
        self.D = r_uint(0x10325476L)
Beispiel #36
0
    def _init(self):
        """Set this object to an initial empty state.
        """
        self.count = r_ulonglong(0)  # total number of bytes
        self.input = ""  # pending unprocessed data, < 64 bytes

        # Load magic initialization constants.
        self.A = r_uint(0x67452301L)
        self.B = r_uint(0xefcdab89L)
        self.C = r_uint(0x98badcfeL)
        self.D = r_uint(0x10325476L)
Beispiel #37
0
 def test_struct_fields_longlong(self):
     POINT = lltype.Struct('POINT',
                           ('x', rffi.LONGLONG),
                           ('y', rffi.ULONGLONG)
                           )
     y_ofs = 8
     p = lltype.malloc(POINT, flavor='raw')
     p.x = r_longlong(123)
     p.y = r_ulonglong(456)
     addr = rffi.cast(rffi.VOIDP, p)
     assert struct_getfield_longlong(types.slonglong, addr, 0) == 123
     assert struct_getfield_longlong(types.ulonglong, addr, y_ofs) == 456
     #
     v = rffi.cast(lltype.SignedLongLong, r_ulonglong(9223372036854775808))
     struct_setfield_longlong(types.slonglong, addr, 0, v)
     struct_setfield_longlong(types.ulonglong, addr, y_ofs, r_longlong(-1))
     assert p.x == -9223372036854775808
     assert rffi.cast(lltype.UnsignedLongLong, p.y) == 18446744073709551615
     #
     lltype.free(p, flavor='raw')
Beispiel #38
0
    def _init(self):
        "Initialisation."
        self.count = r_ulonglong(0)   # total number of bytes
        self.input = ""   # pending unprocessed data, < 64 bytes

        # Initial 160 bit message digest (5 times 32 bit).
        self.H0 = r_uint(0x67452301L)
        self.H1 = r_uint(0xEFCDAB89L)
        self.H2 = r_uint(0x98BADCFEL)
        self.H3 = r_uint(0x10325476L)
        self.H4 = r_uint(0xC3D2E1F0L)
Beispiel #39
0
 def test_truncatedlonglong_w(self):
     space = self.space
     w_value = space.wrap(12)
     res = space.truncatedlonglong_w(w_value)
     assert res == 12
     assert type(res) is r_longlong
     #
     w_value = space.wrap(r_ulonglong(9223372036854775808))
     res = space.truncatedlonglong_w(w_value)
     assert res == -9223372036854775808
     assert type(res) is r_longlong
     #
     w_value = space.wrap(r_ulonglong(18446744073709551615))
     res = space.truncatedlonglong_w(w_value)
     assert res == -1
     assert type(res) is r_longlong
     #
     w_value = space.wrap(r_ulonglong(18446744073709551616))
     res = space.truncatedlonglong_w(w_value)
     assert res == 0
     assert type(res) is r_longlong
 def test_compare_big_ullongs(self):
     bigval = r_ulonglong(9223372036854775808L)
     def fn(x):
         if x > bigval: return 1
         if x == bigval: return 0
         if x < bigval: return -1
         return -2
     
     for val in (bigval-1, bigval, bigval+1):
         expected = fn(val)
         res = self.interpret(fn, [val])
         assert res == expected
Beispiel #41
0
 def test_ulonglong_switch(self):
     def f(x):
         if x == r_ulonglong(3):
             return 9
         elif x == r_ulonglong(9):
             return 27
         elif x == r_ulonglong(27):
             return 3
         return 0
     codegenerator = self.CodeGenerator()
     fn = codegenerator.getcompiled(f, [r_ulonglong])
     for x in (0,1,2,3,9,27,48, r_ulonglong(-9)):
         assert fn(x) == f(x)
Beispiel #42
0
    def test_cast(self):
        def llfn(v):
            return rffi.cast(rffi.VOIDP, v)

        res = self.interpret(llfn, [r_ulonglong(0)])
        assert res == lltype.nullptr(rffi.VOIDP.TO)

        def llfn(v):
            return rffi.cast(rffi.LONGLONG, v)

        res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
        assert res == 0
        assert isinstance(res, r_longlong)
Beispiel #43
0
    def test_ulonglong_switch(self):
        def f(x):
            if x == r_ulonglong(3):
                return 9
            elif x == r_ulonglong(9):
                return 27
            elif x == r_ulonglong(27):
                return 3
            return 0

        codegenerator = self.CodeGenerator()
        fn = codegenerator.getcompiled(f, [r_ulonglong])
        for x in (0, 1, 2, 3, 9, 27, 48, r_ulonglong(-9)):
            assert fn(x) == f(x)
Beispiel #44
0
 def test_ulonglong_args(self):
     """
         unsigned long long sum_xy_ulonglong(unsigned long long x,
                                             unsigned long long y)
         {
             return x+y;
         }
     """
     maxint64 = 9223372036854775807 # maxint64+1 does not fit into a
                                    # longlong, but it does into a
                                    # ulonglong
     libfoo = self.get_libfoo()
     func = (libfoo, 'sum_xy_ulonglong', [types.ulonglong, types.ulonglong],
             types.ulonglong)
     x = r_ulonglong(maxint64+1)
     y = r_ulonglong(2)
     res = self.call(func, [x, y], rffi.ULONGLONG, init_result=0)
     if IS_32_BIT:
         # obscure, on 32bit it's really a long long, so it returns a
         # DOUBLE because of the JIT hack
         res = float2longlong(res)
         res = rffi.cast(rffi.ULONGLONG, res)
     expected = maxint64 + 3
     assert res == expected
Beispiel #45
0
def round_to_nearest(x):
    """Python 3 style round:  round a float x to the nearest int, but
    unlike the builtin Python 2.x round function:

      - return an int, not a float
      - do round-half-to-even, not round-half-away-from-zero.

    We assume that x is finite and nonnegative; except wrong results
    if you use this for negative x.

    """
    int_part = r_ulonglong(x)
    frac_part = x - int_part
    if frac_part > 0.5 or frac_part == 0.5 and int_part & 1:
        int_part += 1
    return int_part
Beispiel #46
0
def round_to_nearest(x):
    """Python 3 style round:  round a float x to the nearest int, but
    unlike the builtin Python 2.x round function:

      - return an int, not a float
      - do round-half-to-even, not round-half-away-from-zero.

    We assume that x is finite and nonnegative; except wrong results
    if you use this for negative x.

    """
    int_part = r_ulonglong(x)
    frac_part = x - int_part
    if frac_part > 0.5 or frac_part == 0.5 and int_part & 1:
        int_part += 1
    return int_part
Beispiel #47
0
 def test_r_ulonglong_w(self):
     space = self.space
     w_value = space.wrap(12)
     res = space.r_ulonglong_w(w_value)
     assert res == 12
     assert type(res) is r_ulonglong
     w_value = space.wrap(r_ulonglong(INT32_MAX * 42))
     res = space.r_ulonglong_w(w_value)
     assert res == INT32_MAX * 42
     assert type(res) is r_ulonglong
     w_obj = space.wrap("hello world")
     space.raises_w(space.w_TypeError, space.r_ulonglong_w, w_obj)
     w_obj = space.wrap(-12.34)
     space.raises_w(space.w_TypeError, space.r_ulonglong_w, w_obj)
     w_obj = space.wrap(-12)
     space.raises_w(space.w_ValueError, space.r_ulonglong_w, w_obj)
Beispiel #48
0
 def test_r_ulonglong_w(self):
     space = self.space
     w_value = space.wrap(12)
     res = space.r_ulonglong_w(w_value)
     assert res == 12
     assert type(res) is r_ulonglong
     w_value = space.wrap(r_ulonglong(INT32_MAX * 42))
     res = space.r_ulonglong_w(w_value)
     assert res == INT32_MAX * 42
     assert type(res) is r_ulonglong
     w_obj = space.wrap("hello world")
     space.raises_w(space.w_TypeError, space.r_ulonglong_w, w_obj)
     w_obj = space.wrap(-12.34)
     space.raises_w(space.w_TypeError, space.r_ulonglong_w, w_obj)
     w_obj = space.wrap(-12)
     space.raises_w(space.w_ValueError, space.r_ulonglong_w, w_obj)
Beispiel #49
0
 def wrap(self, x):
     "Wraps the Python value 'x' into one of the wrapper classes."
     # You might notice that this function is rather conspicuously
     # not RPython.  We can get away with this because the function
     # is specialized (see after the function body).  Also worth
     # noting is that the isinstance's involving integer types
     # behave rather differently to how you might expect during
     # annotation (see pypy/annotation/builtin.py)
     if x is None:
         return self.w_None
     if isinstance(x, model.W_Object):
         raise TypeError, "attempt to wrap already wrapped object: %s" % (
             x, )
     if isinstance(x, OperationError):
         raise TypeError, ("attempt to wrap already wrapped exception: %s" %
                           (x, ))
     if isinstance(x, int):
         if isinstance(x, bool):
             return self.newbool(x)
         else:
             return self.newint(x)
     if isinstance(x, str):
         return wrapstr(self, x)
     if isinstance(x, unicode):
         return wrapunicode(self, x)
     if isinstance(x, float):
         return W_FloatObject(x)
     if isinstance(x, Wrappable):
         w_result = x.__spacebind__(self)
         #print 'wrapping', x, '->', w_result
         return w_result
     if isinstance(x, base_int):
         if self.config.objspace.std.withsmalllong:
             from pypy.objspace.std.smalllongobject import W_SmallLongObject
             from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
             from pypy.rlib.rarithmetic import longlongmax
             if (not isinstance(x, r_ulonglong)
                     or x <= r_ulonglong(longlongmax)):
                 return W_SmallLongObject(r_longlong(x))
         x = widen(x)
         if isinstance(x, int):
             return self.newint(x)
         else:
             return W_LongObject.fromrarith_int(x)
     return self._wrap_not_rpython(x)
Beispiel #50
0
def test_assemble_llong_consts():
    if sys.maxint > 2147483647:
        py.test.skip("only for 32-bit platforms")
    from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
    ssarepr = SSARepr("test")
    ssarepr.insns = [
        ('float_return', Constant(r_longlong(-18000000000000000),
                                  lltype.SignedLongLong)),
        ('float_return', Constant(r_ulonglong(9900000000000000000),
                                  lltype.UnsignedLongLong)),
        ]
    assembler = Assembler()
    jitcode = assembler.assemble(ssarepr)
    assert jitcode.code == ("\x00\xFF"
                            "\x00\xFE")
    assert assembler.insns == {'float_return/f': 0}
    assert jitcode.constants_f == [r_longlong(-18000000000000000),
                                   r_longlong(-8546744073709551616)]
Beispiel #51
0
 def wrap(self, x):
     "Wraps the Python value 'x' into one of the wrapper classes."
     # You might notice that this function is rather conspicuously
     # not RPython.  We can get away with this because the function
     # is specialized (see after the function body).  Also worth
     # noting is that the isinstance's involving integer types
     # behave rather differently to how you might expect during
     # annotation (see pypy/annotation/builtin.py)
     if x is None:
         return self.w_None
     if isinstance(x, model.W_Object):
         raise TypeError, "attempt to wrap already wrapped object: %s"%(x,)
     if isinstance(x, OperationError):
         raise TypeError, ("attempt to wrap already wrapped exception: %s"%
                           (x,))
     if isinstance(x, int):
         if isinstance(x, bool):
             return self.newbool(x)
         else:
             return self.newint(x)
     if isinstance(x, str):
         return wrapstr(self, x)
     if isinstance(x, unicode):
         return wrapunicode(self, x)
     if isinstance(x, float):
         return W_FloatObject(x)
     if isinstance(x, Wrappable):
         w_result = x.__spacebind__(self)
         #print 'wrapping', x, '->', w_result
         return w_result
     if isinstance(x, base_int):
         if self.config.objspace.std.withsmalllong:
             from pypy.objspace.std.smalllongobject import W_SmallLongObject
             from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
             from pypy.rlib.rarithmetic import longlongmax
             if (not isinstance(x, r_ulonglong)
                 or x <= r_ulonglong(longlongmax)):
                 return W_SmallLongObject(r_longlong(x))
         x = widen(x)
         if isinstance(x, int):
             return self.newint(x)
         else:
             return W_LongObject.fromrarith_int(x)
     return self._wrap_not_rpython(x)
Beispiel #52
0
def test_assemble_llong_consts():
    if sys.maxint > 2147483647:
        py.test.skip("only for 32-bit platforms")
    from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
    ssarepr = SSARepr("test")
    ssarepr.insns = [
        ('float_return',
         Constant(r_longlong(-18000000000000000), lltype.SignedLongLong)),
        ('float_return',
         Constant(r_ulonglong(9900000000000000000), lltype.UnsignedLongLong)),
    ]
    assembler = Assembler()
    jitcode = assembler.assemble(ssarepr)
    assert jitcode.code == ("\x00\xFF" "\x00\xFE")
    assert assembler.insns == {'float_return/f': 0}
    assert jitcode.constants_f == [
        r_longlong(-18000000000000000),
        r_longlong(-8546744073709551616)
    ]
Beispiel #53
0
def float_unpack(Q, size):
    """Convert a 32-bit or 64-bit integer created
    by float_pack into a Python float."""

    if size == 8:
        MIN_EXP = -1021  # = sys.float_info.min_exp
        MAX_EXP = 1024  # = sys.float_info.max_exp
        MANT_DIG = 53  # = sys.float_info.mant_dig
        BITS = 64
    elif size == 4:
        MIN_EXP = -125  # C's FLT_MIN_EXP
        MAX_EXP = 128  # FLT_MAX_EXP
        MANT_DIG = 24  # FLT_MANT_DIG
        BITS = 32
    else:
        raise ValueError("invalid size value")

    if not objectmodel.we_are_translated():
        # This tests generates wrong code when translated:
        # with gcc, shifting a 64bit int by 64 bits does
        # not change the value.
        if Q >> BITS:
            raise ValueError("input out of range")

    # extract pieces
    one = r_ulonglong(1)
    sign = rarithmetic.intmask(Q >> BITS - 1)
    exp = rarithmetic.intmask((Q & ((one << BITS - 1) -
                                    (one << MANT_DIG - 1))) >> MANT_DIG - 1)
    mant = Q & ((one << MANT_DIG - 1) - 1)

    if exp == MAX_EXP - MIN_EXP + 2:
        # nan or infinity
        result = rfloat.NAN if mant else rfloat.INFINITY
    elif exp == 0:
        # subnormal or zero
        result = math.ldexp(mant, MIN_EXP - MANT_DIG)
    else:
        # normal
        mant += one << MANT_DIG - 1
        result = math.ldexp(mant, exp + MIN_EXP - MANT_DIG - 1)
    return -result if sign else result
Beispiel #54
0
 def test_cast(self):
     def llfn(v):
         return rffi.cast(rffi.VOIDP, v)
     res = self.interpret(llfn, [r_ulonglong(0)])
     assert res == lltype.nullptr(rffi.VOIDP.TO)
     #
     def llfn(v):
         return rffi.cast(rffi.LONGLONG, v)
     res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
     assert res == 0
     if r_longlong is not r_int:
         assert isinstance(res, r_longlong)
     else:
         assert is_valid_int(res)
     #
     def llfn(v):
         return rffi.cast(rffi.ULONGLONG, v)
     res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
     assert res == 0
     assert isinstance(res, r_ulonglong)
Beispiel #55
0
def float_unpack(Q, size):
    """Convert a 32-bit or 64-bit integer created
    by float_pack into a Python float."""

    if size == 8:
        MIN_EXP = -1021  # = sys.float_info.min_exp
        MAX_EXP = 1024   # = sys.float_info.max_exp
        MANT_DIG = 53    # = sys.float_info.mant_dig
        BITS = 64
    elif size == 4:
        MIN_EXP = -125   # C's FLT_MIN_EXP
        MAX_EXP = 128    # FLT_MAX_EXP
        MANT_DIG = 24    # FLT_MANT_DIG
        BITS = 32
    else:
        raise ValueError("invalid size value")

    if not objectmodel.we_are_translated():
        # This tests generates wrong code when translated:
        # with gcc, shifting a 64bit int by 64 bits does
        # not change the value.
        if Q >> BITS:
            raise ValueError("input out of range")

    # extract pieces
    one = r_ulonglong(1)
    sign = rarithmetic.intmask(Q >> BITS - 1)
    exp = rarithmetic.intmask((Q & ((one << BITS - 1) - (one << MANT_DIG - 1))) >> MANT_DIG - 1)
    mant = Q & ((one << MANT_DIG - 1) - 1)

    if exp == MAX_EXP - MIN_EXP + 2:
        # nan or infinity
        result = rfloat.NAN if mant else rfloat.INFINITY
    elif exp == 0:
        # subnormal or zero
        result = math.ldexp(mant, MIN_EXP - MANT_DIG)
    else:
        # normal
        mant += one << MANT_DIG - 1
        result = math.ldexp(mant, exp + MIN_EXP - MANT_DIG - 1)
    return -result if sign else result
Beispiel #56
0
def test_merge1():
    def merge_int(n):
        n += 1
        if n == 1:
            return 1
        elif n == 2:
            return 2
        elif n == 3:
            return 3
        return 4

    do_test_merge(merge_int, range(4))
    do_test_merge(merge_int, [r_uint(i) for i in range(4)])
    do_test_merge(merge_int, [r_longlong(i) for i in range(4)])
    do_test_merge(merge_int, [r_ulonglong(i) for i in range(4)])

    def merge_chr(n):
        c = chr(n + 1)
        if c == 'a':
            return 'a'
        elif c == 'b':
            return 'b'
        elif c == 'c':
            return 'c'
        return 'd'

    do_test_merge(merge_chr, range(96, 101))

    def merge_uchr(n):
        c = unichr(n + 1)
        if c == u'a':
            return u'a'
        elif c == u'b':
            return u'b'
        elif c == u'c':
            return u'c'
        return u'd'

    do_test_merge(merge_uchr, range(96, 101))
Beispiel #57
0
    def test_cast(self):
        def llfn(v):
            return rffi.cast(rffi.VOIDP, v)

        res = self.interpret(llfn, [r_ulonglong(0)])
        assert res == lltype.nullptr(rffi.VOIDP.TO)

        #
        def llfn(v):
            return rffi.cast(rffi.LONGLONG, v)

        res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
        assert res == 0
        if r_longlong is not r_int:
            assert isinstance(res, r_longlong)
        else:
            assert is_valid_int(res)
        #
        def llfn(v):
            return rffi.cast(rffi.ULONGLONG, v)

        res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)])
        assert res == 0
        assert isinstance(res, r_ulonglong)
Beispiel #58
0
def test_wrap():
    def _is(box1, box2):
        return (box1.__class__ == box2.__class__ and box1.value == box2.value)

    p = lltype.malloc(lltype.GcStruct('S'))
    po = lltype.cast_opaque_ptr(llmemory.GCREF, p)
    assert _is(wrap(None, 42), BoxInt(42))
    assert _is(wrap(None, 42.5), boxfloat(42.5))
    assert _is(wrap(None, p), BoxPtr(po))
    assert _is(wrap(None, 42, in_const_box=True), ConstInt(42))
    assert _is(wrap(None, 42.5, in_const_box=True), constfloat(42.5))
    assert _is(wrap(None, p, in_const_box=True), ConstPtr(po))
    if longlong.supports_longlong:
        import sys
        from pypy.rlib.rarithmetic import r_longlong, r_ulonglong
        value = r_longlong(-sys.maxint * 17)
        assert _is(wrap(None, value), BoxFloat(value))
        assert _is(wrap(None, value, in_const_box=True), ConstFloat(value))
        value_unsigned = r_ulonglong(-sys.maxint * 17)
        assert _is(wrap(None, value_unsigned), BoxFloat(value))
    sfval = r_singlefloat(42.5)
    ival = longlong.singlefloat2int(sfval)
    assert _is(wrap(None, sfval), BoxInt(ival))
    assert _is(wrap(None, sfval, in_const_box=True), ConstInt(ival))
Beispiel #59
0
 def _check_r_ulonglong(self, f):
     self._check(f, [r_ulonglong, r_ulonglong], (r_ulonglong(sys.maxint*3), r_ulonglong(42)))
Beispiel #60
0
 def test_ullong_rshift(self):
     def f(x):
         return x >> 1
     x = sys.maxint+1
     assert self.interpret(f, [r_ulonglong(x)]) == x >> 1