aboutsummaryrefslogtreecommitdiff
blob: 0ef1a294c496edd812c42723d4fa02c8953a1133 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from rpython.rtyper.lltypesystem import lltype, rffi
from pypy.module.cpyext.api import (
    cpython_api, PyObject, build_type_checkers_flags, Py_ssize_t,
    CONST_STRING, ADDR, CANNOT_FAIL, INTP_real)
from pypy.objspace.std.longobject import W_LongObject
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.unicodehelper import wcharpsize2utf8
from pypy.module.cpyext.intobject import PyInt_AsUnsignedLongMask
from rpython.rlib.rbigint import rbigint, InvalidSignednessError

PyLong_Check, PyLong_CheckExact = build_type_checkers_flags("Long")

@cpython_api([lltype.Signed], PyObject)
def PyLong_FromLong(space, val):
    """Return a new PyLongObject object from v, or NULL on failure."""
    return space.newlong(val)

@cpython_api([Py_ssize_t], PyObject)
def PyLong_FromSsize_t(space, val):
    """Return a new PyLongObject object from a C Py_ssize_t, or
    NULL on failure.
    """
    return space.newlong(val)

@cpython_api([rffi.SIZE_T], PyObject)
def PyLong_FromSize_t(space, val):
    """Return a new PyLongObject object from a C size_t, or NULL on
    failure.
    """
    return space.newlong_from_rarith_int(val)

@cpython_api([rffi.LONGLONG], PyObject)
def PyLong_FromLongLong(space, val):
    """Return a new PyLongObject object from a C long long, or NULL
    on failure."""
    return space.newlong_from_rarith_int(val)

@cpython_api([rffi.ULONG], PyObject)
def PyLong_FromUnsignedLong(space, val):
    """Return a new PyLongObject object from a C unsigned long, or
    NULL on failure."""
    return space.newlong_from_rarith_int(val)

@cpython_api([rffi.ULONGLONG], PyObject)
def PyLong_FromUnsignedLongLong(space, val):
    """Return a new PyLongObject object from a C unsigned long long,
    or NULL on failure."""
    return space.newlong_from_rarith_int(val)

@cpython_api([PyObject], rffi.ULONG, error=-1)
def PyLong_AsUnsignedLong(space, w_long):
    """
    Return a C unsigned long representation of the contents of pylong.
    If pylong is greater than ULONG_MAX, an OverflowError is
    raised."""
    try:
        return rffi.cast(rffi.ULONG, space.uint_w(w_long))
    except OperationError as e:
        if e.match(space, space.w_ValueError):
            e.w_type = space.w_OverflowError
        raise

@cpython_api([PyObject], rffi.ULONG, error=-1)
def PyLong_AsUnsignedLongMask(space, w_long):
    """Return a C unsigned long from a Python long integer, without checking
    for overflow.
    """
    return PyInt_AsUnsignedLongMask(space, w_long)

@cpython_api([PyObject], lltype.Signed, error=-1)
def PyLong_AsLong(space, w_long):
    """
    Return a C long representation of the contents of pylong.  If
    pylong is greater than LONG_MAX, an OverflowError is raised
    and -1 will be returned."""
    return space.int_w(w_long)

@cpython_api([PyObject], Py_ssize_t, error=-1)
def PyLong_AsSsize_t(space, w_long):
    """Return a C Py_ssize_t representation of the contents of pylong.  If
    pylong is greater than PY_SSIZE_T_MAX, an OverflowError is raised
    and -1 will be returned.
    """
    return space.int_w(w_long)

@cpython_api([PyObject], rffi.LONGLONG, error=-1)
def PyLong_AsLongLong(space, w_long):
    """
    Return a C unsigned long representation of the contents of pylong.
    If pylong is greater than ULONG_MAX, an OverflowError is
    raised."""
    return rffi.cast(rffi.LONGLONG, space.r_longlong_w(w_long))

