Debian Codegraph @

pypy/objspace/std/intobject.py

raw symbols SCIP
1 """The builtin int type (W_AbstractInt) and the base impl (W_IntObject)
2 based on rpython ints.
3
4 In order to have the same behavior running on CPython, and after RPython
5 translation this module uses rarithmetic.ovfcheck to explicitly check
6 for overflows, something CPython does not do anymore.
7 """
8 import operator
9 import sys
10
11 from rpython.rlib import jit
12 from rpython.rlib.objectmodel import instantiate, enforceargs
13 from rpython.rlib.rarithmetic import (
14 LONG_BIT, intmask, is_valid_int, ovfcheck, r_longlong, r_uint,
15 string_to_int)
16 from rpython.rlib.rbigint import (
17 InvalidEndiannessError, InvalidSignednessError, rbigint, bit_length_int,
18 frombytes_int, tobytes_int)
19 from rpython.rlib.rfloat import DBL_MANT_DIG
20 from rpython.rlib.rstring import (
21 ParseStringError, ParseStringOverflowError, MaxDigitsError)
22 from rpython.tool.sourcetools import func_renamer, func_with_new_name
23
24 from pypy.interpreter import typedef
25 from pypy.interpreter.baseobjspace import W_Root
26 from pypy.interpreter.error import OperationError, oefmt
27 from pypy.interpreter.gateway import (
28 WrappedDefault, applevel, interp2app, interpindirect2app, unwrap_spec)
29 from pypy.interpreter.typedef import TypeDef
30 from pypy.objspace.std import newformat
31 from pypy.objspace.std.util import (
32 BINARY_OPS, CMP_OPS, COMMUTATIVE_OPS, IDTAG_INT, IDTAG_SHIFT, wrap_parsestringerror)
33
34 SENTINEL = object()
35
36 HASH_BITS = 61 if sys.maxsize > 2 ** 31 - 1 else 31
37 HASH_MODULUS = 2 ** HASH_BITS - 1
38
39 MININT = -sys.maxint-1
40
41 class W_AbstractIntObject(W_Root):
42 __slots__ = ()
43
44 def is_w(self, space, w_other):
45 from pypy.objspace.std.boolobject import W_BoolObject
46 if (not isinstance(w_other, W_AbstractIntObject) or
47 isinstance(w_other, W_BoolObject)):
48 return False
49 if self.user_overridden_class or w_other.user_overridden_class:
50 return self is w_other
51 x = space.bigint_w(self, allow_conversion=False)
52 y = space.bigint_w(w_other, allow_conversion=False)
53 return x.eq(y)
54
55 def immutable_unique_id(self, space):
56 if self.user_overridden_class:
57 return None
58 b = space.bigint_w(self)
59 b = b.lshift(IDTAG_SHIFT).int_or_(IDTAG_INT)
60 return space.newlong_from_rbigint(b)
61
62 @staticmethod
63 @unwrap_spec(byteorder='text', signed=bool)
64 def descr_from_bytes(space, w_inttype, w_obj, byteorder='big', signed=False):
65 """int.from_bytes(bytes, byteorder='big', *, signed=False) -> int
66
67 Return the integer represented by the given array of bytes.
68
69 The bytes argument must either support the buffer protocol or be
70 an iterable object producing bytes. Bytes and bytearray are
71 examples of built-in objects that support the buffer protocol.
72
73 The byteorder argument determines the byte order used to
74 represent the integer. If byteorder is 'big', the most
75 significant byte is at the beginning of the byte array. If
76 byteorder is 'little', the most significant byte is at the end
77 of the byte array. To request the native byte order of the host
78 system, use `sys.byteorder' as the byte order value.
79
80 The signed keyword-only argument indicates whether two's
81 complement is used to represent the integer.
82 """
83 from pypy.objspace.std.bytesobject import makebytesdata_w
84 def frombytes(space, bytes, byteorder, signed):
85 try:
86 value = frombytes_int(bytes, byteorder=byteorder,
87 signed=signed)
88 except OverflowError:
89 pass
90 else:
91 return space.newint(value)
92 bigint = rbigint.frombytes(bytes, byteorder=byteorder,
93 signed=signed)
94 return space.newlong_from_rbigint(bigint)
95 bytes = makebytesdata_w(space, w_obj)
96 try:
97 w_obj = frombytes(space, bytes, byteorder, signed)
98 except InvalidEndiannessError:
99 raise oefmt(space.w_ValueError,
100 "byteorder must be either 'little' or 'big'")
101 if not space.is_w(w_inttype, space.w_int):
102 # That's what from_bytes() does in CPython 3.5.2 too
103 w_obj = space.call_function(w_inttype, w_obj)
104 return w_obj
105 descr_from_bytes.__func__.__text_signature__ = "($type, /, bytes, byteorder='big', *, signed=False)"
106
107 @unwrap_spec(length=int, byteorder='text', signed=bool)
108 def descr_to_bytes(self, space, length=1, byteorder='big', signed=False):
109 """to_bytes(...)
110 int.to_bytes(length=1, byteorder='big', *, signed=False) -> bytes
111
112 Return an array of bytes representing an integer.
113
114 The integer is represented using length bytes. An OverflowError
115 is raised if the integer is not representable with the given
116 number of bytes.
117
118 The byteorder argument determines the byte order used to
119 represent the integer. If byteorder is 'big', the most
120 significant byte is at the beginning of the byte array. If
121 byteorder is 'little', the most significant byte is at the end
122 of the byte array. To request the native byte order of the host
123 system, use `sys.byteorder' as the byte order value.
124
125 The signed keyword-only argument determines whether two's
126 complement is used to represent the integer. If signed is False
127 and a negative integer is given, an OverflowError is raised.
128 """
129 bigint = space.bigint_w(self)
130 try:
131 byte_string = bigint.tobytes(length, byteorder=byteorder,
132 signed=signed)
133 except InvalidEndiannessError:
134 raise oefmt(space.w_ValueError,
135 "byteorder must be either 'little' or 'big'")
136 except InvalidSignednessError:
137 raise oefmt(space.w_OverflowError,
138 "can't convert negative int to unsigned")
139 except OverflowError:
140 raise oefmt(space.w_OverflowError, "int too big to convert")
141 return space.newbytes(byte_string)
142 descr_to_bytes.__text_signature__ = "($self, /, length=1, byteorder='big', *, signed=False)"
143
144 def descr_round(self, space, w_ndigits=None):
145 """Rounding an Integral returns itself.
146 Rounding with an ndigits argument also returns an integer.
147 """
148 # To round an integer m to the nearest 10**n (n positive), we
149 # make use of the divmod_near operation, defined by:
150 #
151 # divmod_near(a, b) = (q, r)
152 #
153 # where q is the nearest integer to the quotient a / b (the
154 # nearest even integer in the case of a tie) and r == a - q * b.
155 # Hence q * b = a - r is the nearest multiple of b to a,
156 # preferring even multiples in the case of a tie.
157 #
158 # So the nearest multiple of 10**n to m is:
159 #
160 # m - divmod_near(m, 10**n)[1]
161
162 # XXX: since divmod_near is pure python we can probably remove
163 # the longs used here. or this could at least likely be more
164 # efficient for W_IntObject
165 from pypy.objspace.std.longobject import newlong
166
167 if space.is_none(w_ndigits):
168 return self.int(space)
169
170 ndigits = space.bigint_w(space.index(w_ndigits))
171 # if ndigits >= 0 then no rounding is necessary; return self
172 # unchanged
173 if ndigits.ge(rbigint.fromint(0)):
174 return self.int(space)
175
176 # result = self - divmod_near(self, 10 ** -ndigits)[1]
177 right = rbigint.fromint(10).pow(ndigits.neg())
178 w_tuple = divmod_near(space, self, newlong(space, right))
179 _, w_r = space.fixedview(w_tuple, 2)
180 return space.sub(self, w_r)
181
182 def _self_unaryop(opname, doc=None):
183 @func_renamer('descr_' + opname)
184 def descr_unaryop(self, space):
185 return self.int(space)
186 descr_unaryop.__doc__ = doc
187 return descr_unaryop
188
189 descr_conjugate = _self_unaryop(
190 'conjugate', "Returns self, the complex conjugate of any int.")
191 descr_pos = _self_unaryop('pos', "x.__pos__() <==> +x")
192 descr_index = _self_unaryop('index',
193 "x[y:z] <==> x[y.__index__():z.__index__()]")
194 descr_trunc = _self_unaryop('trunc',
195 "Truncating an Integral returns itself.")
196 descr_floor = _self_unaryop('floor', "Flooring an Integral returns itself.")
197 descr_ceil = _self_unaryop('ceil', "Ceiling of an Integral returns itself.")
198
199 descr_get_numerator = _self_unaryop('get_numerator')
200 descr_get_real = _self_unaryop('get_real')
201
202 def descr_get_denominator(self, space):
203 return wrapint(space, 1)
204
205 def descr_get_imag(self, space):
206 return wrapint(space, 0)
207
208 def int(self, space):
209 """x.__int__() <==> int(x)"""
210 raise NotImplementedError
211
212 def asbigint(self):
213 raise NotImplementedError
214
215 def descr_format(self, space, w_format_spec):
216 raise NotImplementedError
217
218 def descr_pow(self, space, w_exponent, w_modulus=None):
219 """x.__pow__(y[, z]) <==> pow(x, y[, z])"""
220 raise NotImplementedError
221 descr_rpow = func_with_new_name(descr_pow, 'descr_rpow')
222 descr_rpow.__doc__ = "y.__rpow__(x[, z]) <==> pow(x, y[, z])"
223
224 def _abstract_unaryop(opname, doc=SENTINEL):
225 if doc is SENTINEL:
226 doc = 'x.__%s__() <==> %s(x)' % (opname, opname)
227 @func_renamer('descr_' + opname)
228 def descr_unaryop(self, space):
229 raise NotImplementedError
230 descr_unaryop.__doc__ = doc
231 return descr_unaryop
232
233 descr_repr = _abstract_unaryop('repr')
234 descr_str = _abstract_unaryop('str')
235
236 descr_bit_length = _abstract_unaryop('bit_length', """\
237 int.bit_length() -> int
238
239 Number of bits necessary to represent self in binary.
240 >>> bin(37)
241 '0b100101'
242 >>> (37).bit_length()
243 6""")
244 descr_bit_count = _abstract_unaryop('bit_count', """\
245 int.bit_count() -> int
246
247 Number of bits set in the binary representation.
248 >>> bin(37)
249 '0b100101'
250 >>> (37).bit_count()
251 3""")
252 descr_hash = _abstract_unaryop('hash')
253 descr_getnewargs = _abstract_unaryop('getnewargs', None)
254 descr_float = _abstract_unaryop('float')
255 descr_neg = _abstract_unaryop('neg', "x.__neg__() <==> -x")
256 descr_abs = _abstract_unaryop('abs')
257 descr_bool = _abstract_unaryop('bool', "x.__bool__() <==> x != 0")
258 descr_invert = _abstract_unaryop('invert', "x.__invert__() <==> ~x")
259
260 def _abstract_cmpop(opname):
261 @func_renamer('descr_' + opname)
262 def descr_cmp(self, space, w_other):
263 raise NotImplementedError
264 descr_cmp.__doc__ = 'x.__%s__(y) <==> x%sy' % (opname, CMP_OPS[opname])
265 return descr_cmp
266
267 descr_lt = _abstract_cmpop('lt')
268 descr_le = _abstract_cmpop('le')
269 descr_eq = _abstract_cmpop('eq')
270 descr_ne = _abstract_cmpop('ne')
271 descr_gt = _abstract_cmpop('gt')
272 descr_ge = _abstract_cmpop('ge')
273
274 def _abstract_binop(opname):
275 oper = BINARY_OPS.get(opname)
276 if oper == '%':
277 oper = '%%'
278 oper = '%s(%%s, %%s)' % opname if not oper else '%%s%s%%s' % oper
279 @func_renamer('descr_' + opname)
280 def descr_binop(self, space, w_other):
281 raise NotImplementedError
282 descr_binop.__doc__ = "x.__%s__(y) <==> %s" % (opname,
283 oper % ('x', 'y'))
284 descr_rbinop = func_with_new_name(descr_binop, 'descr_r' + opname)
285 descr_rbinop.__doc__ = "x.__r%s__(y) <==> %s" % (opname,
286 oper % ('y', 'x'))
287 return descr_binop, descr_rbinop
288
289 descr_add, descr_radd = _abstract_binop('add')
290 descr_sub, descr_rsub = _abstract_binop('sub')
291 descr_mul, descr_rmul = _abstract_binop('mul')
292 descr_matmul, descr_rmatmul = _abstract_binop('matmul')
293
294 descr_and, descr_rand = _abstract_binop('and')
295 descr_or, descr_ror = _abstract_binop('or')
296 descr_xor, descr_rxor = _abstract_binop('xor')
297
298 descr_lshift, descr_rlshift = _abstract_binop('lshift')
299 descr_rshift, descr_rrshift = _abstract_binop('rshift')
300
301 descr_floordiv, descr_rfloordiv = _abstract_binop('floordiv')
302 descr_truediv, descr_rtruediv = _abstract_binop('truediv')
303 descr_mod, descr_rmod = _abstract_binop('mod')
304 descr_divmod, descr_rdivmod = _abstract_binop('divmod')
305
306 def descr_as_integer_ratio(self, space):
307 """
308 Return integer ratio.
309
310 Return a pair of integers, whose ratio is exactly equal to the original int
311 and with a positive denominator.
312
313 >>> (10).as_integer_ratio()
314 (10, 1)
315 >>> (-10).as_integer_ratio()
316 (-10, 1)
317 >>> (0).as_integer_ratio()
318 (0, 1)
319 """
320 return space.newtuple([self.int(space), space.newint(1)])
321
322
323 def _floordiv(space, x, y):
324 try:
325 z = ovfcheck(x // y)
326 except ZeroDivisionError:
327 raise oefmt(space.w_ZeroDivisionError,
328 "integer division or modulo by zero")
329 return wrapint(space, z)
330
331
332 def _truediv(space, x, y):
333 if not y:
334 raise oefmt(space.w_ZeroDivisionError, "division by zero")
335
336 if (DBL_MANT_DIG < LONG_BIT and
337 (r_uint(abs(x)) >> DBL_MANT_DIG or r_uint(abs(y)) >> DBL_MANT_DIG)):
338 # large x or y, use long arithmetic
339 raise OverflowError
340
341 # both ints can be exactly represented as doubles, do a
342 # floating-point division
343 a = float(x)
344 b = float(y)
345 return space.newfloat(a / b)
346
347
348 def _mod(space, x, y):
349 try:
350 z = ovfcheck(x % y)
351 except ZeroDivisionError:
352 raise oefmt(space.w_ZeroDivisionError, "integer modulo by zero")
353 return wrapint(space, z)
354
355
356 def _divmod(space, x, y):
357 try:
358 z = ovfcheck(x // y)
359 except ZeroDivisionError:
360 raise oefmt(space.w_ZeroDivisionError, "integer divmod by zero")
361 # no overflow possible
362 m = x % y
363 return space.newtuple2(space.newint(z), space.newint(m))
364
365
366 def _divmod_ovf2small(space, x, y):
367 from pypy.objspace.std.smalllongobject import W_SmallLongObject
368 a = r_longlong(x)
369 b = r_longlong(y)
370 return space.newtuple2(W_SmallLongObject(a // b),
371 W_SmallLongObject(a % b))
372
373
374 def _lshift(space, a, b):
375 if r_uint(b) < LONG_BIT: # 0 <= b < LONG_BIT
376 c = ovfcheck(a << b)
377 return wrapint(space, c)
378 if b < 0:
379 raise oefmt(space.w_ValueError, "negative shift count")
380 # b >= LONG_BIT
381 if a == 0:
382 return wrapint(space, a)
383 raise OverflowError
384
385
386 def _lshift_ovf2small(space, a, b):
387 from pypy.objspace.std.smalllongobject import W_SmallLongObject
388 w_a = W_SmallLongObject.fromint(a)
389 w_b = W_SmallLongObject.fromint(b)
390 return w_a.descr_lshift(space, w_b)
391
392
393 def _rshift(space, a, b):
394 if r_uint(b) >= LONG_BIT: # not (0 <= b < LONG_BIT)
395 if b < 0:
396 raise oefmt(space.w_ValueError, "negative shift count")
397 # b >= LONG_BIT
398 if a == 0:
399 return wrapint(space, a)
400 a = -1 if a < 0 else 0
401 else:
402 a = a >> b
403 return wrapint(space, a)
404
405
406 def _pow(space, iv, iw, iz):
407 """Helper for pow"""
408 if iz == 0:
409 return _pow_nomod(iv, iw)
410 else:
411 return _pow_mod(space, iv, iw, iz)
412
413 @jit.look_inside_iff(lambda iv, iw: jit.isconstant(iw))
414 def _pow_nomod(iv, iw):
415 if iw <= 0:
416 if iw == 0:
417 return 1
418 # bounce it, since it always returns float
419 raise ValueError
420 temp = iv
421 ix = 1
422 while True:
423 if iw & 1:
424 try:
425 ix = ovfcheck(ix * temp)
426 except OverflowError:
427 raise
428 iw >>= 1 # Shift exponent down by 1 bit
429 if iw == 0:
430 break
431 try:
432 temp = ovfcheck(temp * temp) # Square the value of temp
433 except OverflowError:
434 raise
435 return ix
436
437 @jit.look_inside_iff(lambda space, iv, iw, iz:
438 jit.isconstant(iw) and jit.isconstant(iz))
439 def _pow_mod(space, iv, iw, iz):
440 from rpython.rlib.rarithmetic import mulmod
441
442 if iw == 0:
443 return 1 % iz # != 1, for iz == 1 or iz < 0
444 if iz < 0:
445 try:
446 iz = ovfcheck(-iz)
447 except OverflowError:
448 raise
449 iz_negative = True
450 else:
451 iz_negative = False
452 if iw <= 0:
453 w_iv = invmod(space, space.newint(iv), space.newint(iz))
454 assert isinstance(w_iv, W_IntObject)
455 iv = w_iv.intval
456 try:
457 iw = ovfcheck(-iw)
458 except OverflowError:
459 raise
460
461 temp = iv
462 ix = 1
463 while True:
464 if iw & 1:
465 ix = mulmod(ix, temp, iz)
466 iw >>= 1 # Shift exponent down by 1 bit
467 if iw == 0:
468 break
469 temp = mulmod(temp, temp, iz)
470
471 if iz_negative and ix > 0:
472 ix -= iz
473 return ix
474
475
476 def _pow_ovf2long(space, iv, w_iv, iw, w_iw, w_modulus):
477 if space.is_none(w_modulus) and _recover_with_smalllong(space):
478 from pypy.objspace.std.smalllongobject import _pow as _pow_small
479 try:
480 # XXX: shouldn't have to pass r_longlong(0) here (see
481 # 4fa4c6b93a84)
482 return _pow_small(space, r_longlong(iv), iw, r_longlong(0))
483 except (OverflowError, ValueError):
484 pass
485 from pypy.objspace.std.longobject import W_LongObject, W_AbstractLongObject
486 if w_iv is None or not isinstance(w_iv, W_AbstractLongObject):
487 w_iv = W_LongObject.fromint(space, iv)
488 # *don't* convert w_iw. W_LongObject.descr_pow can deal with w_iw being an
489 # int just fine
490 assert w_iw is not None
491 return w_iv.descr_pow(space, w_iw, w_modulus)
492
493
494 def _make_ovf2long(opname, ovf2small=None):
495 op = getattr(operator, opname, None)
496 assert op or ovf2small
497
498 def ovf2long(space, x, w_x, y, w_y):
499 """Handle overflowing to smalllong or long"""
500 if _recover_with_smalllong(space):
501 if ovf2small:
502 return ovf2small(space, x, y)
503 # Assume a generic operation without an explicit ovf2small
504 # handler
505 from pypy.objspace.std.smalllongobject import W_SmallLongObject
506 a = r_longlong(x)
507 b = r_longlong(y)
508 return W_SmallLongObject(op(a, b))
509 if opname == 'add':
510 return space.newlong_from_rbigint(rbigint.add_int_int_bigint_result(x, y))
511 if opname == 'sub':
512 return space.newlong_from_rbigint(rbigint.sub_int_int_bigint_result(x, y))
513 if opname == 'mul':
514 return space.newlong_from_rbigint(rbigint.mul_int_int_bigint_result(x, y))
515 from pypy.objspace.std.longobject import W_LongObject, W_AbstractLongObject
516 w_x = W_LongObject.fromint(space, x)
517 assert w_y is not None
518 # call the W_LongObject implementation with the unconverted w_y.
519 # W_LongObject can deal with W_IntObject arguments just fine, and it
520 # has a slightly better code path for long/int combinations
521 return getattr(w_x, 'descr_' + opname)(space, w_y)
522
523 return ovf2long
524
525
526
527 @jit.elidable
528 def _bit_count(val):
529 if val == -sys.maxint - 1:
530 return 1
531 elif val < 0:
532 val = -val
533 count = 0
534 while val:
535 count += val & 1
536 val >>= 1
537 return count
538
539
540 class W_IntObject(W_AbstractIntObject):
541
542 __slots__ = 'intval'
543 _immutable_fields_ = ['intval']
544
545 def __init__(self, intval):
546 assert is_valid_int(intval)
547 self.intval = int(intval)
548
549 def __repr__(self):
550 """representation for debugging purposes"""
551 return "%s(%d)" % (self.__class__.__name__, self.intval)
552
553 def is_w(self, space, w_other):
554 from pypy.objspace.std.boolobject import W_BoolObject
555 if (not isinstance(w_other, W_AbstractIntObject) or
556 isinstance(w_other, W_BoolObject)):
557 return False
558 if self.user_overridden_class or w_other.user_overridden_class:
559 return self is w_other
560 x = self.intval
561 try:
562 y = space.int_w(w_other)
563 except OperationError as e:
564 if e.match(space, space.w_OverflowError):
565 return False
566 raise
567 return x == y
568
569 def int_w(self, space, allow_conversion=True):
570 return self.intval
571
572 def _int_w(self, space):
573 return self.intval
574
575 unwrap = _int_w
576
577 def uint_w(self, space):
578 intval = self.intval
579 if intval < 0:
580 raise oefmt(space.w_ValueError,
581 "cannot convert negative integer to unsigned")
582 return r_uint(intval)
583
584 def bigint_w(self, space, allow_conversion=True):
585 return self.asbigint()
586
587 def _bigint_w(self, space):
588 return self.asbigint()
589
590 def float_w(self, space, allow_conversion=True):
591 return float(self.intval)
592
593 # note that we do NOT implement _float_w, because __float__ cannot return
594 # an int
595
596 def int(self, space):
597 if type(self) is W_IntObject:
598 return self
599 if not space.is_overloaded(self, space.w_int, '__int__'):
600 return space.newint(self.intval)
601 return W_Root.int(self, space)
602
603 def asbigint(self):
604 return rbigint.fromint(self.intval)
605
606 @staticmethod
607 @unwrap_spec(w_x=WrappedDefault(0))
608 def descr_new(space, w_inttype, w_x, __posonly__, w_base=None):
609 "Create and return a new object. See help(type) for accurate signature."
610 return _new_int(space, w_inttype, w_x, w_base)
611
612 def descr_hash(self, space):
613 return space.newint(_hash_int(self.intval))
614
615 def as_w_long(self, space):
616 from pypy.objspace.std.longobject import W_LongObject
617 from pypy.objspace.std.smalllongobject import W_SmallLongObject
618 if space.config.objspace.std.withsmalllong:
619 return W_SmallLongObject.fromint(self.intval)
620 return W_LongObject.fromint(space, self.intval)
621
622 def descr_bool(self, space):
623 return space.newbool(self.intval != 0)
624
625 def descr_invert(self, space):
626 return wrapint(space, ~self.intval)
627
628 def descr_neg(self, space):
629 a = self.intval
630 if a == MININT:
631 if _recover_with_smalllong(space):
632 from pypy.objspace.std.smalllongobject import W_SmallLongObject
633 x = r_longlong(a)
634 return W_SmallLongObject(-x)
635 return self.as_w_long(space).descr_neg(space)
636 return wrapint(space, -a)
637
638 def descr_abs(self, space):
639 if type(self) is W_IntObject:
640 if self.intval == MININT:
641 return self.descr_neg(space)
642 # branchless version
643 x = self.intval
644 mask = x >> (LONG_BIT - 1)
645 return space.newint((x ^ mask) - mask)
646 pos = self.intval >= 0
647 return self.int(space) if pos else self.descr_neg(space)
648
649 def descr_float(self, space):
650 a = self.intval
651 x = float(a)
652 return space.newfloat(x)
653
654 def descr_getnewargs(self, space):
655 return space.newtuple([wrapint(space, self.intval)])
656
657 def descr_bit_length(self, space):
658 return space.newint(bit_length_int(self.intval))
659
660 def descr_bit_count(self, space):
661 return space.newint(_bit_count(self.intval))
662
663 def descr_repr(self, space):
664 res = str(self.intval)
665 return space.newutf8(res, len(res)) # res is always ASCII
666 descr_str = func_with_new_name(descr_repr, 'descr_str')
667
668 def descr_format(self, space, w_format_spec):
669 return newformat.run_formatter(space, w_format_spec,
670 "format_int_or_long", self,
671 newformat.INT_KIND)
672
673 @unwrap_spec(w_modulus=WrappedDefault(None))
674 def descr_pow(self, space, w_exponent, w_modulus=None):
675 if isinstance(w_exponent, W_IntObject):
676 y = w_exponent.intval
677 elif isinstance(w_exponent, W_AbstractIntObject):
678 self = self.as_w_long(space)
679 return self.descr_pow(space, w_exponent, w_modulus)
680 else:
681 return space.w_NotImplemented
682
683 x = self.intval
684 y = w_exponent.intval
685
686 if space.is_none(w_modulus):
687 z = 0
688 elif isinstance(w_modulus, W_IntObject):
689 z = w_modulus.intval
690 if z == 0:
691 raise oefmt(space.w_ValueError,
692 "pow() 3rd argument cannot be 0")
693 else:
694 # can't return NotImplemented (space.pow doesn't do full
695 # ternary, i.e. w_modulus.__zpow__(self, w_exponent)), so
696 # handle it ourselves
697 return _pow_ovf2long(space, x, self, y, w_exponent, w_modulus)
698
699 try:
700 result = _pow(space, x, y, z)
701 except OverflowError:
702 return _pow_ovf2long(space, x, self, y, w_exponent, w_modulus)
703 except ValueError:
704 # float result, so let avoid a roundtrip in rbigint.
705 self = self.descr_float(space)
706 w_exponent = w_exponent.descr_float(space)
707 return space.pow(self, w_exponent, space.w_None)
708
709 return space.newint(result)
710
711 @unwrap_spec(w_modulus=WrappedDefault(None))
712 def descr_rpow(self, space, w_base, w_modulus=None):
713 if isinstance(w_base, W_IntObject):
714 return w_base.descr_pow(space, self, w_modulus)
715 elif isinstance(w_base, W_AbstractIntObject):
716 self = self.as_w_long(space)
717 return self.descr_rpow(space, w_base, w_modulus)
718 return space.w_NotImplemented
719
720 def _make_descr_cmp(opname):
721 op = getattr(operator, opname)
722 descr_name = 'descr_' + opname
723
724 if opname == 'lt': revopname = 'gt'
725 elif opname == 'le': revopname = 'ge'
726 elif opname == 'eq': revopname = 'eq'
727 elif opname == 'ne': revopname = 'ne'
728 elif opname == 'gt': revopname = 'lt'
729 elif opname == 'ge': revopname = 'le'
730 bigintintrevop = getattr(rbigint, "int_" + revopname)
731
732 @func_renamer(descr_name)
733 def descr_cmp(self, space, w_other):
734 from pypy.objspace.std.longobject import W_LongObject, W_AbstractLongObject
735 if isinstance(w_other, W_IntObject):
736 i = self.intval
737 j = w_other.intval
738 return space.newbool(op(i, j))
739 elif isinstance(w_other, W_AbstractIntObject):
740 if not space.config.objspace.std.withsmalllong:
741 assert isinstance(w_other, W_LongObject)
742 return space.newbool(bigintintrevop(w_other.asbigint(), self.intval))
743 return space.w_NotImplemented
744 return descr_cmp
745
746 descr_lt = _make_descr_cmp('lt')
747 descr_le = _make_descr_cmp('le')
748 descr_eq = _make_descr_cmp('eq')
749 descr_ne = _make_descr_cmp('ne')
750 descr_gt = _make_descr_cmp('gt')
751 descr_ge = _make_descr_cmp('ge')
752
753 def _make_generic_descr_binop(opname, ovf=True):
754 op = getattr(operator,
755 opname + '_' if opname in ('and', 'or') else opname)
756 descr_name, descr_rname = 'descr_' + opname, 'descr_r' + opname
757 if ovf:
758 ovf2long = _make_ovf2long(opname)
759
760 @func_renamer(descr_name)
761 def descr_binop(self, space, w_other):
762 from pypy.objspace.std.longobject import W_LongObject
763 if isinstance(w_other, W_IntObject):
764 x = self.intval
765 y = w_other.intval
766 if ovf:
767 try:
768 z = ovfcheck(op(x, y))
769 except OverflowError:
770 return ovf2long(space, x, self, y, w_other)
771 else:
772 z = op(x, y)
773 return wrapint(space, z)
774 elif type(w_other) is W_LongObject:
775 return getattr(w_other, descr_rname)(space, self)
776 elif isinstance(w_other, W_AbstractIntObject):
777 self = self.as_w_long(space)
778 return getattr(self, descr_name)(space, w_other)
779 return space.w_NotImplemented
780
781 if opname in COMMUTATIVE_OPS:
782 @func_renamer(descr_rname)
783 def descr_rbinop(self, space, w_other):
784 return descr_binop(self, space, w_other)
785 return descr_binop, descr_rbinop
786
787 @func_renamer(descr_rname)
788 def descr_rbinop(self, space, w_other):
789 if isinstance(w_other, W_IntObject):
790 x = self.intval
791 y = w_other.intval
792 if ovf:
793 try:
794 z = ovfcheck(op(y, x))
795 except OverflowError:
796 return ovf2long(space, y, w_other, x, self) # XXX write a test
797 else:
798 z = op(y, x)
799 return wrapint(space, z)
800 elif isinstance(w_other, W_AbstractIntObject):
801 self = self.as_w_long(space)
802 return getattr(self, descr_rname)(space, w_other)
803 return space.w_NotImplemented
804
805 return descr_binop, descr_rbinop
806
807 descr_add, descr_radd = _make_generic_descr_binop('add')
808 descr_sub, descr_rsub = _make_generic_descr_binop('sub')
809 descr_mul, descr_rmul = _make_generic_descr_binop('mul')
810
811 descr_and, descr_rand = _make_generic_descr_binop('and', ovf=False)
812 descr_or, descr_ror = _make_generic_descr_binop('or', ovf=False)
813 descr_xor, descr_rxor = _make_generic_descr_binop('xor', ovf=False)
814
815 def _make_descr_binop(func, ovf=True, ovf2small=None, ovf_func=None):
816 opname = func.__name__[1:]
817 descr_name, descr_rname = 'descr_' + opname, 'descr_r' + opname
818 if ovf:
819 if ovf_func:
820 ovf2long = ovf_func
821 assert not ovf2small # must be part of ovf_func
822 else:
823 ovf2long = _make_ovf2long(opname, ovf2small)
824
825 @func_renamer(descr_name)
826 def descr_binop(self, space, w_other):
827 if isinstance(w_other, W_IntObject):
828 x = self.intval
829 y = w_other.intval
830 if ovf:
831 try:
832 return func(space, x, y)
833 except OverflowError:
834 return ovf2long(space, x, self, y, w_other)
835 else:
836 return func(space, x, y)
837 elif isinstance(w_other, W_AbstractIntObject):
838 self = self.as_w_long(space)
839 return getattr(self, descr_name)(space, w_other)
840 return space.w_NotImplemented
841
842 @func_renamer(descr_rname)
843 def descr_rbinop(self, space, w_other):
844 if isinstance(w_other, W_IntObject):
845 x = self.intval
846 y = w_other.intval
847 if ovf:
848 try:
849 return func(space, y, x)
850 except OverflowError:
851 return ovf2long(space, y, w_other, x, self)
852 else:
853 return func(space, y, x)
854 elif isinstance(w_other, W_AbstractIntObject):
855 self = self.as_w_long(space)
856 return getattr(self, descr_rname)(space, w_other)
857 return space.w_NotImplemented
858
859 return descr_binop, descr_rbinop
860
861 def _ovf2long_lshift(space, x, w_x, y, w_y):
862 if _recover_with_smalllong(space):
863 return _lshift_ovf2small(space, x, y)
864
865 return space.newlong_from_rbigint(rbigint.lshift_int_int_bigint_result(x, y))
866
867 descr_lshift, descr_rlshift = _make_descr_binop(
868 _lshift, ovf_func=_ovf2long_lshift)
869 descr_rshift, descr_rrshift = _make_descr_binop(_rshift, ovf=False)
870
871 descr_floordiv, descr_rfloordiv = _make_descr_binop(_floordiv)
872 descr_truediv, descr_rtruediv = _make_descr_binop(_truediv)
873 descr_mod, descr_rmod = _make_descr_binop(_mod)
874 descr_divmod, descr_rdivmod = _make_descr_binop(
875 _divmod, ovf2small=_divmod_ovf2small)
876
877 def descr_to_bytes(self, space, length=1, byteorder='big', signed=False):
878 x = self.intval
879 try:
880 byte_string = tobytes_int(x, length, byteorder=byteorder,
881 signed=signed)
882 except InvalidEndiannessError:
883 raise oefmt(space.w_ValueError,
884 "byteorder must be either 'little' or 'big'")
885 except InvalidSignednessError:
886 raise oefmt(space.w_OverflowError,
887 "can't convert negative int to unsigned")
888 except OverflowError:
889 raise oefmt(space.w_OverflowError, "int too big to convert")
890 return space.newbytes(byte_string)
891
892
893 def setup_prebuilt(space):
894 if space.config.objspace.std.withprebuiltint:
895 W_IntObject.PREBUILT = []
896 for i in range(space.config.objspace.std.prebuiltintfrom,
897 space.config.objspace.std.prebuiltintto):
898 W_IntObject.PREBUILT.append(W_IntObject(i))
899 else:
900 W_IntObject.PREBUILT = None
901
902
903 def wrapint(space, x):
904 if not space.config.objspace.std.withprebuiltint:
905 return W_IntObject(x)
906 lower = space.config.objspace.std.prebuiltintfrom
907 upper = space.config.objspace.std.prebuiltintto
908 # use r_uint to perform a single comparison (this whole function is
909 # getting inlined into every caller so keeping the branching to a
910 # minimum is a good idea)
911 index = r_uint(x) - r_uint(lower)
912 if index >= r_uint(upper - lower):
913 w_res = instantiate(W_IntObject)
914 else:
915 w_res = W_IntObject.PREBUILT[index]
916 # obscure hack to help the CPU cache: we store 'x' even into a
917 # prebuilt integer's intval. This makes sure that the intval field
918 # is present in the cache in the common case where it is quickly
919 # reused. (we could use a prefetch hint if we had that)
920 w_res.intval = x
921 return w_res
922
923
924 divmod_near = applevel('''
925 def divmod_near(a, b):
926 """Return a pair (q, r) such that a = b * q + r, and abs(r)
927 <= abs(b)/2, with equality possible only if q is even. In
928 other words, q == a / b, rounded to the nearest integer using
929 round-half-to-even."""
930 q, r = divmod(a, b)
931 # round up if either r / b > 0.5, or r / b == 0.5 and q is
932 # odd. The expression r / b > 0.5 is equivalent to 2 * r > b
933 # if b is positive, 2 * r < b if b negative.
934 greater_than_half = 2*r > b if b > 0 else 2*r < b
935 exactly_half = 2*r == b
936 if greater_than_half or exactly_half and q % 2 == 1:
937 q += 1
938 r -= b
939 return q, r
940 ''', filename=__file__).interphook('divmod_near')
941
942 invmod = applevel('''
943 def invmod(a, n):
944 if n == 1:
945 return 0
946 if a == 1:
947 return 1
948 assert n >= 0
949 b, c = 1, 0
950 while n:
951 q, r = divmod(a, n)
952 a, b, c, n = n, c, b - q*c, r
953 # at this point a is the gcd of the original inputs
954 if a == 1:
955 return b
956 raise ValueError("base is not invertible for the given modulus")
957 ''', filename=__file__).interphook("invmod")
958
959
960 def _recover_with_smalllong(space):
961 """True if there is a chance that a SmallLong would fit when an Int
962 does not
963 """
964 return (space.config.objspace.std.withsmalllong and
965 sys.maxint == 2147483647)
966
967
968 def _string_to_int_or_long(space, w_source, string, base=10):
969 from pypy.module.sys.state import get_int_max_str_digits
970
971 if (base & (base - 1) != 0):
972 # Limit the size to avoid excessive computation attacks on non-binary bases
973 max_str_digits = space.int_w(get_int_max_str_digits(space))
974 else:
975 max_str_digits = 0
976 try:
977 value = string_to_int(string, base, allow_underscores=True,
978 no_implicit_octal=True,
979 max_str_digits=max_str_digits,
980 disallow_whitespace_after_sign=True)
981 return wrapint(space, value)
982 except MaxDigitsError as e:
983 raise oefmt(space.w_ValueError,
984 "Exceeds the limit (%d) for integer string conversion: value has %d digits",
985 max_str_digits, e.digits)
986 except ParseStringError as e:
987 raise wrap_parsestringerror(space, e, w_source)
988 except ParseStringOverflowError as e:
989 return _retry_to_w_long(space, e.parser, w_source)
990
991
992 def _retry_to_w_long(space, parser, w_source):
993 from pypy.objspace.std.longobject import newbigint
994 parser.rewind()
995 try:
996 bigint = rbigint._from_numberstring_parser(parser)
997 except ParseStringError as e:
998 raise wrap_parsestringerror(space, e, w_source)
999 return newbigint(space, space.w_int, bigint)
1000
1001
1002 def _new_int(space, w_inttype, w_x, w_base=None):
1003 w_value = w_x # 'x' is the keyword argument name in CPython
1004 if w_inttype is space.w_int:
1005 return _new_baseint(space, w_x, w_base)
1006 else:
1007 w_tmp = _new_baseint(space, w_x, w_base)
1008 return _as_subint(space, w_inttype, w_tmp)
1009
1010 def _new_baseint(space, w_value, w_base=None):
1011 if w_base is None:
1012 if space.is_w(space.type(w_value), space.w_int):
1013 assert isinstance(w_value, W_AbstractIntObject)
1014 return w_value
1015 elif space.lookup(w_value, '__int__') is not None:
1016 w_intvalue = space.int(w_value)
1017 return _ensure_baseint(space, w_intvalue)
1018 elif space.lookup(w_value, '__trunc__') is not None:
1019 space.warn(space.newtext(
1020 "The delegation of int() to __trunc__ is deprecated."),
1021 space.w_DeprecationWarning)
1022 w_obj = space.trunc(w_value)
1023 if not space.isinstance_w(w_obj, space.w_int):
1024 try:
1025 w_obj = space.index(w_obj)
1026 except OperationError as e:
1027 if not e.match(space, space.w_TypeError):
1028 raise
1029 raise oefmt(
1030 space.w_TypeError,
1031 "__trunc__ returned non-Integral (type '%T')",
1032 w_obj
1033 )
1034 assert isinstance(w_obj, W_AbstractIntObject)
1035 return _ensure_baseint(space, w_obj)
1036 elif space.lookup(w_value, '__index__') is not None:
1037 w_obj = space.index(w_value)
1038 if not space.is_w(space.type(w_obj), space.w_int):
1039 if space.isinstance_w(w_obj, space.w_int):
1040 w_obj = space.int(w_obj)
1041 else:
1042 raise oefmt(space.w_TypeError,
1043 "int() argument must be a string, a bytes-like "
1044 "object or a number, not '%T'", w_value)
1045 assert isinstance(w_obj, W_AbstractIntObject)
1046 return _ensure_baseint(space, w_obj)
1047 elif space.isinstance_w(w_value, space.w_unicode):
1048 from pypy.objspace.std.unicodeobject import unicode_to_decimal_w
1049 try:
1050 b = unicode_to_decimal_w(space, w_value)
1051 except Exception:
1052 raise oefmt(space.w_ValueError,
1053 'invalid literal for int() with base 10: %R',
1054 w_value)
1055 return _string_to_int_or_long(space, w_value, b)
1056 elif (space.isinstance_w(w_value, space.w_bytearray) or
1057 space.isinstance_w(w_value, space.w_bytes)):
1058 return _string_to_int_or_long(space, w_value,
1059 space.charbuf_w(w_value))
1060 else:
1061 # If object supports the buffer interface
1062 try:
1063 buf = space.charbuf_w(w_value)
1064 except OperationError as e:
1065 if not e.match(space, space.w_TypeError):
1066 raise
1067 raise oefmt(space.w_TypeError,
1068 "int() argument must be a string, a bytes-like "
1069 "object or a number, not '%T'", w_value)
1070 else:
1071 return _string_to_int_or_long(space, w_value, buf)
1072 else:
1073 try:
1074 base = space.getindex_w(w_base, None)
1075 except OperationError as e:
1076 if not e.match(space, space.w_OverflowError):
1077 raise
1078 base = 37 # this raises the right error in string_to_bigint()
1079
1080 if space.isinstance_w(w_value, space.w_unicode):
1081 from pypy.objspace.std.unicodeobject import unicode_to_decimal_w
1082 try:
1083 s = unicode_to_decimal_w(space, w_value)
1084 except Exception:
1085 raise oefmt(space.w_ValueError,
1086 'invalid literal for int() with base %d: %R',
1087 base, w_value)
1088 elif (space.isinstance_w(w_value, space.w_bytes) or
1089 space.isinstance_w(w_value, space.w_bytearray)):
1090 s = space.charbuf_w(w_value)
1091 else:
1092 raise oefmt(space.w_TypeError,
1093 "int() can't convert non-string with explicit base")
1094
1095 return _string_to_int_or_long(space, w_value, s, base)
1096
1097 @enforceargs(None, None, W_AbstractIntObject, typecheck=False)
1098 def _as_subint(space, w_inttype, w_value):
1099 from pypy.objspace.std.longobject import W_LongObject, newbigint
1100 if space.config.objspace.std.withsmalllong:
1101 from pypy.objspace.std.smalllongobject import W_SmallLongObject
1102 else:
1103 W_SmallLongObject = None
1104 if type(w_value) is W_IntObject:
1105 w_obj = space.allocate_instance(W_IntObject, w_inttype)
1106 W_IntObject.__init__(w_obj, w_value.intval)
1107 return w_obj
1108 elif type(w_value) is W_LongObject:
1109 return newbigint(space, w_inttype, w_value.num)
1110 elif W_SmallLongObject and type(w_value) is W_SmallLongObject:
1111 return newbigint(space, w_inttype, space.bigint_w(w_value))
1112
1113 @enforceargs(None, W_AbstractIntObject, typecheck=False)
1114 def _ensure_baseint(space, w_intvalue):
1115 from pypy.objspace.std.longobject import (
1116 W_LongObject, W_AbstractLongObject, newlong)
1117 if isinstance(w_intvalue, W_IntObject):
1118 if type(w_intvalue) is not W_IntObject:
1119 w_intvalue = wrapint(space, w_intvalue.intval)
1120 return w_intvalue
1121 elif isinstance(w_intvalue, W_AbstractLongObject):
1122 if type(w_intvalue) is not W_LongObject:
1123 w_intvalue = newlong(space, w_intvalue.asbigint())
1124 return w_intvalue
1125 else:
1126 # shouldn't happen
1127 raise oefmt(space.w_RuntimeError,
1128 "internal error in int.__new__()")
1129
1130
1131 W_AbstractIntObject.typedef = TypeDef("int",
1132 __doc__ = """int([x]) -> integer
1133 int(x, base=10) -> integer
1134
1135 Convert a number or string to an integer, or return 0 if no arguments
1136 are given. If x is a number, return x.__int__(). For floating point
1137 numbers, this truncates towards zero.
1138
1139 If x is not a number or if base is given, then x must be a string,
1140 bytes, or bytearray instance representing an integer literal in the
1141 given base. The literal can be preceded by '+' or '-' and be surrounded
1142 by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
1143 Base 0 means to interpret the base from the string as an integer literal.
1144 >>> int('0b100', base=0)
1145 4""",
1146 __new__ = interp2app(W_IntObject.descr_new),
1147
1148 numerator = typedef.GetSetProperty(
1149 W_AbstractIntObject.descr_get_numerator,
1150 doc="the numerator of a rational number in lowest terms"),
1151 denominator = typedef.GetSetProperty(
1152 W_AbstractIntObject.descr_get_denominator,
1153 doc="the denominator of a rational number in lowest terms"),
1154 real = typedef.GetSetProperty(
1155 W_AbstractIntObject.descr_get_real,
1156 doc="the real part of a complex number"),
1157 imag = typedef.GetSetProperty(
1158 W_AbstractIntObject.descr_get_imag,
1159 doc="the imaginary part of a complex number"),
1160
1161 as_integer_ratio = interp2app(W_AbstractIntObject.descr_as_integer_ratio),
1162
1163 from_bytes = interp2app(W_AbstractIntObject.descr_from_bytes,
1164 as_classmethod=True),
1165 to_bytes = interpindirect2app(W_AbstractIntObject.descr_to_bytes),
1166
1167 __repr__ = interpindirect2app(W_AbstractIntObject.descr_repr),
1168 __str__ = interpindirect2app(W_AbstractIntObject.descr_str),
1169
1170 conjugate = interpindirect2app(W_AbstractIntObject.descr_conjugate),
1171 bit_length = interpindirect2app(W_AbstractIntObject.descr_bit_length),
1172 bit_count = interpindirect2app(W_AbstractIntObject.descr_bit_count),
1173 __format__ = interpindirect2app(W_AbstractIntObject.descr_format),
1174 __hash__ = interpindirect2app(W_AbstractIntObject.descr_hash),
1175 __getnewargs__ = interpindirect2app(W_AbstractIntObject.descr_getnewargs),
1176
1177 __int__ = interpindirect2app(W_AbstractIntObject.int),
1178 __index__ = interpindirect2app(W_AbstractIntObject.descr_index),
1179 __trunc__ = interpindirect2app(W_AbstractIntObject.descr_trunc),
1180 __float__ = interpindirect2app(W_AbstractIntObject.descr_float),
1181 __round__ = interpindirect2app(W_AbstractIntObject.descr_round),
1182
1183 __pos__ = interpindirect2app(W_AbstractIntObject.descr_pos),
1184 __neg__ = interpindirect2app(W_AbstractIntObject.descr_neg),
1185 __abs__ = interpindirect2app(W_AbstractIntObject.descr_abs),
1186 __bool__ = interpindirect2app(W_AbstractIntObject.descr_bool),
1187 __invert__ = interpindirect2app(W_AbstractIntObject.descr_invert),
1188 __floor__ = interpindirect2app(W_AbstractIntObject.descr_floor),
1189 __ceil__ = interpindirect2app(W_AbstractIntObject.descr_ceil),
1190
1191 __lt__ = interpindirect2app(W_AbstractIntObject.descr_lt),
1192 __le__ = interpindirect2app(W_AbstractIntObject.descr_le),
1193 __eq__ = interpindirect2app(W_AbstractIntObject.descr_eq),
1194 __ne__ = interpindirect2app(W_AbstractIntObject.descr_ne),
1195 __gt__ = interpindirect2app(W_AbstractIntObject.descr_gt),
1196 __ge__ = interpindirect2app(W_AbstractIntObject.descr_ge),
1197
1198 __add__ = interpindirect2app(W_AbstractIntObject.descr_add),
1199 __radd__ = interpindirect2app(W_AbstractIntObject.descr_radd),
1200 __sub__ = interpindirect2app(W_AbstractIntObject.descr_sub),
1201 __rsub__ = interpindirect2app(W_AbstractIntObject.descr_rsub),
1202 __mul__ = interpindirect2app(W_AbstractIntObject.descr_mul),
1203 __rmul__ = interpindirect2app(W_AbstractIntObject.descr_rmul),
1204
1205 __and__ = interpindirect2app(W_AbstractIntObject.descr_and),
1206 __rand__ = interpindirect2app(W_AbstractIntObject.descr_rand),
1207 __or__ = interpindirect2app(W_AbstractIntObject.descr_or),
1208 __ror__ = interpindirect2app(W_AbstractIntObject.descr_ror),
1209 __xor__ = interpindirect2app(W_AbstractIntObject.descr_xor),
1210 __rxor__ = interpindirect2app(W_AbstractIntObject.descr_rxor),
1211
1212 __lshift__ = interpindirect2app(W_AbstractIntObject.descr_lshift),
1213 __rlshift__ = interpindirect2app(W_AbstractIntObject.descr_rlshift),
1214 __rshift__ = interpindirect2app(W_AbstractIntObject.descr_rshift),
1215 __rrshift__ = interpindirect2app(W_AbstractIntObject.descr_rrshift),
1216
1217 __floordiv__ = interpindirect2app(W_AbstractIntObject.descr_floordiv),
1218 __rfloordiv__ = interpindirect2app(W_AbstractIntObject.descr_rfloordiv),
1219 __truediv__ = interpindirect2app(W_AbstractIntObject.descr_truediv),
1220 __rtruediv__ = interpindirect2app(W_AbstractIntObject.descr_rtruediv),
1221 __mod__ = interpindirect2app(W_AbstractIntObject.descr_mod),
1222 __rmod__ = interpindirect2app(W_AbstractIntObject.descr_rmod),
1223 __divmod__ = interpindirect2app(W_AbstractIntObject.descr_divmod),
1224 __rdivmod__ = interpindirect2app(W_AbstractIntObject.descr_rdivmod),
1225
1226 __pow__ = interpindirect2app(W_AbstractIntObject.descr_pow),
1227 __rpow__ = interpindirect2app(W_AbstractIntObject.descr_rpow),
1228 )
1229
1230
1231 def _hash_int(a):
1232 # write it without branches for the benefit of the jit
1233 # it needs to give numbers that are equivalent to the hash function of
1234 # rbigint
1235
1236 # compute the sign
1237 sign = 1 - ((a < 0) << 1)
1238 x = r_uint(a)
1239 # take absolute value
1240 x *= r_uint(sign)
1241 # efficient x % HASH_MODULUS: as HASH_MODULUS is a Mersenne
1242 # prime
1243 x = (x & HASH_MODULUS) + (x >> HASH_BITS)
1244
1245 # if x >= HASH_MODULUS:
1246 # x -= HASH_MODULUS
1247 x -= HASH_MODULUS * (x >= HASH_MODULUS)
1248 h = intmask(intmask(x) * sign)
1249 return h - (h == -1)