@cpython_api([PyObject], rffi.ULONGLONG, error=-1)
def PyLong_AsUnsignedLongLong(space, w_long):
    """
    Return a C unsigned long representation of the contents of pylong.
    If pylong is greater than ULONG_MAX, an OverflowError is
    raised."""
    try:
        return rffi.cast(rffi.ULONGLONG, space.r_ulonglong_w(w_long))
    except OperationError as e:
        if e.match(space, space.w_ValueError):
            e.w_type = space.w_OverflowError
        raise

@cpython_api([PyObject], rffi.ULONGLONG, error=-1)
def PyLong_AsUnsignedLongLongMask(space, w_long):
    """Will first attempt to cast the object to a PyIntObject or
    PyLongObject, if it is not already one, and then return its value as
    unsigned long long, without checking for overflow.
    """
    num = space.bigint_w(w_long)
    return num.ulonglongmask()

@cpython_api([PyObject, INTP_real], lltype.Signed,
             error=-1)
def PyLong_AsLongAndOverflow(space, w_long, overflow_ptr):
    """
    Return a C long representation of the contents of pylong.  If pylong is
    greater than LONG_MAX or less than LONG_MIN, set *overflow to 1 or -1,
    respectively, and return -1; otherwise, set *overflow to 0.  If any other
    exception occurs (for example a TypeError or MemoryError), then -1 will be
    returned and *overflow will be 0."""
    overflow_ptr[0] = rffi.cast(rffi.INT_real, 0)
    try:
        return space.int_w(w_long)
    except OperationError as e:
        if not e.match(space, space.w_OverflowError):
            raise
    if space.is_true(space.gt(w_long, space.newint(0))):
        overflow_ptr[0] = rffi.cast(rffi.INT_real, 1)
    else:
        overflow_ptr[0] = rffi.cast(rffi.INT_real, -1)
    return -1

@cpython_api([PyObject, INTP_real], rffi.LONGLONG,
             error=-1)
def PyLong_AsLongLongAndOverflow(space, w_long, overflow_ptr):
    """
    Return a C long long representation of the contents of pylong.  If pylong is
    greater than PY_LLONG_MAX or less than PY_LLONG_MIN, set *overflow to 1 or
    -1, respectively, and return -1; otherwise, set *overflow to 0.  If any
    other exception occurs (for example a TypeError or MemoryError), then -1
    will be returned and *overflow will be 0."""
    overflow_ptr[0] = rffi.cast(rffi.INT_real, 0)
    try:
        return rffi.cast(rffi.LONGLONG, space.r_longlong_w(w_long))
    except OperationError as e:
        if not e.match(space, space.w_OverflowError):
            raise
    if space.is_true(space.gt(w_long, space.newint(0))):
        overflow_ptr[0] = rffi.cast(rffi.INT_real, 1)
    else:
        overflow_ptr[0] = rffi.cast(rffi.INT_real, -1)
    return -1

@cpython_api([lltype.Float], PyObject)
def PyLong_FromDouble(space, val):
    """Return a new PyLongObject object from v, or NULL on failure."""
    return space.long(space.newfloat(val))

@cpython_api([PyObject], lltype.Float, error=-1.0)
def PyLong_AsDouble(space, w_long):
    """Return a C double representation of the contents of pylong.  If
    pylong cannot be approximately represented as a double, an
    OverflowError exception is raised and -1.0 will be returned."""
    return space.float_w(space.float(w_long))

@cpython_api([CONST_STRING, rffi.CCHARPP, rffi.INT_real], PyObject)
def PyLong_FromString(space, str, pend, base):
    """Return a new PyLongObject based on the string value in str, which is
    interpreted according to the radix in base.  If pend is non-NULL,
    *pend will point to the first character in str which follows the
    representation of the number.  If base is 0, the radix will be determined
    based on the leading characters of str: if str starts with '0x' or
    '0X', radix 16 will be used; if str starts with '0', radix 8 will be
    used; otherwise radix 10 will be used.  If base is not 0, it must be
    between 2 and 36, inclusive.  Leading spaces are ignored.  If there are
    no digits, ValueError will be raised."""
    s = rffi.charp2str(str)
    w_str = space.newtext(s)
    w_base = space.newint(rffi.cast(lltype.Signed, base))
    if pend:
        pend[0] = rffi.ptradd(str, len(s))
    return space.call_function(space.w_long, w_str, w_base)

@cpython_api([rffi.CWCHARP, Py_ssize_t, rffi.INT_real], PyObject)
def PyLong_FromUnicode(space, u, length, base):
    """Convert a sequence of Unicode digits to a Python long integer value.
    The first parameter, u, points to the first character of the Unicode
    string, length gives the number of characters, and base is the radix
    for the conversion.  The radix must be in the range [2, 36]; if it is
    out of range, ValueError will be raised."""
    w_value = space.newutf8(wcharpsize2utf8(space, u, length), length)
    w_base = space.newint(rffi.cast(lltype.Signed, base))
    return space.call_function(space.w_long, w_value, w_base)

@cpython_api([rffi.VOIDP], PyObject)
def PyLong_FromVoidPtr(space, p):
    """Create a Python integer or long integer from the pointer p. The pointer value
    can be retrieved from the resulting value using PyLong_AsVoidPtr().

    If the integer is larger than LONG_MAX, a positive long integer is returned."""
    value = rffi.cast(ADDR, p)    # signed integer
    if value < 0:
        return space.newlong_from_rarith_int(rffi.cast(lltype.Unsigned, p))
    return space.newint(value)

@cpython_api([PyObject], rffi.VOIDP, error=lltype.nullptr(rffi.VOIDP.TO))
def PyLong_AsVoidPtr(space, w_long):
    """Convert a Python integer or long integer pylong to a C void pointer.
    If pylong cannot be converted, an OverflowError will be raised.  This
    is only assured to produce a usable void pointer for values created
    with PyLong_FromVoidPtr().
    For values outside 0..LONG_MAX, both signed and unsigned integers are accepted."""
    return rffi.cast(rffi.VOIDP, space.uint_w(w_long))

@cpython_api([PyObject], rffi.SIZE_T, error=-1)
def _PyLong_NumBits(space, w_long):
    return space.uint_w(space.call_method(w_long, "bit_length"))

@cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
def _PyLong_Sign(space, w_long):
    assert isinstance(w_long, W_LongObject)
    return w_long.num.sign

CONST_UCHARP = lltype.Ptr(lltype.Array(rffi.UCHAR, hints={'nolength': True,
                                       'render_as_const': True}))
@cpython_api([CONST_UCHARP, rffi.SIZE_T, rffi.INT_real, rffi.INT_real], PyObject)
def _PyLong_FromByteArray(space, bytes, n, little_endian, signed):
    little_endian = rffi.cast(lltype.Signed, little_endian)
    signed = rffi.cast(lltype.Signed, signed)
    s = rffi.charpsize2str(rffi.cast(rffi.CCHARP, bytes),
                           rffi.cast(lltype.Signed, n))
    if little_endian:
        byteorder = 'little'
    else:
        byteorder = 'big'
    result = rbigint.frombytes(s, byteorder, signed != 0)
    return space.newlong_from_rbigint(result)

@cpython_api([PyObject, rffi.UCHARP, rffi.SIZE_T,
              rffi.INT_real, rffi.INT_real], rffi.INT_real, error=-1)
def _PyLong_AsByteArrayO(space, w_v, bytes, n, little_endian, is_signed):
    n = rffi.cast(lltype.Signed, n)
    little_endian = rffi.cast(lltype.Signed, little_endian)
    signed = rffi.cast(lltype.Signed, is_signed) != 0
    byteorder = 'little' if little_endian else 'big'
    bigint = space.bigint_w(w_v)
    try:
        digits = bigint.tobytes(n, byteorder, signed)
    except InvalidSignednessError:     # < 0 but not 'signed'
        # in this case, CPython raises OverflowError even though the C
        # comments say it should raise TypeError
        raise oefmt(space.w_OverflowError,
                    "can't convert negative long to unsigned")
    except OverflowError:
        raise oefmt(space.w_OverflowError,
                    "long too big to convert")
    assert len(digits) == n
    for i in range(n):
        bytes[i] = rffi.cast(rffi.UCHAR, digits[i])
    return 0