Debian Codegraph @

rpython/rlib/rbigint.py

raw symbols SCIP
1 from rpython.rlib.rarithmetic import LONG_BIT, intmask, longlongmask, r_uint, r_ulonglong
2 from rpython.rlib.rarithmetic import ovfcheck, r_longlong, widen
3 from rpython.rlib.rarithmetic import most_neg_value_of_same_type
4 from rpython.rlib.rarithmetic import check_support_int128
5 from rpython.rlib.rstring import StringBuilder
6 from rpython.rlib.debug import make_sure_not_resized, check_regular_int
7 from rpython.rlib.objectmodel import we_are_translated, specialize, \
8 not_rpython, newlist_hint, always_inline
9 from rpython.rlib import jit
10 from rpython.rtyper.lltypesystem import lltype, rffi
11 from rpython.rtyper import extregistry
12
13 import math, sys
14
15 SUPPORT_INT128 = check_support_int128()
16 BYTEORDER = sys.byteorder
17
18 # note about digit sizes:
19 # In division, the native integer type must be able to hold
20 # a sign bit plus two digits plus 1 overflow bit.
21
22 #SHIFT = (LONG_BIT // 2) - 1
23 if SUPPORT_INT128:
24 SHIFT = 63
25 UDIGIT_TYPE = r_ulonglong
26 if LONG_BIT >= 64:
27 UDIGIT_MASK = intmask
28 else:
29 UDIGIT_MASK = longlongmask
30 LONG_TYPE = rffi.__INT128_T
31 ULONG_TYPE = rffi.__UINT128_T
32 if LONG_BIT > SHIFT:
33 STORE_TYPE = lltype.Signed
34 UNSIGNED_TYPE = lltype.Unsigned
35 else:
36 STORE_TYPE = rffi.LONGLONG
37 UNSIGNED_TYPE = rffi.ULONGLONG
38 else:
39 SHIFT = 31
40 UDIGIT_TYPE = r_uint
41 UDIGIT_MASK = intmask
42 STORE_TYPE = lltype.Signed
43 UNSIGNED_TYPE = lltype.Unsigned
44 LONG_TYPE = rffi.LONGLONG
45 ULONG_TYPE = rffi.ULONGLONG
46
47 # TODO if LONG_BIT >= 64, it would be best to use r_uint32, but
48 # int32 and uint32 ops are unimplemented
49
50 MASK = int((1 << SHIFT) - 1)
51 FLOAT_MULTIPLIER = float(1 << SHIFT)
52
53 # For BIGINT and INT mix.
54 #
55 # The VALID range of an int is different than a valid range of a bigint of length one.
56 # -1 << LONG_BIT is actually TWO digits, because they are stored without the sign.
57 if SHIFT == LONG_BIT - 1:
58 MIN_INT_VALUE = -1 << SHIFT
59 def int_in_valid_range(x):
60 if x == MIN_INT_VALUE:
61 return False
62 return True
63 else:
64 # Means we don't have INT128 on 64bit.
65 def int_in_valid_range(x):
66 if x > MASK or x < -MASK:
67 return False
68 return True
69
70 int_in_valid_range._always_inline_ = True
71
72 # Debugging digit array access.
73 #
74 # False == no checking at all
75 # True == check 0 <= value <= MASK
76
77
78 # For long multiplication, use the O(N**2) school algorithm unless
79 # both operands contain more than KARATSUBA_CUTOFF digits (this
80 # being an internal Python long digit, in base BASE).
81
82 # Karatsuba is O(N**1.585)
83 USE_KARATSUBA = True # set to False for comparison
84
85 if SHIFT > 31:
86 KARATSUBA_CUTOFF = 19
87 else:
88 KARATSUBA_CUTOFF = 38
89
90 KARATSUBA_SQUARE_CUTOFF = 2 * KARATSUBA_CUTOFF
91
92 # For exponentiation, use the binary left-to-right algorithm
93 # unless the exponent contains more than FIVEARY_CUTOFF digits.
94 # In that case, do 5 bits at a time. The potential drawback is that
95 # a table of 2**5 intermediate results is computed.
96
97 FIVEARY_CUTOFF = 8
98
99 @specialize.argtype(0)
100 def _mask_digit(x):
101 return UDIGIT_MASK(x & MASK)
102
103 def _widen_digit(x):
104 return rffi.cast(LONG_TYPE, x)
105
106 def _unsigned_widen_digit(x):
107 return rffi.cast(ULONG_TYPE, x)
108
109 @specialize.argtype(0)
110 def _store_digit(x):
111 return rffi.cast(STORE_TYPE, x)
112
113 def _load_unsigned_digit(x):
114 return rffi.cast(UNSIGNED_TYPE, x)
115
116 _load_unsigned_digit._always_inline_ = True
117
118 NULLDIGIT = _store_digit(0)
119 ONEDIGIT = _store_digit(1)
120 NULLDIGITS = [NULLDIGIT]
121
122 def _check_digits(l):
123 for x in l:
124 assert type(x) is type(NULLDIGIT)
125 assert UDIGIT_MASK(x) & MASK == UDIGIT_MASK(x)
126
127 class InvalidEndiannessError(Exception):
128 pass
129
130 class InvalidSignednessError(Exception):
131 pass
132
133 class MaxIntError(Exception):
134 pass
135
136
137 class Entry(extregistry.ExtRegistryEntry):
138 _about_ = _check_digits
139
140 def compute_result_annotation(self, s_list):
141 from rpython.annotator import model as annmodel
142 assert isinstance(s_list, annmodel.SomeList)
143 s_DIGIT = self.bookkeeper.valueoftype(type(NULLDIGIT))
144 assert s_DIGIT.contains(s_list.listdef.listitem.s_value)
145
146 def specialize_call(self, hop):
147 hop.exception_cannot_occur()
148
149 def intsign(i):
150 if i == 0:
151 return 0
152 return -1 if i < 0 else 1
153
154 class rbigint(object):
155 """This is a reimplementation of longs using a list of digits."""
156 _immutable_ = True
157 _immutable_fields_ = ["_digits[*]", "_size"]
158
159 def __init__(self, digits=NULLDIGITS, sign=0, size=0):
160 if not we_are_translated():
161 _check_digits(digits)
162 make_sure_not_resized(digits)
163 self._digits = digits
164
165 assert size >= 0
166 self._size = (size or len(digits)) * sign
167
168 def get_sign(self):
169 return intsign(self._size)
170
171 def _set_sign(self, sign):
172 self._size = abs(self._size) * sign
173
174 # __eq__ and __ne__ method exist for testing only, they are not RPython!
175 @not_rpython
176 def __eq__(self, other):
177 if not isinstance(other, rbigint):
178 return NotImplemented
179 return self.eq(other)
180
181 @not_rpython
182 def __ne__(self, other):
183 return not (self == other)
184
185 @specialize.argtype(1)
186 def digit(self, x):
187 """Return the x'th digit, as an int."""
188 return self._digits[x]
189 digit._always_inline_ = True
190
191 def widedigit(self, x):
192 """Return the x'th digit, as a long long int if needed
193 to have enough room to contain two digits."""
194 return _widen_digit(self._digits[x])
195 widedigit._always_inline_ = True
196
197 def uwidedigit(self, x):
198 """Return the x'th digit, as a long long int if needed
199 to have enough room to contain two digits."""
200 return _unsigned_widen_digit(self._digits[x])
201 uwidedigit._always_inline_ = True
202
203 def udigit(self, x):
204 """Return the x'th digit, as an unsigned int."""
205 return _load_unsigned_digit(self._digits[x])
206 udigit._always_inline_ = True
207
208 @specialize.argtype(2)
209 def setdigit(self, x, val):
210 val = _mask_digit(val)
211 assert val >= 0
212 self._digits[x] = _store_digit(val)
213 setdigit._always_inline_ = True
214
215 def numdigits(self):
216 w = abs(self._size)
217 if not w:
218 w = 1
219 assert w > 0
220 return w
221 numdigits._always_inline_ = True
222
223 @staticmethod
224 @jit.elidable
225 def fromint(intval):
226 # This function is marked as pure, so you must not call it and
227 # then modify the result.
228
229 # for hypothesis testing, we want to be able to set SHIFT to a small
230 # number to hit edge cases more easily. so use a slower path if SHIFT
231 # is a nonstandard value
232 if SHIFT != 63 and SHIFT != 31:
233 return rbigint.fromrarith_int(intval)
234 check_regular_int(intval)
235
236 if intval < 0:
237 sign = -1
238 ival = -r_uint(intval)
239 carry = ival >> SHIFT
240 elif intval > 0:
241 sign = 1
242 ival = r_uint(intval)
243 carry = 0
244 else:
245 return NULLRBIGINT
246
247 if SHIFT != LONG_BIT - 1:
248 # Means we don't have INT128 on 64bit.
249 if intval > 0:
250 carry = ival >> SHIFT
251
252 if carry > 0:
253 carry2 = carry >> SHIFT
254 else:
255 carry2 = 0
256
257 if carry2:
258 return rbigint([_store_digit(ival & MASK),
259 _store_digit(carry & MASK),
260 _store_digit(carry2)], sign, 3)
261
262 if carry:
263 return rbigint([_store_digit(ival & MASK),
264 _store_digit(carry)], sign, 2)
265 else:
266 return rbigint([_store_digit(ival & MASK)], sign, 1)
267
268 @staticmethod
269 @jit.elidable
270 def frombool(b):
271 # You must not call this function and then modify the result.
272 if b:
273 return ONERBIGINT
274 return NULLRBIGINT
275
276 @staticmethod
277 @not_rpython
278 def fromlong(l):
279 return rbigint(*args_from_long(l))
280
281 @staticmethod
282 @jit.elidable
283 def fromfloat(dval):
284 """ Create a new bigint object from a float """
285 # This function is not marked as pure because it can raise
286 if math.isinf(dval):
287 raise OverflowError("cannot convert float infinity to integer")
288 if math.isnan(dval):
289 raise ValueError("cannot convert float NaN to integer")
290 return rbigint._fromfloat_finite(dval)
291
292 @staticmethod
293 @jit.elidable
294 def _fromfloat_finite(dval):
295 sign = 1
296 if dval < 0.0:
297 sign = -1
298 dval = -dval
299 frac, expo = math.frexp(dval) # dval = frac*2**expo; 0.0 <= frac < 1.0
300 if expo <= 0:
301 return NULLRBIGINT
302 ndig = (expo-1) // SHIFT + 1 # Number of 'digits' in result
303 v = rbigint([NULLDIGIT] * ndig, sign, ndig)
304 frac = math.ldexp(frac, (expo-1) % SHIFT + 1)
305 for i in range(ndig-1, -1, -1):
306 # use int(int(frac)) as a workaround for a CPython bug:
307 # with frac == 2147483647.0, int(frac) == 2147483647L
308 bits = int(int(frac))
309 v.setdigit(i, bits)
310 frac -= float(bits)
311 frac = math.ldexp(frac, SHIFT)
312 return v
313
314 @staticmethod
315 @jit.elidable
316 @specialize.argtype(0)
317 def fromrarith_int(i):
318 # This function is marked as pure, so you must not call it and
319 # then modify the result.
320 return rbigint(*args_from_rarith_int(i))
321
322 @staticmethod
323 @jit.elidable
324 def fromdecimalstr(s):
325 # This function is marked as elidable, so you must not call it and
326 # then modify the result.
327 return _decimalstr_to_bigint(s)
328
329 @staticmethod
330 @jit.elidable
331 def fromstr(s, base=0, allow_underscores=False):
332 """As string_to_int(), but ignores an optional 'l' or 'L' suffix
333 and returns an rbigint."""
334 from rpython.rlib.rstring import NumberStringParser, \
335 strip_spaces
336 s = literal = strip_spaces(s) # XXX could get rid of this slice
337 end = len(s)
338 if (s.endswith('l') or s.endswith('L')) and base < 22:
339 # in base 22 and above, 'L' is a valid digit! try: long('L',22)
340 end -= 1
341 parser = NumberStringParser(s, literal, base, 'long',
342 allow_underscores=allow_underscores,
343 end=end)
344 return rbigint._from_numberstring_parser(parser)
345
346 @staticmethod
347 def _from_numberstring_parser(parser):
348 return parse_digit_string(parser)
349
350 @staticmethod
351 @jit.elidable
352 def frombytes(s, byteorder, signed):
353 if byteorder not in ('big', 'little'):
354 raise InvalidEndiannessError()
355 if not s:
356 return NULLRBIGINT
357
358 if byteorder == 'big':
359 msb = ord(s[0])
360 itr = range(len(s)-1, -1, -1)
361 else:
362 msb = ord(s[-1])
363 itr = range(0, len(s))
364
365 sign = -1 if msb >= 0x80 and signed else 1
366 accum = _widen_digit(0)
367 accumbits = 0
368 digits = newlist_hint(len(s) * 8 // LONG_BIT + 1)
369 carry = 1
370
371 for i in itr:
372 c = _widen_digit(ord(s[i]))
373 if sign == -1:
374 c = (0xFF ^ c) + carry
375 carry = c >> 8
376 c &= 0xFF
377
378 accum |= c << accumbits
379 accumbits += 8
380 if accumbits >= SHIFT:
381 digits.append(_store_digit(intmask(accum & MASK)))
382 accum >>= SHIFT
383 accumbits -= SHIFT
384
385 if accumbits:
386 digits.append(_store_digit(intmask(accum)))
387 result = rbigint(digits[:], sign)
388 result._normalize()
389 return result
390
391 @jit.elidable
392 def tobytes(self, nbytes, byteorder, signed):
393 if byteorder not in ('big', 'little'):
394 raise InvalidEndiannessError()
395 if not signed and self.get_sign() == -1:
396 raise InvalidSignednessError()
397
398 bswap = byteorder == 'big'
399 d = _widen_digit(0)
400 j = 0
401 imax = self.numdigits()
402 accum = _widen_digit(0)
403 accumbits = 0
404 result = StringBuilder(nbytes)
405 carry = 1
406
407 for i in range(0, imax):
408 d = self.widedigit(i)
409 if self.get_sign() == -1:
410 d = (d ^ MASK) + carry
411 carry = d >> SHIFT
412 d &= MASK
413
414 accum |= d << accumbits
415 if i == imax - 1:
416 # Avoid bogus 0's
417 s = d ^ MASK if self.get_sign() == -1 else d
418 while s:
419 s >>= 1
420 accumbits += 1
421 else:
422 accumbits += SHIFT
423
424 while accumbits >= 8:
425 if j >= nbytes:
426 raise OverflowError()
427 j += 1
428
429 result.append(chr(accum & 0xFF))
430 accum >>= 8
431 accumbits -= 8
432
433 if accumbits:
434 if j >= nbytes:
435 raise OverflowError()
436 j += 1
437
438 if self.get_sign() == -1:
439 # Add a sign bit
440 accum |= (~_widen_digit(0)) << accumbits
441
442 result.append(chr(accum & 0xFF))
443
444 if j < nbytes:
445 signbyte = 0xFF if self.get_sign() == -1 else 0
446 result.append_multiple_char(chr(signbyte), nbytes - j)
447
448 digits = result.build()
449
450 if j == nbytes and nbytes > 0 and signed:
451 # If not already set, we cannot contain the sign bit
452 msb = digits[-1]
453 if (self.get_sign() == -1) != (ord(msb) >= 0x80):
454 raise OverflowError()
455
456 if bswap:
457 # Bah, this is very inefficient. At least it's not
458 # quadratic.
459 length = len(digits)
460 if length >= 0:
461 digits = ''.join([digits[i] for i in range(length-1, -1, -1)])
462 return digits
463
464 @jit.elidable
465 def toint(self):
466 """
467 Get an integer from a bigint object.
468 Raises OverflowError if overflow occurs.
469 """
470 if self.numdigits() > MAX_DIGITS_THAT_CAN_FIT_IN_INT:
471 raise OverflowError
472 return self._toint_helper()
473
474 @jit.elidable
475 def _toint_helper(self):
476 x = self._touint_helper()
477 # Haven't lost any bits so far
478 if self.get_sign() >= 0:
479 res = intmask(x)
480 if res < 0:
481 raise OverflowError
482 else:
483 # Use "-" on the unsigned number, not on the signed number.
484 # This is needed to produce valid C code.
485 res = intmask(-x)
486 if res >= 0:
487 raise OverflowError
488 return res
489
490 def fits_int(self):
491 n = self.numdigits()
492 if n < MAX_DIGITS_THAT_CAN_FIT_IN_INT:
493 return True
494 if n > MAX_DIGITS_THAT_CAN_FIT_IN_INT:
495 return False
496 try:
497 x = self._touint_helper()
498 except OverflowError:
499 return False
500 if self.get_sign() >= 0:
501 res = intmask(x)
502 return res >= 0
503 else:
504 res = intmask(-x)
505 return res < 0
506
507 @jit.elidable
508 def tolonglong(self):
509 return _AsLongLong(self)
510
511 def tobool(self):
512 return self.get_sign() != 0
513
514 @jit.elidable
515 def touint(self):
516 if self.get_sign() == -1:
517 raise ValueError("cannot convert negative integer to unsigned int")
518 return self._touint_helper()
519
520 @jit.elidable
521 def _touint_helper(self):
522 x = r_uint(0)
523 i = self.numdigits() - 1
524 while i >= 0:
525 prev = x
526 x = (x << SHIFT) + self.udigit(i)
527 if (x >> SHIFT) != prev:
528 raise OverflowError("long int too large to convert to unsigned int")
529 i -= 1
530 return x
531
532 @jit.elidable
533 def toulonglong(self):
534 if self.get_sign() == -1:
535 raise ValueError("cannot convert negative integer to unsigned int")
536 return _AsULonglong_ignore_sign(self)
537
538 @jit.elidable
539 def uintmask(self):
540 return _AsUInt_mask(self)
541
542 @jit.elidable
543 def ulonglongmask(self):
544 """Return r_ulonglong(self), truncating."""
545 return _AsULonglong_mask(self)
546
547 @jit.elidable
548 def tofloat(self):
549 return _AsDouble(self)
550
551 @jit.elidable
552 def format(self, digits, prefix='', suffix='', max_str_digits=0):
553 # 'digits' is a string whose length is the base to use,
554 # and where each character is the corresponding digit.
555 return _format(self, digits, prefix, suffix, max_str_digits)
556
557 @jit.elidable
558 def repr(self):
559 try:
560 x = self.toint()
561 except OverflowError:
562 return self.format(BASE10, suffix="L")
563 return str(x) + "L"
564
565 @jit.elidable
566 def str(self, max_str_digits=0):
567 try:
568 x = self.toint()
569 except OverflowError:
570 return self.format(BASE10, max_str_digits=max_str_digits)
571 return str(x)
572
573 @jit.elidable
574 def eq(self, other):
575 if (self.get_sign() != other.get_sign() or
576 self.numdigits() != other.numdigits()):
577 return False
578
579 i = 0
580 ld = self.numdigits()
581 while i < ld:
582 if self.digit(i) != other.digit(i):
583 return False
584 i += 1
585 return True
586
587 @jit.elidable
588 def int_eq(self, iother):
589 """ eq with int """
590 if not int_in_valid_range(iother):
591 # Fallback to Long.
592 return self.eq(rbigint.fromint(iother))
593
594 if self.numdigits() > 1:
595 return False
596
597 return (self.get_sign() * self.digit(0)) == iother
598
599 def ne(self, other):
600 return not self.eq(other)
601
602 def int_ne(self, iother):
603 return not self.int_eq(iother)
604
605 @jit.elidable
606 def lt(self, other):
607 selfsign = self.get_sign()
608 othersign = other.get_sign()
609 if selfsign > othersign:
610 return False
611 if selfsign < othersign:
612 return True
613 ld1 = self.numdigits()
614 ld2 = other.numdigits()
615 if ld1 > ld2:
616 if othersign > 0:
617 return False
618 else:
619 return True
620 elif ld1 < ld2:
621 if othersign > 0:
622 return True
623 else:
624 return False
625 i = ld1 - 1
626 while i >= 0:
627 d1 = self.digit(i)
628 d2 = other.digit(i)
629 if d1 < d2:
630 if othersign > 0:
631 return True
632 else:
633 return False
634 elif d1 > d2:
635 if othersign > 0:
636 return False
637 else:
638 return True
639 i -= 1
640 return False
641
642 @jit.elidable
643 def int_lt(self, iother):
644 """ lt where other is an int """
645
646 if not int_in_valid_range(iother):
647 # Fallback to Long.
648 return self.lt(rbigint.fromint(iother))
649
650 return _x_int_lt(self, iother, False)
651
652 def le(self, other):
653 return not other.lt(self)
654
655 def int_le(self, iother):
656 """ le where iother is an int """
657
658 if not int_in_valid_range(iother):
659 # Fallback to Long.
660 return self.le(rbigint.fromint(iother))
661
662 return _x_int_lt(self, iother, True)
663
664 def gt(self, other):
665 return other.lt(self)
666
667 def int_gt(self, iother):
668 return not self.int_le(iother)
669
670 def ge(self, other):
671 return not self.lt(other)
672
673 def int_ge(self, iother):
674 return not self.int_lt(iother)
675
676 @jit.elidable
677 def hash(self):
678 return _hash(self)
679
680 @jit.elidable
681 def add(self, other):
682 selfsign = self.get_sign()
683 othersign = other.get_sign()
684 if selfsign == 0:
685 return other
686 if othersign == 0:
687 return self
688 if selfsign == othersign:
689 result = _x_add(self, other)
690 else:
691 result = _x_sub(other, self)
692 result._set_sign(result.get_sign() * othersign)
693 return result
694
695 @jit.elidable
696 def int_add(self, iother):
697 selfsign = self.get_sign()
698 if selfsign == 0:
699 return rbigint.fromint(iother)
700 if iother == 0:
701 return self
702 if not int_in_valid_range(iother):
703 # Fallback to long.
704 return self.add(rbigint.fromint(iother))
705
706 othersign = intsign(iother)
707 if selfsign == othersign:
708 result = _x_int_add(self, iother)
709 else:
710 result = _x_int_sub(self, iother)
711 result._set_sign(-result.get_sign())
712 result._set_sign(result.get_sign() * othersign)
713 return result
714
715 @staticmethod
716 @jit.elidable
717 def add_int_int_bigint_result(iself, iother):
718 if not SUPPORT_INT128 or SHIFT != 63 or not int_in_valid_range(iself) or not int_in_valid_range(iother):
719 return rbigint.fromint(iself).int_add(iother)
720 return rbigint._add_int_int_helper(iself, iother)
721
722 @staticmethod
723 def _add_int_int_helper(iself, iother):
724 if iself == 0:
725 return rbigint.fromint(iother)
726 if iother == 0:
727 return rbigint.fromint(iself)
728
729 sign1 = intsign(iself)
730 sign2 = intsign(iother)
731 v1 = abs(iself)
732 v2 = abs(iother)
733
734 if sign1 == sign2:
735 sign = sign1
736 ures = UDIGIT_TYPE(v1) + UDIGIT_TYPE(v2)
737 else:
738 if v1 >= v2:
739 sign = sign1
740 ures = UDIGIT_TYPE(v1) - UDIGIT_TYPE(v2)
741 else:
742 sign = sign2
743 ures = UDIGIT_TYPE(v2) - UDIGIT_TYPE(v1)
744
745 if ures == 0:
746 return NULLRBIGINT
747
748 carry = ures >> SHIFT
749 if carry:
750 return rbigint([_store_digit(ures & MASK), _store_digit(carry)], sign, 2)
751 else:
752 return rbigint([_store_digit(ures & MASK)], sign, 1)
753
754 @jit.elidable
755 def sub(self, other):
756 selfsign = self.get_sign()
757 othersign = other.get_sign()
758 if othersign == 0:
759 return self
760 elif selfsign == 0:
761 return rbigint(other._digits[:other.numdigits()], -othersign, other.numdigits())
762 elif selfsign == othersign:
763 result = _x_sub(self, other)
764 else:
765 result = _x_add(self, other)
766 result._set_sign(result.get_sign() * selfsign)
767 return result
768
769 @jit.elidable
770 def int_sub(self, iother):
771 selfsign = self.get_sign()
772 if not int_in_valid_range(iother):
773 # Fallback to long.
774 return self.sub(rbigint.fromint(iother))
775 elif iother == 0:
776 return self
777 elif selfsign == 0:
778 return rbigint.fromint(-iother)
779 elif selfsign == intsign(iother):
780 result = _x_int_sub(self, iother)
781 else:
782 result = _x_int_add(self, iother)
783 result._set_sign(result.get_sign() * selfsign)
784 return result
785
786 @staticmethod
787 @jit.elidable
788 def sub_int_int_bigint_result(iself, iother):
789 if not SUPPORT_INT128 or SHIFT != 63 or not int_in_valid_range(iself) or not int_in_valid_range(iother):
790 return rbigint.fromint(iself).int_sub(iother)
791 # -iother is safe here because int_in_valid_range(iother)
792 # checks that it's not minint
793 return rbigint._add_int_int_helper(iself, -iother)
794
795 @jit.elidable
796 def mul(self, other):
797 selfsize = self.numdigits()
798 othersize = other.numdigits()
799 selfsign = self.get_sign()
800 othersign = other.get_sign()
801
802 if selfsize > othersize:
803 self, other, selfsize, othersize = other, self, othersize, selfsize
804
805 if selfsign == 0 or othersign == 0:
806 return NULLRBIGINT
807
808 if selfsize == 1:
809 if self._digits[0] == ONEDIGIT:
810 return rbigint(other._digits[:othersize], selfsign * othersign, othersize)
811 elif othersize == 1:
812 res = other.uwidedigit(0) * self.udigit(0)
813 carry = res >> SHIFT
814 if carry:
815 return rbigint([_store_digit(res & MASK), _store_digit(carry)], selfsign * othersign, 2)
816 else:
817 return rbigint([_store_digit(res & MASK)], selfsign * othersign, 1)
818
819 result = _x_mul(self, other, self.digit(0))
820 elif USE_KARATSUBA:
821 if self is other:
822 i = KARATSUBA_SQUARE_CUTOFF
823 else:
824 i = KARATSUBA_CUTOFF
825
826 if selfsize <= i:
827 result = _x_mul(self, other)
828 else:
829 result = _k_mul(self, other)
830 else:
831 result = _x_mul(self, other)
832
833 result._set_sign(selfsign * othersign)
834 return result
835
836 @jit.elidable
837 def int_mul(self, iother):
838 if not int_in_valid_range(iother):
839 # Fallback to long.
840 return self.mul(rbigint.fromint(iother))
841
842 selfsign = self.get_sign()
843 if selfsign == 0 or iother == 0:
844 return NULLRBIGINT
845
846 asize = self.numdigits()
847 digit = abs(iother)
848
849 othersign = intsign(iother)
850
851 if digit == 1:
852 if othersign == 1:
853 return self
854 return rbigint(self._digits[:asize], selfsign * othersign, asize)
855 elif asize == 1:
856 udigit = r_uint(digit)
857 res = self.uwidedigit(0) * udigit
858 carry = res >> SHIFT
859 if carry:
860 return rbigint([_store_digit(res & MASK), _store_digit(carry)], selfsign * othersign, 2)
861 else:
862 return rbigint([_store_digit(res & MASK)], selfsign * othersign, 1)
863 elif digit & (digit - 1) == 0:
864 result = self.lqshift(ptwotable[digit])
865 else:
866 result = _muladd1(self, digit)
867
868 result._set_sign(selfsign * othersign)
869 return result
870
871 @staticmethod
872 @jit.elidable
873 def mul_int_int_bigint_result(iself, iother):
874 if not SUPPORT_INT128 or SHIFT != 63 or not int_in_valid_range(iself):
875 return rbigint.fromint(iself).int_mul(iother)
876 if iself == 0 or iother == 0:
877 return NULLRBIGINT
878 selfsign = intsign(iself)
879 othersign = intsign(iother)
880 otherdigit = r_uint(iother)
881 if iother < 0: # can use abs because of minint
882 otherdigit = -otherdigit
883 res = _unsigned_widen_digit(abs(iself)) * otherdigit
884 carry = res >> SHIFT
885 if carry:
886 return rbigint([_store_digit(res & MASK), _store_digit(carry)], selfsign * othersign, 2)
887 else:
888 return rbigint([_store_digit(res & MASK)], selfsign * othersign, 1)
889
890 @jit.elidable
891 def truediv(self, other):
892 div = _bigint_true_divide(self, other)
893 return div
894
895 def floordiv(self, other):
896 div, mod = self.divmod(other)
897 return div
898
899 def div(self, other):
900 return self.floordiv(other)
901
902 @jit.elidable
903 def int_floordiv(self, iother):
904 if not int_in_valid_range(iother):
905 # Fallback to long.
906 return self.floordiv(rbigint.fromint(iother))
907
908 if iother == 0:
909 raise ZeroDivisionError("long division by zero")
910
911 digit = abs(iother)
912 assert digit > 0
913
914 selfsign = self.get_sign()
915 if selfsign == 1 and iother > 0:
916 if digit == 1:
917 return self
918 elif digit & (digit - 1) == 0:
919 return self.rqshift(ptwotable[digit])
920
921 div, mod = _divrem1(self, digit)
922
923 othersign = intsign(iother)
924 if mod != 0 and selfsign * othersign == -1:
925 if div.get_sign() == 0:
926 return ONENEGATIVERBIGINT
927 div = div.int_add(1)
928 div._set_sign(selfsign * othersign)
929 div._normalize()
930 return div
931
932 def int_div(self, iother):
933 return self.int_floordiv(iother)
934
935 def mod(self, other):
936 div, mod = self.divmod(other)
937 return mod
938
939 @jit.elidable
940 def int_mod(self, iother):
941 if iother == 0:
942 raise ZeroDivisionError("long division or modulo by zero")
943 selfsign = self.get_sign()
944 if selfsign == 0:
945 return NULLRBIGINT
946
947 elif not int_in_valid_range(iother):
948 # Fallback to long.
949 return self.mod(rbigint.fromint(iother))
950
951 if 1: # preserve indentation to preserve history
952 digit = abs(iother)
953 if digit == 1:
954 return NULLRBIGINT
955 elif digit == 2:
956 modm = self.digit(0) & 1
957 if modm:
958 return ONENEGATIVERBIGINT if iother < 0 else ONERBIGINT
959 return NULLRBIGINT
960 elif digit & (digit - 1) == 0:
961 mod = self.int_and_(digit - 1)
962 else:
963 rem = _int_rem_core(self, digit)
964 if rem == 0:
965 return NULLRBIGINT
966 mod = rbigint([rem], -1 if selfsign < 0 else 1, 1)
967
968 if mod.get_sign() * intsign(iother) == -1:
969 mod = mod.int_add(iother)
970 return mod
971
972 @jit.elidable
973 def int_mod_int_result(self, iother):
974 selfsign = self.get_sign()
975 if iother == 0:
976 raise ZeroDivisionError("long division or modulo by zero")
977 if selfsign == 0:
978 return 0
979
980 elif not int_in_valid_range(iother):
981 # Fallback to long.
982 return self.mod(rbigint.fromint(iother)).toint() # cannot raise
983
984 assert iother != -sys.maxint-1 # covered by int_in_valid_range above
985 digit = abs(iother)
986 if digit == 1:
987 return 0
988 elif digit == 2:
989 modm = self.digit(0) & 1
990 if modm:
991 return -1 if iother < 0 else 1
992 return 0
993 elif digit & (digit - 1) == 0:
994 mod = self.int_and_(digit - 1).toint() # XXX improve
995 else:
996 mod = _int_rem_core(self, digit) * selfsign
997 if intsign(mod) * intsign(iother) == -1:
998 mod = mod + iother
999 return mod
1000
1001 @jit.elidable
1002 def divmod(self, other):
1003 """
1004 The / and % operators are now defined in terms of divmod().
1005 The expression a mod b has the value a - b*floor(a/b).
1006 The _divrem function gives the remainder after division of
1007 |a| by |b|, with the sign of a. This is also expressed
1008 as a - b*trunc(a/b), if trunc truncates towards zero.
1009 Some examples:
1010 a b a rem b a mod b
1011 13 10 3 3
1012 -13 10 -3 7
1013 13 -10 3 -7
1014 -13 -10 -3 -3
1015 So, to get from rem to mod, we have to add b if a and b
1016 have different signs. We then subtract one from the 'div'
1017 part of the outcome to keep the invariant intact.
1018 """
1019 selfsign = self.get_sign()
1020 othersign = other.get_sign()
1021 if othersign == 0:
1022 raise ZeroDivisionError("long division or modulo by zero")
1023 if selfsign == 0:
1024 return TWO_NULLRBIGINTS
1025 if other.numdigits() == 1 and not (-1 == othersign != selfsign):
1026 otherint = other.digit(0) * othersign
1027 assert int_in_valid_range(otherint)
1028 return self.int_divmod(otherint)
1029
1030 if self.numdigits() > 1.2 * other.numdigits() and \
1031 other.numdigits() > HOLDER.DIV_LIMIT * 2: # * 2 to offset setup cost
1032 res = divmod_big(self, other)
1033 # be paranoid: keep the assert here for a bit
1034 div, mod = res
1035 assert div.mul(other).add(mod).eq(self)
1036 return res
1037
1038 return self._divmod_small(other)
1039
1040 def _divmod_small(self, other):
1041 div, mod = _divrem(self, other)
1042 if mod.get_sign() * other.get_sign() == -1:
1043 mod = mod.add(other)
1044 if div.get_sign() == 0:
1045 return ONENEGATIVERBIGINT, mod
1046 div = div.int_sub(1)
1047 return div, mod
1048
1049 @jit.elidable
1050 def int_divmod(self, iother):
1051 """ Divmod with int """
1052
1053 if iother == 0:
1054 raise ZeroDivisionError("long division or modulo by zero")
1055
1056 selfsign = self.get_sign()
1057 othersign = intsign(iother)
1058 if not int_in_valid_range(iother) or (othersign == -1 and selfsign != othersign):
1059 # Just fallback.
1060 return self.divmod(rbigint.fromint(iother))
1061
1062 digit = abs(iother)
1063 assert digit > 0
1064
1065 div, mod = _divrem1(self, digit)
1066 # _divrem1 doesn't fix the sign
1067 if div._size == 0:
1068 assert div.get_sign() == 0
1069 else:
1070 div._set_sign(selfsign * othersign)
1071 if selfsign < 0:
1072 mod = -mod
1073 if mod and selfsign * othersign == -1:
1074 mod += iother
1075 if div.get_sign() == 0:
1076 div = ONENEGATIVERBIGINT
1077 else:
1078 div = div.int_sub(1)
1079 mod = rbigint.fromint(mod)
1080 return div, mod
1081
1082 @jit.elidable
1083 def pow(self, other, modulus=None):
1084 selfsign = self.get_sign()
1085 othersign = other.get_sign()
1086 negativeOutput = False # if x<0 return negative output
1087
1088 # 5-ary values. If the exponent is large enough, table is
1089 # precomputed so that table[i] == self**i % modulus for i in range(32).
1090 # python translation: the table is computed when needed.
1091
1092 if othersign < 0: # if exponent is negative
1093 if modulus is not None:
1094 raise TypeError(
1095 "pow() 2nd argument "
1096 "cannot be negative when 3rd argument specified")
1097 raise ValueError("bigint pow() too negative")
1098
1099 size_b = UDIGIT_TYPE(other.numdigits())
1100
1101 if modulus is not None:
1102 modulussign = modulus.get_sign()
1103 if modulussign == 0:
1104 raise ValueError("pow() 3rd argument cannot be 0")
1105
1106 if modulussign < 0:
1107 negativeOutput = True
1108 modulus = modulus.neg()
1109
1110 # if modulus == 1:
1111 # return 0
1112 if modulus.numdigits() == 1 and modulus._digits[0] == ONEDIGIT:
1113 return NULLRBIGINT
1114
1115 # Reduce base by modulus in some cases:
1116 # 1. If base < 0. Forcing the base non-neg makes things easier.
1117 # 2. If base is obviously larger than the modulus. The "small
1118 # exponent" case later can multiply directly by base repeatedly,
1119 # while the "large exponent" case multiplies directly by base 31
1120 # times. It can be unboundedly faster to multiply by
1121 # base % modulus instead.
1122 # We could _always_ do this reduction, but mod() isn't cheap,
1123 # so we only do it when it buys something.
1124 if selfsign < 0 or self.numdigits() > modulus.numdigits():
1125 self = self.mod(modulus)
1126 elif othersign == 0:
1127 return ONERBIGINT
1128 elif selfsign == 0:
1129 return NULLRBIGINT
1130 elif size_b == 1:
1131 if other._digits[0] == ONEDIGIT:
1132 return self
1133 elif self.numdigits() == 1 and modulus is None:
1134 adigit = self.digit(0)
1135 digit = other.digit(0)
1136 if adigit == 1:
1137 if selfsign == -1 and digit % 2:
1138 return ONENEGATIVERBIGINT
1139 return ONERBIGINT
1140 elif adigit & (adigit - 1) == 0:
1141 ret = self.lshift(((digit-1)*(ptwotable[adigit]-1)) + digit-1)
1142 if selfsign == -1 and not digit % 2:
1143 ret._set_sign(1)
1144 return ret
1145
1146 # At this point self, other, and modulus are guaranteed non-negative UNLESS
1147 # modulus is NULL, in which case self may be negative. */
1148
1149 z = ONERBIGINT
1150
1151 # python adaptation: moved macros REDUCE(X) and MULT(X, Y, result)
1152 # into helper function result = _help_mult(x, y, c)
1153 if size_b <= FIVEARY_CUTOFF:
1154 # Left-to-right binary exponentiation (HAC Algorithm 14.79)
1155 # http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1156
1157 while size_b > 0:
1158 size_b -= 1
1159 bi = other.digit(size_b)
1160 j = 1 << (SHIFT-1)
1161 while j != 0:
1162 z = _help_mult(z, z, modulus)
1163 if bi & j:
1164 z = _help_mult(z, self, modulus)
1165 j >>= 1
1166
1167
1168 else:
1169 # Left-to-right 5-ary exponentiation (HAC Algorithm 14.82)
1170 # This is only useful in the case where modulus != None.
1171 # z still holds 1L
1172 table = [z] * 32
1173 table[0] = z
1174 for i in range(1, 32):
1175 table[i] = _help_mult(table[i-1], self, modulus)
1176
1177 # Note that here SHIFT is not a multiple of 5. The difficulty
1178 # is to extract 5 bits at a time from 'other', starting from the
1179 # most significant digits, so that at the end of the algorithm
1180 # it falls exactly to zero.
1181 # m = max number of bits = i * SHIFT
1182 # m+ = m rounded up to the next multiple of 5
1183 # j = (m+) % SHIFT = (m+) - (i * SHIFT)
1184 # (computed without doing "i * SHIFT", which might overflow)
1185 j = size_b % 5
1186 j = _jmapping[j]
1187 if not we_are_translated():
1188 assert j == (size_b*SHIFT+4)//5*5 - size_b*SHIFT
1189 #
1190 accum = r_uint(0)
1191 while True:
1192 j -= 5
1193 if j >= 0:
1194 index = (accum >> j) & 0x1f
1195 else:
1196 # 'accum' does not have enough digit.
1197 # must get the next digit from 'other' in order to complete
1198 if size_b == 0:
1199 break # Done
1200
1201 size_b -= 1
1202 assert size_b >= 0
1203 bi = other.udigit(size_b)
1204 index = ((accum << (-j)) | (bi >> (j+SHIFT))) & 0x1f
1205 accum = bi
1206 j += SHIFT
1207 #
1208 for k in range(5):
1209 z = _help_mult(z, z, modulus)
1210 if index:
1211 z = _help_mult(z, table[index], modulus)
1212 #
1213 assert j == -5
1214
1215 if negativeOutput and z.get_sign() != 0:
1216 z = z.sub(modulus)
1217 return z
1218
1219 @jit.elidable
1220 def int_pow(self, iother, modulus=None):
1221 negativeOutput = False # if x<0 return negative output
1222
1223 # 5-ary values. If the exponent is large enough, table is
1224 # precomputed so that table[i] == self**i % modulus for i in range(32).
1225 # python translation: the table is computed when needed.
1226
1227 if iother < 0: # if exponent is negative
1228 if modulus is not None:
1229 raise TypeError(
1230 "pow() 2nd argument "
1231 "cannot be negative when 3rd argument specified")
1232 raise ValueError("bigint pow() too negative")
1233
1234 selfsign = self.get_sign()
1235 assert iother >= 0
1236 if modulus is not None:
1237 modulussign = modulus.get_sign()
1238 if modulussign == 0:
1239 raise ValueError("pow() 3rd argument cannot be 0")
1240
1241 if modulussign < 0:
1242 negativeOutput = True
1243 modulus = modulus.neg()
1244
1245 # if modulus == 1:
1246 # return 0
1247 if modulus.numdigits() == 1 and modulus._digits[0] == ONEDIGIT:
1248 return NULLRBIGINT
1249
1250 # Reduce base by modulus in some cases:
1251 # 1. If base < 0. Forcing the base non-neg makes things easier.
1252 # 2. If base is obviously larger than the modulus. The "small
1253 # exponent" case later can multiply directly by base repeatedly,
1254 # while the "large exponent" case multiplies directly by base 31
1255 # times. It can be unboundedly faster to multiply by
1256 # base % modulus instead.
1257 # We could _always_ do this reduction, but mod() isn't cheap,
1258 # so we only do it when it buys something.
1259 if selfsign < 0 or self.numdigits() > modulus.numdigits():
1260 self = self.mod(modulus)
1261 elif iother == 0:
1262 return ONERBIGINT
1263 elif selfsign == 0:
1264 return NULLRBIGINT
1265 elif iother == 1:
1266 return self
1267 elif self.numdigits() == 1:
1268 adigit = self.digit(0)
1269 if adigit == 1:
1270 if selfsign == -1 and iother % 2:
1271 return ONENEGATIVERBIGINT
1272 return ONERBIGINT
1273 elif adigit & (adigit - 1) == 0:
1274 ret = self.lshift(((iother-1)*(ptwotable[adigit]-1)) + iother-1)
1275 if selfsign == -1 and not iother % 2:
1276 ret._set_sign(1)
1277 return ret
1278
1279 # At this point self, iother, and modulus are guaranteed non-negative UNLESS
1280 # modulus is NULL, in which case self may be negative. */
1281
1282 z = ONERBIGINT
1283
1284 # Left-to-right binary exponentiation (HAC Algorithm 14.79)
1285 # http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1286 j = 1 << (LONG_BIT-2)
1287
1288 while j != 0:
1289 z = _help_mult(z, z, modulus)
1290 if iother & j:
1291 z = _help_mult(z, self, modulus)
1292 j >>= 1
1293
1294 if negativeOutput and z.get_sign() != 0:
1295 z = z.sub(modulus)
1296 return z
1297
1298 @jit.elidable
1299 def neg(self):
1300 return rbigint(self._digits, -self.get_sign(), self.numdigits())
1301
1302 @jit.elidable
1303 def abs(self):
1304 selfsign = self.get_sign()
1305 if selfsign != -1:
1306 return self
1307 return rbigint(self._digits, abs(selfsign), self.numdigits())
1308
1309 @jit.elidable
1310 def invert(self): #Implement ~x as -(x + 1)
1311 if self.get_sign() == 0:
1312 return ONENEGATIVERBIGINT
1313
1314 ret = self.int_add(1)
1315 ret._set_sign(-ret.get_sign())
1316 return ret
1317
1318 @jit.elidable
1319 def lshift(self, int_other):
1320 selfsign = self.get_sign()
1321 if int_other < 0:
1322 raise ValueError("negative shift count")
1323 elif int_other == 0 or selfsign == 0:
1324 return self
1325
1326 # wordshift, remshift = divmod(int_other, SHIFT)
1327 wordshift = int_other // SHIFT
1328 remshift = int_other - wordshift * SHIFT
1329 hishift = SHIFT - remshift
1330
1331 if not remshift:
1332 # So we can avoid problems with eq, AND avoid the need for normalize.
1333 return rbigint([NULLDIGIT] * wordshift + self._digits, selfsign, self.numdigits() + wordshift)
1334
1335 oldsize = self.numdigits()
1336 newsize = oldsize + wordshift + 1
1337 z = rbigint([NULLDIGIT] * newsize, selfsign, newsize)
1338 j = 0
1339 prevdigit = NULLDIGIT
1340 while j < oldsize:
1341 digit = self.udigit(j)
1342 newdigit = (digit << remshift) | (prevdigit >> hishift)
1343 z.setdigit(wordshift, newdigit)
1344 prevdigit = digit
1345 wordshift += 1
1346 j += 1
1347
1348 newsize -= 1
1349 assert newsize >= 0
1350 z.setdigit(newsize, prevdigit >> hishift)
1351
1352 z._normalize()
1353 return z
1354 lshift._always_inline_ = True # It's so fast that it's always beneficial.
1355
1356 @jit.elidable
1357 def lqshift(self, int_other):
1358 " A quicker one with much less checks, int_other is valid and for the most part constant."
1359 assert int_other > 0
1360
1361 oldsize = self.numdigits()
1362 selfsign = self.get_sign()
1363
1364 z = rbigint([NULLDIGIT] * (oldsize + 1), selfsign, (oldsize + 1))
1365 i = 0
1366 hishift = SHIFT - int_other
1367 prevdigit = NULLDIGIT
1368 while i < oldsize:
1369 digit = self.udigit(i)
1370 newdigit = (digit << int_other) | (prevdigit >> hishift)
1371 z.setdigit(i, newdigit)
1372 prevdigit = digit
1373 i += 1
1374 z.setdigit(oldsize, prevdigit >> hishift)
1375 z._normalize()
1376 return z
1377 lqshift._always_inline_ = True # It's so fast that it's always beneficial.
1378
1379 @staticmethod
1380 @jit.elidable
1381 def lshift_int_int_bigint_result(iself, int_other):
1382 if not SUPPORT_INT128 or SHIFT != 63 or not int_in_valid_range(iself):
1383 return rbigint.fromint(iself).lshift(int_other)
1384 if int_other < 0:
1385 raise ValueError("negative shift count")
1386
1387 if iself == 0:
1388 return NULLRBIGINT
1389 if int_other == 0:
1390 return rbigint.fromint(iself)
1391
1392 selfsign = intsign(iself)
1393
1394 wordshift = int_other // SHIFT
1395 remshift = int_other - wordshift * SHIFT
1396 hishift = SHIFT - remshift
1397
1398 if iself < 0:
1399 ival = -r_uint(iself)
1400 carry = ival >> SHIFT
1401 assert not carry
1402 else:
1403 assert iself > 0
1404 ival = r_uint(iself)
1405
1406 if remshift:
1407 lowerdigit = ival << remshift
1408 upperdigit = ival >> hishift
1409 if upperdigit:
1410 resdigits = [NULLDIGIT] * (wordshift + 2)
1411 resdigits[wordshift] = _store_digit(lowerdigit & MASK)
1412 resdigits[wordshift + 1] = _store_digit(upperdigit & MASK)
1413 return rbigint(resdigits, selfsign, wordshift + 2)
1414 else:
1415 lowerdigit = ival
1416 # don't need to normalize
1417 resdigits = [NULLDIGIT] * (wordshift + 1)
1418 resdigits[wordshift] = _store_digit(lowerdigit & MASK)
1419 return rbigint(resdigits, selfsign, wordshift + 1)
1420
1421 @jit.elidable
1422 def rshift(self, int_other, dont_invert=False):
1423 if int_other < 0:
1424 raise ValueError("negative shift count")
1425 elif int_other == 0:
1426 return self
1427 selfsign = self.get_sign()
1428 if selfsign == -1 and not dont_invert:
1429 a = self.invert().rshift(int_other)
1430 return a.invert()
1431
1432 wordshift = int_other / SHIFT
1433 newsize = self.numdigits() - wordshift
1434 if newsize <= 0:
1435 return NULLRBIGINT
1436
1437 loshift = int_other % SHIFT
1438 hishift = SHIFT - loshift
1439 z = rbigint([NULLDIGIT] * newsize, selfsign, newsize)
1440 i = 0
1441 while i < newsize:
1442 newdigit = (self.digit(wordshift) >> loshift)
1443 if i+1 < newsize:
1444 newdigit |= (self.digit(wordshift+1) << hishift)
1445 z.setdigit(i, newdigit)
1446 i += 1
1447 wordshift += 1
1448 z._normalize()
1449 return z
1450 rshift._always_inline_ = 'try' # It's so fast that it's always benefitial.
1451
1452 @jit.elidable
1453 def rqshift(self, int_other):
1454 wordshift = int_other / SHIFT
1455 loshift = int_other % SHIFT
1456 newsize = self.numdigits() - wordshift
1457
1458 if newsize <= 0:
1459 return NULLRBIGINT
1460
1461 hishift = SHIFT - loshift
1462 selfsign = self.get_sign()
1463 z = rbigint([NULLDIGIT] * newsize, selfsign, newsize)
1464 i = 0
1465
1466 while i < newsize:
1467 digit = self.udigit(wordshift)
1468 newdigit = (digit >> loshift)
1469 if i+1 < newsize:
1470 newdigit |= (self.udigit(wordshift+1) << hishift)
1471 z.setdigit(i, newdigit)
1472 i += 1
1473 wordshift += 1
1474 z._normalize()
1475 return z
1476 rshift._always_inline_ = 'try' # It's so fast that it's always beneficial.
1477
1478 @jit.elidable
1479 def abs_rshift_and_mask(self, bigshiftcount, mask):
1480 assert isinstance(bigshiftcount, r_ulonglong)
1481 assert mask >= 0
1482 wordshift = bigshiftcount / SHIFT
1483 numdigits = self.numdigits()
1484 if wordshift >= numdigits:
1485 return 0
1486 wordshift = intmask(wordshift)
1487 loshift = intmask(intmask(bigshiftcount) - intmask(wordshift * SHIFT))
1488 lastdigit = self.digit(wordshift) >> loshift
1489 if mask > (MASK >> loshift) and wordshift + 1 < numdigits:
1490 hishift = SHIFT - loshift
1491 lastdigit |= self.digit(wordshift+1) << hishift
1492 if SHIFT != LONG_BIT - 1:
1493 # Means we don't have INT128 on 64bit.
1494 if mask > (MASK << (SHIFT - loshift)) and wordshift + 2 < numdigits:
1495 hishift = 2*SHIFT - loshift
1496 lastdigit |= self.digit(wordshift+2) << hishift
1497 return lastdigit & mask
1498
1499 @staticmethod
1500 def from_list_n_bits(list, nbits):
1501 if len(list) == 0:
1502 return NULLRBIGINT
1503
1504 if nbits == SHIFT:
1505 z = rbigint(list, 1)
1506 else:
1507 if not (1 <= nbits < SHIFT):
1508 raise ValueError
1509
1510 lllength = (r_ulonglong(len(list)) * nbits) // SHIFT
1511 length = intmask(lllength) + 1
1512 z = rbigint([NULLDIGIT] * length, 1)
1513
1514 out = 0
1515 i = 0
1516 accum = 0
1517 for input in list:
1518 accum |= (input << i)
1519 original_i = i
1520 i += nbits
1521 if i > SHIFT:
1522 z.setdigit(out, accum)
1523 out += 1
1524 accum = input >> (SHIFT - original_i)
1525 i -= SHIFT
1526 assert out < length
1527 z.setdigit(out, accum)
1528
1529 z._normalize()
1530 return z
1531
1532 @jit.elidable
1533 def and_(self, other):
1534 return _bitwise(self, '&', other)
1535
1536 @jit.elidable
1537 def int_and_(self, iother):
1538 return _int_bitwise(self, '&', iother)
1539
1540 @jit.elidable
1541 def xor(self, other):
1542 return _bitwise(self, '^', other)
1543
1544 @jit.elidable
1545 def int_xor(self, iother):
1546 return _int_bitwise(self, '^', iother)
1547
1548 @jit.elidable
1549 def or_(self, other):
1550 return _bitwise(self, '|', other)
1551
1552 @jit.elidable
1553 def int_or_(self, iother):
1554 return _int_bitwise(self, '|', iother)
1555
1556 @jit.elidable
1557 def oct(self):
1558 if self.get_sign() == 0:
1559 return '0L'
1560 else:
1561 return _format(self, BASE8, '0', 'L')
1562
1563 @jit.elidable
1564 def hex(self):
1565 return _format(self, BASE16, '0x', 'L')
1566
1567 @jit.elidable
1568 def log(self, base):
1569 # base is supposed to be positive or 0.0, which means we use e
1570 if base == 10.0:
1571 return _loghelper(math.log10, self)
1572 if base == 2.0:
1573 from rpython.rlib import rfloat
1574 return _loghelper(rfloat.log2, self)
1575 ret = _loghelper(math.log, self)
1576 if base != 0.0:
1577 ret /= math.log(base)
1578 return ret
1579
1580 @not_rpython
1581 def tolong(self):
1582 l = 0L
1583 digits = list(self._digits)
1584 digits.reverse()
1585 for d in digits:
1586 l = l << SHIFT
1587 l += intmask(d)
1588 result = l * self.get_sign()
1589 if result == 0:
1590 assert self.get_sign() == 0
1591 return result
1592
1593 def _normalize(self):
1594 i = self.numdigits()
1595
1596 while i > 1 and self._digits[i - 1] == NULLDIGIT:
1597 i -= 1
1598 assert i > 0
1599
1600 self._size = i * self.get_sign()
1601 if i == 1 and self._digits[0] == NULLDIGIT:
1602 self._size = 0
1603 self._digits = NULLDIGITS
1604
1605 _normalize._always_inline_ = True
1606
1607 @jit.elidable
1608 def bit_length(self):
1609 i = self.numdigits()
1610 if i == 1 and self._digits[0] == NULLDIGIT:
1611 return 0
1612 msd = self.digit(i - 1)
1613 msd_bits = bits_in_digit(msd)
1614 # yes, this can overflow: a huge number which fits 3 gigabytes of
1615 # memory has around 24 gigabits!
1616 bits = ovfcheck((i-1) * SHIFT) + msd_bits
1617 return bits
1618
1619 @jit.elidable
1620 def bit_count(self):
1621 res = 0
1622 for i in range(self.numdigits()):
1623 res = ovfcheck(res + bit_count_digit(self.digit(i)))
1624 return res
1625
1626 def gcd(self, other):
1627 """ Compute the (always positive) greatest common divisor of self and
1628 other """
1629 return gcd_lehmer(self.abs(), other.abs())
1630
1631 def isqrt(self):
1632 """ Compute the integer square root of self """
1633 if self.int_lt(0):
1634 raise ValueError("isqrt() argument must be nonnegative")
1635 if self.int_eq(0):
1636 return NULLRBIGINT
1637 c = (self.bit_length() - 1) // 2
1638 a = ONERBIGINT
1639 d = 0
1640 for s in range(bits_in_digit(_store_digit(c)) - 1, -1, -1):
1641 # Loop invariant: (a-1)**2 < (self >> 2*(c - d)) < (a+1)**2
1642 e = d
1643 d = c >> s
1644 a = a.lshift(d - e - 1).add(self.rshift(2*c - e - d + 1).floordiv(a))
1645 return a.int_sub(a.mul(a).gt(self))
1646
1647 def __repr__(self):
1648 return "<rbigint digits=%s, sign=%s, size=%d, len=%d, %s>" % (self._digits,
1649 self.get_sign(), self.numdigits(), len(self._digits),
1650 self.tolong())
1651
1652 ONERBIGINT = rbigint([ONEDIGIT], 1, 1)
1653 ONENEGATIVERBIGINT = rbigint([ONEDIGIT], -1, 1)
1654 NULLRBIGINT = rbigint()
1655
1656 TWO_NULLRBIGINTS = (NULLRBIGINT, NULLRBIGINT)
1657
1658 _jmapping = [(5 * SHIFT) % 5,
1659 (4 * SHIFT) % 5,
1660 (3 * SHIFT) % 5,
1661 (2 * SHIFT) % 5,
1662 (1 * SHIFT) % 5]
1663
1664
1665
1666 #_________________________________________________________________
1667
1668 # Helper Functions
1669
1670
1671 def _help_mult(x, y, c):
1672 """
1673 Multiply two values, then reduce the result:
1674 result = X*Y % c. If c is None, skip the mod.
1675 """
1676 res = x.mul(y)
1677 # Perform a modular reduction, X = X % c, but leave X alone if c
1678 # is NULL.
1679 if c is not None:
1680 res = res.mod(c)
1681
1682 return res
1683
1684 @specialize.argtype(0)
1685 def digits_from_nonneg_long(l):
1686 digits = []
1687 while True:
1688 digits.append(_store_digit(_mask_digit(l & MASK)))
1689 l = l >> SHIFT
1690 if not l:
1691 return digits[:] # to make it non-resizable
1692
1693 @specialize.argtype(0)
1694 def digits_for_most_neg_long(l):
1695 # This helper only works if 'l' is the most negative integer of its
1696 # type, which in base 2 looks like: 1000000..0000
1697 digits = []
1698 while _mask_digit(l) == 0:
1699 digits.append(NULLDIGIT)
1700 l = l >> SHIFT
1701 # now 'l' looks like: ...111100000
1702 # turn it into: ...000100000
1703 # to drop the extra unwanted 1's introduced by the signed right shift
1704 l = -intmask(l)
1705 assert l & MASK == l
1706 digits.append(_store_digit(l))
1707 return digits[:] # to make it non-resizable
1708
1709 @specialize.argtype(0)
1710 def args_from_rarith_int1(x):
1711 if x > 0:
1712 return digits_from_nonneg_long(x), 1
1713 elif x == 0:
1714 return NULLDIGITS, 0
1715 elif x != most_neg_value_of_same_type(x):
1716 # normal case
1717 return digits_from_nonneg_long(-x), -1
1718 else:
1719 # the most negative integer! hacks needed...
1720 return digits_for_most_neg_long(x), -1
1721
1722 @specialize.argtype(0)
1723 def args_from_rarith_int(x):
1724 return args_from_rarith_int1(widen(x))
1725 # ^^^ specialized by the precise type of 'x', which is typically a r_xxx
1726 # instance from rlib.rarithmetic
1727
1728 @not_rpython
1729 def args_from_long(x):
1730 if x >= 0:
1731 if x == 0:
1732 return NULLDIGITS, 0
1733 else:
1734 return digits_from_nonneg_long(x), 1
1735 else:
1736 return digits_from_nonneg_long(-x), -1
1737
1738 def _x_add(a, b):
1739 """ Add the absolute values of two bigint integers. """
1740 size_a = a.numdigits()
1741 size_b = b.numdigits()
1742
1743 # Ensure a is the larger of the two:
1744 if size_a < size_b:
1745 a, b = b, a
1746 size_a, size_b = size_b, size_a
1747 z = rbigint([NULLDIGIT] * (size_a + 1), 1)
1748 i = UDIGIT_TYPE(0)
1749 carry = UDIGIT_TYPE(0)
1750 while i < size_b:
1751 carry += a.udigit(i) + b.udigit(i)
1752 z.setdigit(i, carry)
1753 carry >>= SHIFT
1754 i += 1
1755 while i < size_a:
1756 carry += a.udigit(i)
1757 z.setdigit(i, carry)
1758 carry >>= SHIFT
1759 i += 1
1760 z.setdigit(i, carry)
1761 z._normalize()
1762 return z
1763
1764 def _x_int_add(a, b):
1765 """ Add the absolute values of one bigint and one integer. """
1766 size_a = a.numdigits()
1767
1768 z = rbigint([NULLDIGIT] * (size_a + 1), 1)
1769 i = UDIGIT_TYPE(1)
1770 carry = a.udigit(0) + abs(b)
1771 z.setdigit(0, carry)
1772 carry >>= SHIFT
1773
1774 while i < size_a:
1775 carry += a.udigit(i)
1776 z.setdigit(i, carry)
1777 carry >>= SHIFT
1778 i += 1
1779 z.setdigit(i, carry)
1780 z._normalize()
1781 return z
1782
1783 def _x_sub(a, b):
1784 """ Subtract the absolute values of two integers. """
1785
1786 size_a = a.numdigits()
1787 size_b = b.numdigits()
1788 sign = 1
1789
1790 # Ensure a is the larger of the two:
1791 if size_a < size_b:
1792 sign = -1
1793 a, b = b, a
1794 size_a, size_b = size_b, size_a
1795 elif size_a == size_b:
1796 # Find highest digit where a and b differ:
1797 i = size_a - 1
1798 while i >= 0 and a.digit(i) == b.digit(i):
1799 i -= 1
1800 if i < 0:
1801 return NULLRBIGINT
1802 if a.digit(i) < b.digit(i):
1803 sign = -1
1804 a, b = b, a
1805 size_a = size_b = i+1
1806
1807 z = rbigint([NULLDIGIT] * size_a, sign, size_a)
1808 borrow = UDIGIT_TYPE(0)
1809 i = _load_unsigned_digit(0)
1810 while i < size_b:
1811 # The following assumes unsigned arithmetic
1812 # works modulo 2**N for some N>SHIFT.
1813 borrow = a.udigit(i) - b.udigit(i) - borrow
1814 z.setdigit(i, borrow)
1815 borrow >>= SHIFT
1816 borrow &= 1 # Keep only one sign bit
1817 i += 1
1818 while i < size_a:
1819 borrow = a.udigit(i) - borrow
1820 z.setdigit(i, borrow)
1821 borrow >>= SHIFT
1822 borrow &= 1
1823 i += 1
1824
1825 assert borrow == 0
1826 z._normalize()
1827 return z
1828
1829 def _x_int_sub(a, b):
1830 """ Subtract the absolute values of two integers. """
1831
1832 size_a = a.numdigits()
1833
1834 bdigit = abs(b)
1835
1836 if size_a == 1:
1837 # Find highest digit where a and b differ:
1838 adigit = a.digit(0)
1839
1840 if adigit == bdigit:
1841 return NULLRBIGINT
1842
1843 return rbigint.fromint(adigit - bdigit)
1844
1845 z = rbigint([NULLDIGIT] * size_a, 1, size_a)
1846 i = _load_unsigned_digit(1)
1847 # The following assumes unsigned arithmetic
1848 # works modulo 2**N for some N>SHIFT.
1849 borrow = a.udigit(0) - bdigit
1850 z.setdigit(0, borrow)
1851 borrow >>= SHIFT
1852 borrow &= 1 # Keep only one sign bit
1853
1854 while i < size_a:
1855 borrow = a.udigit(i) - borrow
1856 z.setdigit(i, borrow)
1857 borrow >>= SHIFT
1858 borrow &= 1
1859 i += 1
1860
1861 assert borrow == 0
1862 z._normalize()
1863 return z
1864
1865 # A neat little table of power of twos.
1866 ptwotable = {}
1867 for x in range(SHIFT-1):
1868 ptwotable[r_longlong(2 << x)] = x+1
1869 ptwotable[r_longlong(-2 << x)] = x+1
1870 del x
1871
1872 def _x_mul(a, b, digit=0):
1873 """
1874 Grade school multiplication, ignoring the signs.
1875 Returns the absolute value of the product, or None if error.
1876 """
1877
1878 size_a = a.numdigits()
1879 size_b = b.numdigits()
1880
1881 if a is b:
1882 # Efficient squaring per HAC, Algorithm 14.16:
1883 # http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1884 # Gives slightly less than a 2x speedup when a == b,
1885 # via exploiting that each entry in the multiplication
1886 # pyramid appears twice (except for the size_a squares).
1887 z = rbigint([NULLDIGIT] * (size_a + size_b), 1)
1888 i = UDIGIT_TYPE(0)
1889 while i < size_a:
1890 f = a.uwidedigit(i)
1891 pz = i << 1
1892 pa = i + 1
1893
1894 carry = z.uwidedigit(pz) + f * f
1895 z.setdigit(pz, carry)
1896 pz += 1
1897 carry >>= SHIFT
1898 assert carry <= MASK
1899
1900 # Now f is added in twice in each column of the
1901 # pyramid it appears. Same as adding f<<1 once.
1902 f <<= 1
1903 while pa < size_a:
1904 carry += z.uwidedigit(pz) + a.uwidedigit(pa) * f
1905 pa += 1
1906 z.setdigit(pz, carry)
1907 pz += 1
1908 carry >>= SHIFT
1909 if carry:
1910 carry += z.udigit(pz)
1911 z.setdigit(pz, carry)
1912 pz += 1
1913 carry >>= SHIFT
1914 if carry:
1915 z.setdigit(pz, z.udigit(pz) + carry)
1916 assert (carry >> SHIFT) == 0
1917 i += 1
1918 z._normalize()
1919 return z
1920
1921 elif digit:
1922 if digit & (digit - 1) == 0:
1923 return b.lqshift(ptwotable[digit])
1924
1925 # Even if it's not power of two it can still be useful.
1926 return _muladd1(b, digit)
1927
1928 # a is not b
1929 # use the following identity to reduce the number of operations
1930 # a * b = a_0*b_0 + sum_{i=1}^n(a_0*b_i + a_1*b_{i-1}) + a_1*b_n
1931 z = rbigint([NULLDIGIT] * (size_a + size_b), 1)
1932 i = UDIGIT_TYPE(0)
1933 size_a1 = UDIGIT_TYPE(size_a - 1)
1934 size_b1 = UDIGIT_TYPE(size_b - 1)
1935 while i < size_a1:
1936 f0 = a.uwidedigit(i)
1937 f1 = a.uwidedigit(i + 1)
1938 pz = i
1939 carry = z.uwidedigit(pz) + b.uwidedigit(0) * f0
1940 z.setdigit(pz, carry)
1941 pz += 1
1942 carry >>= SHIFT
1943 j = UDIGIT_TYPE(0)
1944 while j < size_b1:
1945 # this operation does not overflow using
1946 # SHIFT = (LONG_BIT // 2) - 1 = B - 1; in fact before it
1947 # carry and z.widedigit(pz) are less than 2**(B - 1);
1948 # b.widedigit(j + 1) * f0 < (2**(B-1) - 1)**2; so
1949 # carry + z.widedigit(pz) + b.widedigit(j + 1) * f0 +
1950 # b.widedigit(j) * f1 < 2**(2*B - 1) - 2**B < 2**LONG)BIT - 1
1951 carry += z.uwidedigit(pz) + b.uwidedigit(j + 1) * f0 + \
1952 b.uwidedigit(j) * f1
1953 z.setdigit(pz, carry)
1954 pz += 1
1955 carry >>= SHIFT
1956 j += 1
1957 # carry < 2**(B + 1) - 2
1958 carry += z.uwidedigit(pz) + b.uwidedigit(size_b1) * f1
1959 z.setdigit(pz, carry)
1960 pz += 1
1961 carry >>= SHIFT
1962 # carry < 4
1963 if carry:
1964 z.setdigit(pz, carry)
1965 assert (carry >> SHIFT) == 0
1966 i += 2
1967 if size_a & 1:
1968 pz = size_a1
1969 f = a.uwidedigit(pz)
1970 pb = 0
1971 carry = _unsigned_widen_digit(0)
1972 while pb < size_b:
1973 carry += z.uwidedigit(pz) + b.uwidedigit(pb) * f
1974 pb += 1
1975 z.setdigit(pz, carry)
1976 pz += 1
1977 carry >>= SHIFT
1978 if carry:
1979 z.setdigit(pz, z.udigit(pz) + carry)
1980 z._normalize()
1981 return z
1982
1983 def _kmul_split(n, size):
1984 """
1985 A helper for Karatsuba multiplication (k_mul).
1986 Takes a bigint "n" and an integer "size" representing the place to
1987 split, and sets low and high such that abs(n) == (high << size) + low,
1988 viewing the shift as being by digits. The sign bit is ignored, and
1989 the return values are >= 0.
1990 """
1991 size_n = n.numdigits()
1992 size_lo = min(size_n, size)
1993
1994 # We use "or" her to avoid having a check where list can be empty in _normalize.
1995 lo = rbigint(n._digits[:size_lo] or NULLDIGITS, 1)
1996 hi = rbigint(n._digits[size_lo:size_n] or NULLDIGITS, 1)
1997 lo._normalize()
1998 hi._normalize()
1999 return hi, lo
2000
2001 def _k_mul(a, b):
2002 """
2003 Karatsuba multiplication. Ignores the input signs, and returns the
2004 absolute value of the product (or raises if error).
2005 See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2006 """
2007 asize = a.numdigits()
2008 bsize = b.numdigits()
2009
2010 # (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2011 # Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2012 # Then the original product is
2013 # ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2014 # By picking X to be a power of 2, "*X" is just shifting, and it's
2015 # been reduced to 3 multiplies on numbers half the size.
2016
2017 # allocate result for both paths, asize + bsize is always enough
2018 ret = rbigint([NULLDIGIT] * (asize + bsize), 1)
2019
2020 # Split a & b into hi & lo pieces.
2021 shift = bsize >> 1
2022 bh, bl = _kmul_split(b, shift)
2023 if a is b:
2024 ah = bh
2025 al = bl
2026 elif asize <= shift:
2027 # a is more than 2x smaller than b. it's important that we still use
2028 # .mul to get karatsuba for sub-parts. the computation is just:
2029 # a*(bh*X+bl) = a*bh*X + a*bl
2030
2031 # multiply lower bits, copy into result
2032 t1 = a.mul(bl)
2033 for i in range(t1.numdigits()):
2034 ret._digits[i] = t1._digits[i]
2035 t2 = a.mul(bh)
2036 i = ret.numdigits() - shift # digits after shift
2037 carry = _v_iadd(ret, shift, i, t2, t2.numdigits())
2038 ret._normalize()
2039 return ret
2040 else:
2041 ah, al = _kmul_split(a, shift)
2042
2043 # The plan:
2044 # 1. Allocate result space (asize + bsize digits: that's always
2045 # enough).
2046 # 2. Compute ah*bh, and copy into result at 2*shift.
2047 # 3. Compute al*bl, and copy into result at 0. Note that this
2048 # can't overlap with #2.
2049 # 4. Subtract al*bl from the result, starting at shift. This may
2050 # underflow (borrow out of the high digit), but we don't care:
2051 # we're effectively doing unsigned arithmetic mod
2052 # BASE**(sizea + sizeb), and so long as the *final* result fits,
2053 # borrows and carries out of the high digit can be ignored.
2054 # 5. Subtract ah*bh from the result, starting at shift.
2055 # 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2056 # at shift.
2057
2058 # 1. Allocate result space. (done, see above)
2059
2060 # 2. t1 <- ah*bh, and copy into high digits of result.
2061 t1 = ah.mul(bh)
2062
2063 assert t1.get_sign() >= 0
2064 assert 2*shift + t1.numdigits() <= ret.numdigits()
2065 for i in range(t1.numdigits()):
2066 ret._digits[2*shift + i] = t1._digits[i]
2067
2068 # 3. t2 <- al*bl, and copy into the low digits.
2069 t2 = al.mul(bl)
2070 assert t2.get_sign() >= 0
2071 assert t2.numdigits() <= 2*shift # no overlap with high digits
2072 for i in range(t2.numdigits()):
2073 ret._digits[i] = t2._digits[i]
2074
2075 # 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2076 # because it's fresher in cache.
2077 i = ret.numdigits() - shift # # digits after shift
2078 _v_isub(ret, shift, i, t2, t2.numdigits())
2079 _v_isub(ret, shift, i, t1, t1.numdigits())
2080
2081 # 6. t3 <- (ah+al)(bh+bl), and add into result.
2082 t1 = _x_add(ah, al)
2083
2084 if a is b:
2085 t2 = t1
2086 else:
2087 t2 = _x_add(bh, bl)
2088
2089 t3 = t1.mul(t2)
2090 assert t3.get_sign() >= 0
2091
2092 # Add t3. It's not obvious why we can't run out of room here.
2093 # See the (*) comment after this function.
2094 _v_iadd(ret, shift, i, t3, t3.numdigits())
2095
2096 ret._normalize()
2097 return ret
2098
2099 """ (*) Why adding t3 can't "run out of room" above.
2100
2101 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2102 to start with:
2103
2104 1. For any integer i, i = c(i/2) + f(i/2). In particular,
2105 bsize = c(bsize/2) + f(bsize/2).
2106 2. shift = f(bsize/2)
2107 3. asize <= bsize
2108 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2109 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
2110
2111 We allocated asize + bsize result digits, and add t3 into them at an offset
2112 of shift. This leaves asize+bsize-shift allocated digit positions for t3
2113 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2114 asize + c(bsize/2) available digit positions.
2115
2116 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2117 at most c(bsize/2) digits + 1 bit.
2118
2119 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2120 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2121 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
2122
2123 The product (ah+al)*(bh+bl) therefore has at most
2124
2125 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
2126
2127 and we have asize + c(bsize/2) available digit positions. We need to show
2128 this is always enough. An instance of c(bsize/2) cancels out in both, so
2129 the question reduces to whether asize digits is enough to hold
2130 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2131 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2132 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2133 digit is enough to hold 2 bits. This is so since SHIFT=15 >= 2. If
2134 asize == bsize, then we're asking whether bsize digits is enough to hold
2135 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2136 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2137 bsize >= KARATSUBA_CUTOFF >= 2.
2138
2139 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2140 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2141 ah*bh and al*bl too.
2142 """
2143
2144
2145 def _inplace_divrem1(pout, pin, n):
2146 """
2147 Divide bigint pin by non-zero digit n, storing quotient
2148 in pout, and returning the remainder. It's OK for pin == pout on entry.
2149 """
2150 rem = _unsigned_widen_digit(0)
2151 assert n > 0 and n <= MASK
2152 size = pin.numdigits() - 1
2153 while size >= 0:
2154 rem = (rem << SHIFT) | pin.udigit(size)
2155 hi = rem // n
2156 pout.setdigit(size, hi)
2157 rem -= hi * n
2158 size -= 1
2159 return rffi.cast(lltype.Signed, rem)
2160
2161 @jit.elidable
2162 def _divrem1(a, n):
2163 """
2164 Divide a bigint integer by a digit, returning both the quotient
2165 and the remainder as a tuple.
2166 The sign of a is ignored; n should not be zero.
2167 """
2168 assert n > 0 and n <= MASK
2169
2170 size = a.numdigits()
2171 z = rbigint([NULLDIGIT] * size, 1, size)
2172 rem = _inplace_divrem1(z, a, n)
2173 z._normalize()
2174 return z, rem
2175
2176 def _int_rem_core(a, digit):
2177 # digit must be positive
2178 size = UDIGIT_TYPE(a.numdigits() - 1)
2179
2180 if size > 0:
2181 wrem = a.widedigit(size)
2182 while size > 0:
2183 size -= 1
2184 wrem = ((wrem << SHIFT) | a.digit(size)) % digit
2185 rem = _store_digit(wrem)
2186 else:
2187 rem = _store_digit(a.digit(0) % digit)
2188
2189 return rem
2190
2191 def _v_iadd(x, xofs, m, y, n):
2192 """
2193 x and y are rbigints, m >= n required. x.digits[0:n] is modified in place,
2194 by adding y.digits[0:m] to it. Carries are propagated as far as
2195 x[m-1], and the remaining carry (0 or 1) is returned.
2196 Python adaptation: x is addressed relative to xofs!
2197 """
2198 carry = UDIGIT_TYPE(0)
2199
2200 assert m >= n
2201 i = _load_unsigned_digit(xofs)
2202 iend = xofs + n
2203 while i < iend:
2204 carry += x.udigit(i) + y.udigit(i-xofs)
2205 x.setdigit(i, carry)
2206 carry >>= SHIFT
2207 i += 1
2208 iend = xofs + m
2209 while carry and i < iend:
2210 carry += x.udigit(i)
2211 x.setdigit(i, carry)
2212 carry >>= SHIFT
2213 i += 1
2214 return carry
2215
2216 def _v_isub(x, xofs, m, y, n):
2217 """
2218 x and y are rbigints, m >= n required. x.digits[0:n] is modified in place,
2219 by substracting y.digits[0:m] to it. Borrows are propagated as
2220 far as x[m-1], and the remaining borrow (0 or 1) is returned.
2221 Python adaptation: x is addressed relative to xofs!
2222 """
2223 borrow = UDIGIT_TYPE(0)
2224
2225 assert m >= n
2226 i = _load_unsigned_digit(xofs)
2227 iend = xofs + n
2228 while i < iend:
2229 borrow = x.udigit(i) - y.udigit(i-xofs) - borrow
2230 x.setdigit(i, borrow)
2231 borrow >>= SHIFT
2232 borrow &= 1 # keep only 1 sign bit
2233 i += 1
2234 iend = xofs + m
2235 while borrow and i < iend:
2236 borrow = x.udigit(i) - borrow
2237 x.setdigit(i, borrow)
2238 borrow >>= SHIFT
2239 borrow &= 1
2240 i += 1
2241 return borrow
2242
2243 @specialize.argtype(2)
2244 def _muladd1(a, n, extra=0):
2245 """Multiply by a single digit and add a single digit, ignoring the sign.
2246 """
2247 assert n > 0
2248
2249 size_a = a.numdigits()
2250 z = rbigint([NULLDIGIT] * (size_a+1), 1)
2251 assert extra & MASK == extra
2252 carry = _unsigned_widen_digit(extra)
2253 i = 0
2254 while i < size_a:
2255 carry += a.uwidedigit(i) * n
2256 z.setdigit(i, carry)
2257 carry >>= SHIFT
2258 i += 1
2259 z.setdigit(i, carry)
2260 z._normalize()
2261 return z
2262
2263 def _v_lshift(z, a, m, d):
2264 """ Shift digit vector a[0:m] d bits left, with 0 <= d < SHIFT. Put
2265 * result in z[0:m], and return the d bits shifted out of the top.
2266 """
2267
2268 carry = 0
2269 #assert 0 <= d and d < SHIFT
2270 i = 0
2271 while i < m:
2272 acc = a.uwidedigit(i) << d | carry
2273 z.setdigit(i, acc)
2274 carry = acc >> SHIFT
2275 i += 1
2276
2277 return carry
2278
2279 def _v_rshift(z, a, m, d):
2280 """ Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
2281 * result in z[0:m], and return the d bits shifted out of the bottom.
2282 """
2283
2284 carry = _unsigned_widen_digit(0)
2285 acc = _unsigned_widen_digit(0)
2286 mask = (1 << d) - 1
2287
2288 #assert 0 <= d and d < SHIFT
2289 i = m-1
2290 while i >= 0:
2291 acc = (carry << SHIFT) | a.udigit(i)
2292 carry = acc & mask
2293 z.setdigit(i, acc >> d)
2294 i -= 1
2295
2296 return carry
2297
2298 def _x_divrem(v1, w1):
2299 """ Unsigned bigint division with remainder -- the algorithm """
2300 size_v = v1.numdigits()
2301 size_w = w1.numdigits()
2302 assert size_v >= size_w and size_w > 1
2303
2304 v = rbigint([NULLDIGIT] * (size_v + 1), 1, size_v + 1)
2305 w = rbigint([NULLDIGIT] * size_w, 1, size_w)
2306
2307 """ normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2308 shift v1 left by the same amount. Results go into w and v. """
2309
2310 d = SHIFT - bits_in_digit(w1.digit(abs(size_w-1)))
2311 carry = _v_lshift(w, w1, size_w, d)
2312 assert carry == 0
2313 carry = _v_lshift(v, v1, size_v, d)
2314 if carry != 0 or v.digit(abs(size_v-1)) >= w.digit(abs(size_w-1)):
2315 v.setdigit(size_v, carry)
2316 size_v += 1
2317
2318 """ Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2319 at most (and usually exactly) k = size_v - size_w digits. """
2320 k = size_v - size_w
2321 if k == 0:
2322 # We can't use v1, nor NULLRBIGINT here as some function modify the result.
2323 assert _v_rshift(w, v, size_w, d) == 0
2324 w._normalize()
2325 return rbigint([NULLDIGIT]), w
2326
2327 assert k > 0
2328 a = rbigint([NULLDIGIT] * k, 1, k)
2329
2330 wm1 = w.widedigit(abs(size_w-1))
2331 wm2 = w.widedigit(abs(size_w-2))
2332
2333 j = size_v - 1
2334 k -= 1
2335 while k >= 0:
2336 assert j >= 0
2337 """ inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2338 single-digit quotient q, remainder in vk[0:size_w]. """
2339
2340 # estimate quotient digit q; may overestimate by 1 (rare)
2341 if j >= size_v:
2342 vtop = 0
2343 else:
2344 vtop = v.widedigit(j)
2345 assert vtop <= wm1
2346
2347 vv = (vtop << SHIFT) | v.widedigit(abs(j-1))
2348
2349 # Hints to make division just as fast as doing it unsigned. But avoids casting to get correct results.
2350 assert vv >= 0
2351 assert wm1 >= 1
2352
2353 q = vv / wm1
2354 r = vv % wm1 # This seems to be slightly faster on widen digits than vv - wm1 * q.
2355 vj2 = v.digit(abs(j-2))
2356 while wm2 * q > ((r << SHIFT) | vj2):
2357 q -= 1
2358 r += wm1
2359
2360 #assert q <= MASK+1, We need to compare to BASE <=, but ehm, it gives a buildin long error. So we ignore this.
2361
2362 # subtract q*w0[0:size_w] from vk[0:size_w+1]
2363 zhi = 0
2364 i = 0
2365 while i < size_w:
2366 z = v.widedigit(k+i) + zhi - q * w.widedigit(i)
2367 v.setdigit(k+i, z)
2368 zhi = z >> SHIFT
2369 i += 1
2370
2371 # add w back if q was too large (this branch taken rarely)
2372 if vtop + zhi < 0:
2373 carry = UDIGIT_TYPE(0)
2374 i = 0
2375 while i < size_w:
2376 carry += v.udigit(k+i) + w.udigit(i)
2377 v.setdigit(k+i, carry)
2378 carry >>= SHIFT
2379 i += 1
2380 q -= 1
2381
2382 # store quotient digit
2383 a.setdigit(k, q)
2384 k -= 1
2385 j -= 1
2386
2387 carry = _v_rshift(w, v, size_w, d)
2388 assert carry == 0
2389
2390 a._normalize()
2391 w._normalize()
2392
2393 return a, w
2394
2395 @jit.elidable
2396 def _divrem(a, b):
2397 """ Long division with remainder, top-level routine """
2398 size_a = a.numdigits()
2399 size_b = b.numdigits()
2400
2401 if b.get_sign() == 0:
2402 raise ZeroDivisionError("long division or modulo by zero")
2403
2404 if (size_a < size_b or
2405 (size_a == size_b and
2406 a.digit(abs(size_a-1)) < b.digit(abs(size_b-1)))):
2407 # |a| < |b|
2408 return NULLRBIGINT, a# result is 0
2409 if size_b == 1:
2410 z, urem = _divrem1(a, b.digit(0))
2411 rem = rbigint([_store_digit(urem)], int(urem != 0), 1)
2412 else:
2413 z, rem = _x_divrem(a, b)
2414 # Set the signs.
2415 # The quotient z has the sign of a*b;
2416 # the remainder r has the sign of a,
2417 # so a = b*z + r.
2418 if a.get_sign() != b.get_sign():
2419 z._set_sign(-z.get_sign())
2420 if a.get_sign() < 0 and rem.get_sign() != 0:
2421 rem._set_sign(-rem.get_sign())
2422 return z, rem
2423
2424
2425
2426 class LimitHolder:
2427 pass
2428
2429 HOLDER = LimitHolder()
2430 HOLDER.DIV_LIMIT = 21
2431 HOLDER.STR2INT_LIMIT = 2048
2432 HOLDER.MINSIZE_STR2INT = 4000
2433
2434
2435 def _extract_digits(a, startindex, numdigits):
2436 assert startindex >= 0
2437 if startindex >= a.numdigits():
2438 return NULLRBIGINT
2439 stop = min(startindex + numdigits, a.numdigits())
2440 assert stop >= 0
2441 digits = a._digits[startindex: stop]
2442 if not digits:
2443 return NULLRBIGINT
2444 r = rbigint(digits, 1)
2445 r._normalize()
2446 return r
2447
2448 def div2n1n(a_container, a_startindex, b, n_S):
2449 """Divide a 2*n_S-digit nonnegative integer a by an n_S-digit positive integer
2450 b, using a recursive divide-and-conquer algorithm.
2451
2452 Inputs:
2453 n_S is a positive integer
2454 b is a positive rbigint with exactly n_S digits
2455 a is a nonnegative integer such that a < 2**(n_S * SHIFT) * b
2456
2457 Output:
2458 (q, r) such that a = b*q+r and 0 <= r < b.
2459
2460 a is represented as a slice of a bigger number a_container, 2 * n_S digits
2461 wide, starting at a_startindex
2462 """
2463 if n_S <= HOLDER.DIV_LIMIT:
2464 a = _extract_digits(a_container, a_startindex, 2 * n_S)
2465 if a.get_sign() == 0:
2466 return NULLRBIGINT, NULLRBIGINT
2467 res = _divrem(a, b)
2468 return res
2469 assert n_S & 1 == 0
2470 half_n_S = n_S >> 1
2471 # school division: (diagram from Burnikel & Ziegler, p 3)
2472 #
2473 # size half_n_S size n_S
2474 # | |
2475 # v v
2476 # +----+----+----+----+ +----+----+ +----+----+ +---------+
2477 # | a1 | a2 | a3 | a4 | / | b1 | b2 | = | q1 | q2 | = | q |
2478 # +====+====+====+====+ +----+----+ +----+----+ +---------+
2479 # | q1 * b1 |
2480 # +----+----+----+ <
2481 # | q1 * b2 | subtracting < first call to div3n2n
2482 # +---------+----+ <
2483 # | r1 | a4 |
2484 # +---------+----+
2485 # | q2 * b1 |
2486 # +----+----+----+ <
2487 # | q2 * b2 | subtracing < second call to div3n2n
2488 # +---------+ <
2489 # | r |
2490 # +---------+
2491
2492 b1, b2 = _extract_digits(b, half_n_S, half_n_S), _extract_digits(b, 0, half_n_S)
2493 q1, r1 = div3n2n(a_container, a_startindex + n_S, a_container, a_startindex + half_n_S, b, b1, b2, half_n_S)
2494 q2, r = div3n2n(r1, 0, a_container, a_startindex, b, b1, b2, half_n_S)
2495 return _full_digits_lshift_then_or(q1, half_n_S, q2), r
2496
2497 def div3n2n(a12_container, a12_startindex, a3_container, a3_startindex, b, b1, b2, n_S):
2498 """Helper function for div2n1n; not intended to be called directly."""
2499 q, r = div2n1n(a12_container, a12_startindex, b1, n_S)
2500 # equivalent to r = _full_digits_lshift_then_or(r, n_S, _extract_digits(a_container, a3_startindex, n_S))
2501 if r.get_sign() == 0:
2502 r = _extract_digits(a3_container, a3_startindex, n_S)
2503 else:
2504 digits = [NULLDIGIT] * (n_S + r.numdigits())
2505 index = 0
2506 for i in range(a3_startindex, min(a3_startindex + n_S, a3_container.numdigits())):
2507 digits[index] = a3_container._digits[i]
2508 index += 1
2509 index = n_S
2510 for i in range(r.numdigits()):
2511 digits[index] = r._digits[i]
2512 index += 1
2513 r = rbigint(digits, 1)
2514 r._normalize()
2515 if q.get_sign() == 0:
2516 return q, r
2517 r = r.sub(q.mul(b2))
2518
2519 # loop runs at most twice
2520 while r.get_sign() < 0:
2521 q = q.int_sub(1)
2522 r = r.add(b)
2523 return q, r
2524
2525 def _full_digits_lshift_then_or(a, n, b):
2526 """ equivalent to a.lshift(n * SHIFT).or_(b)
2527 the size of b must be smaller than n
2528 """
2529 if a.get_sign() == 0:
2530 return b
2531 bdigits = b.numdigits()
2532 assert bdigits <= n
2533 # b._digits + [NULLDIGIT] * (n - bdigits) + a._digits
2534 digits = [NULLDIGIT] * (a.numdigits() + n)
2535 for i in range(b.numdigits()):
2536 digit = b._digits[i]
2537 digits[i] = digit
2538 index = n
2539 for i in range(a.numdigits()):
2540 digits[index] = a._digits[i]
2541 index += 1
2542
2543 return rbigint(digits, 1)
2544
2545 def _divmod_fast_pos(a, b):
2546 """Divide a positive integer a by a positive integer b, giving
2547 quotient and remainder."""
2548 # Use grade-school algorithm in base 2**n, n = nbits(b)
2549 n = b.bit_length()
2550 m = a.bit_length()
2551 if m < n:
2552 return NULLRBIGINT, a
2553 # make n of the form SHIFT * HOLDER.DIV_LIMIT * 2 ** x
2554 new_n = SHIFT * HOLDER.DIV_LIMIT
2555 while new_n < n:
2556 new_n <<= 1
2557 rest_shift = new_n - n
2558 if rest_shift:
2559 a = a.lshift(rest_shift)
2560 b = b.lshift(rest_shift)
2561 assert b.bit_length() == new_n
2562 n = new_n
2563
2564 n_S = n // SHIFT
2565 r = range(0, a.numdigits(), n_S)
2566 a_digits_base_two_pow_n = [None] * len(r)
2567 index = 0
2568 for i in r:
2569 assert i >= 0
2570 stop = i + n_S
2571 assert stop >= 0
2572 a_digits_base_two_pow_n[index] = rbigint(a._digits[i: stop], 1)
2573 index += 1
2574
2575 a_digits_index = len(a_digits_base_two_pow_n) - 1
2576 assert a_digits_index >= 0
2577 if a_digits_base_two_pow_n[a_digits_index].ge(b):
2578 r = NULLRBIGINT
2579 else:
2580 r = a_digits_base_two_pow_n[a_digits_index]
2581 a_digits_index -= 1
2582 q_digits = None
2583 q_index_start = a_digits_index * n_S
2584 while a_digits_index >= 0:
2585 arg1 = _full_digits_lshift_then_or(r, n_S, a_digits_base_two_pow_n[a_digits_index])
2586 q_digitbase_two_pow_n, r = div2n1n(arg1, 0, b, n_S)
2587 if q_digits is None:
2588 q_digits = [NULLDIGIT] * (a_digits_index * n_S + q_digitbase_two_pow_n.numdigits())
2589 for i in range(q_digitbase_two_pow_n.numdigits()):
2590 q_digits[q_index_start + i] = q_digitbase_two_pow_n._digits[i]
2591 q_index_start -= n_S
2592 a_digits_index -= 1
2593 if rest_shift:
2594 r = r.rshift(rest_shift)
2595 if q_digits is None:
2596 q = NULLRBIGINT
2597 else:
2598 q = rbigint(q_digits, 1)
2599 q._normalize()
2600 r._normalize()
2601 return q, r
2602
2603 def divmod_big(a, b):
2604 # code from Mark Dickinson via https://bugs.python.org/file11060/fast_div.py
2605 # follows cr.yp.to/bib/1998/burnikel.ps
2606 if b.eq(NULLRBIGINT):
2607 raise ZeroDivisionError
2608 elif b.get_sign() < 0:
2609 q, r = divmod_big(a.neg(), b.neg())
2610 return q, r.neg()
2611 elif a.get_sign() < 0:
2612 q, r = divmod_big(a.invert(), b)
2613 return q.invert(), b.add(r.invert())
2614 elif a.get_sign() == 0:
2615 return TWO_NULLRBIGINTS
2616 else:
2617 return _divmod_fast_pos(a, b)
2618
2619 def _x_int_lt(a, b, eq=False):
2620 """ Compare bigint a with int b for less than or less than or equal """
2621 osign = 1
2622 if b == 0:
2623 osign = 0
2624 elif b < 0:
2625 osign = -1
2626
2627 if a.get_sign() > osign:
2628 return False
2629 elif a.get_sign() < osign:
2630 return True
2631
2632 digits = a.numdigits()
2633
2634 if digits > 1:
2635 if osign == 1:
2636 return False
2637 else:
2638 return True
2639
2640 d1 = a.get_sign() * a.digit(0)
2641 if eq:
2642 if d1 <= b:
2643 return True
2644 else:
2645 if d1 < b:
2646 return True
2647 return False
2648
2649 # ______________ conversions to double _______________
2650
2651 def _AsScaledDouble(v):
2652 """
2653 NBITS_WANTED should be > the number of bits in a double's precision,
2654 but small enough so that 2**NBITS_WANTED is within the normal double
2655 range. nbitsneeded is set to 1 less than that because the most-significant
2656 Python digit contains at least 1 significant bit, but we don't want to
2657 bother counting them (catering to the worst case cheaply).
2658
2659 57 is one more than VAX-D double precision; I (Tim) don't know of a double
2660 format with more precision than that; it's 1 larger so that we add in at
2661 least one round bit to stand in for the ignored least-significant bits.
2662 """
2663 NBITS_WANTED = 57
2664 if v.get_sign() == 0:
2665 return 0.0, 0
2666 i = v.numdigits() - 1
2667 sign = v.get_sign()
2668 x = float(v.digit(i))
2669 nbitsneeded = NBITS_WANTED - 1
2670 # Invariant: i Python digits remain unaccounted for.
2671 while i > 0 and nbitsneeded > 0:
2672 i -= 1
2673 x = x * FLOAT_MULTIPLIER + float(v.digit(i))
2674 nbitsneeded -= SHIFT
2675 # There are i digits we didn't shift in. Pretending they're all
2676 # zeroes, the true value is x * 2**(i*SHIFT).
2677 exponent = i
2678 assert x > 0.0
2679 return x * sign, exponent
2680
2681 ##def ldexp(x, exp):
2682 ## assert type(x) is float
2683 ## lb1 = LONG_BIT - 1
2684 ## multiplier = float(1 << lb1)
2685 ## while exp >= lb1:
2686 ## x *= multiplier
2687 ## exp -= lb1
2688 ## if exp:
2689 ## x *= float(1 << exp)
2690 ## return x
2691
2692 # note that math.ldexp checks for overflows,
2693 # while the C ldexp is not guaranteed to do.
2694 # XXX make sure that we don't ignore this!
2695 # YYY no, we decided to do ignore this!
2696
2697 @jit.dont_look_inside
2698 def _AsDouble(n):
2699 """ Get a C double from a bigint object. """
2700 # This is a "correctly-rounded" version from Python 2.7.
2701 #
2702 from rpython.rlib import rfloat
2703 DBL_MANT_DIG = rfloat.DBL_MANT_DIG # 53 for IEEE 754 binary64
2704 DBL_MAX_EXP = rfloat.DBL_MAX_EXP # 1024 for IEEE 754 binary64
2705 assert DBL_MANT_DIG < r_ulonglong.BITS
2706
2707 # Reduce to case n positive.
2708 sign = n.get_sign()
2709 if sign == 0:
2710 return 0.0
2711 elif sign < 0:
2712 n = n.neg()
2713
2714 # Find exponent: 2**(exp - 1) <= n < 2**exp
2715 exp = n.bit_length()
2716
2717 # Get top DBL_MANT_DIG + 2 significant bits of n, with a 'sticky'
2718 # last bit: that is, the least significant bit of the result is 1
2719 # iff any of the shifted-out bits is set.
2720 shift = DBL_MANT_DIG + 2 - exp
2721 if shift >= 0:
2722 q = _AsULonglong_mask(n) << shift
2723 if not we_are_translated():
2724 assert q == n.tolong() << shift # no masking actually done
2725 else:
2726 shift = -shift
2727 n2 = n.rshift(shift)
2728 q = _AsULonglong_mask(n2)
2729 if not we_are_translated():
2730 assert q == n2.tolong() # no masking actually done
2731 if not n.eq(n2.lshift(shift)):
2732 q |= 1
2733
2734 # Now remove the excess 2 bits, rounding to nearest integer (with
2735 # ties rounded to even).
2736 q = (q >> 2) + r_uint((bool(q & 2) and bool(q & 5)))
2737
2738 if exp > DBL_MAX_EXP or (exp == DBL_MAX_EXP and
2739 q == r_ulonglong(1) << DBL_MANT_DIG):
2740 raise OverflowError("integer too large to convert to float")
2741
2742 ad = math.ldexp(float(q), exp - DBL_MANT_DIG)
2743 if sign < 0:
2744 ad = -ad
2745 return ad
2746
2747 @specialize.arg(0)
2748 def _loghelper(func, arg):
2749 """
2750 A decent logarithm is easy to compute even for huge bigints, but libm can't
2751 do that by itself -- loghelper can. func is log or log10.
2752 Note that overflow isn't possible: a bigint can contain
2753 no more than INT_MAX * SHIFT bits, so has value certainly less than
2754 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
2755 small enough to fit in an IEEE single. log and log10 are even smaller.
2756 """
2757 x, e = _AsScaledDouble(arg)
2758 if x <= 0.0:
2759 raise ValueError
2760 # Value is ~= x * 2**(e*SHIFT), so the log ~=
2761 # log(x) + log(2) * e * SHIFT.
2762 # CAUTION: e*SHIFT may overflow using int arithmetic,
2763 # so force use of double. */
2764 return func(x) + (e * float(SHIFT) * func(2.0))
2765
2766 # ____________________________________________________________
2767
2768 BASE_AS_FLOAT = float(1 << SHIFT) # note that it may not fit an int
2769
2770 bit_length_table = [0] * 2**8
2771 for i in range(1, len(bit_length_table)):
2772 bit_length_table[i] = 1 + bit_length_table[i//2]
2773 bit_length_table = "".join(chr(c) for c in bit_length_table)
2774 del i
2775
2776
2777 def bits_in_digit(d):
2778 # returns the unique integer k such that 2**(k-1) <= d <
2779 # 2**k if d is nonzero, else 0.
2780 assert d >= 0
2781 d_bits = 0
2782 while d >= 2 ** 8:
2783 d_bits += 8
2784 d >>= 8
2785 d_bits += ord(bit_length_table[d])
2786 return d_bits
2787
2788
2789 @jit.elidable
2790 def bit_length_int(val):
2791 if val < 0:
2792 # warning, "-val" can overflow here
2793 val = -((val + 1) >> 1)
2794 count = 1
2795 else:
2796 count = 0
2797 if LONG_BIT > 32 and val >= 2**32:
2798 val >>= 32
2799 count += 32
2800 if val >= 2**16:
2801 val >>= 16
2802 count += 16
2803 if val >= 2**8:
2804 val >>= 8
2805 count += 8
2806 return count + ord(bit_length_table[val])
2807
2808
2809 def bit_count_digit(val):
2810 if SHIFT == 63:
2811 return _bitcount64(r_ulonglong(val))
2812 count = 0
2813 while val:
2814 count += val & 1
2815 val >>= 1
2816 return count
2817
2818 BITCOUNT_K1 = r_ulonglong(0x5555555555555555) # Repeating 01
2819 BITCOUNT_K2 = r_ulonglong(0x3333333333333333) # Repeating 0011
2820 BITCOUNT_K4 = r_ulonglong(0x0f0f0f0f0f0f0f0f) # Repeating 00001111
2821 BITCOUNT_KF = r_ulonglong(0x0101010101010101) # Repeating 00000001
2822
2823 @jit.elidable
2824 def _bitcount64(x):
2825 # takes an r_ulonglong
2826 return intmask(_bitcount64_ops(x))
2827
2828 @always_inline
2829 def _bitcount64_ops(x, K1=BITCOUNT_K1, K2=BITCOUNT_K2, K4=BITCOUNT_K4, KF=BITCOUNT_KF):
2830 # this is a separate function for Z3 testing
2831 x -= (x >> 1) & K1
2832 x = (x & K2) + ((x >> 2) & K2)
2833 x = (x + (x >> 4)) & K4
2834 return (x * KF) >> 56
2835
2836 def _truediv_result(result, negate):
2837 if negate:
2838 result = -result
2839 return result
2840
2841 def _truediv_overflow():
2842 raise OverflowError("integer division result too large for a float")
2843
2844 def _bigint_true_divide(a, b):
2845 # A longish method to obtain the floating-point result with as much
2846 # precision as theoretically possible. The code is almost directly
2847 # copied from CPython. See there (Objects/longobject.c,
2848 # long_true_divide) for detailled comments. Method in a nutshell:
2849 #
2850 # 0. reduce to case a, b > 0; filter out obvious underflow/overflow
2851 # 1. choose a suitable integer 'shift'
2852 # 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
2853 # 3. adjust x for correct rounding
2854 # 4. convert x to a double dx with the same value
2855 # 5. return ldexp(dx, shift).
2856
2857 from rpython.rlib import rfloat
2858 DBL_MANT_DIG = rfloat.DBL_MANT_DIG # 53 for IEEE 754 binary64
2859 DBL_MAX_EXP = rfloat.DBL_MAX_EXP # 1024 for IEEE 754 binary64
2860 DBL_MIN_EXP = rfloat.DBL_MIN_EXP
2861 MANT_DIG_DIGITS = DBL_MANT_DIG // SHIFT
2862 MANT_DIG_BITS = DBL_MANT_DIG % SHIFT
2863
2864 # Reduce to case where a and b are both positive.
2865 negate = (a.get_sign() < 0) ^ (b.get_sign() < 0)
2866 if not b.tobool():
2867 raise ZeroDivisionError("long division or modulo by zero")
2868 if not a.tobool():
2869 return _truediv_result(0.0, negate)
2870
2871 a_size = a.numdigits()
2872 b_size = b.numdigits()
2873
2874 # Fast path for a and b small (exactly representable in a double).
2875 # Relies on floating-point division being correctly rounded; results
2876 # may be subject to double rounding on x86 machines that operate with
2877 # the x87 FPU set to 64-bit precision.
2878 a_is_small = (a_size <= MANT_DIG_DIGITS or
2879 (a_size == MANT_DIG_DIGITS+1 and
2880 a.digit(MANT_DIG_DIGITS) >> MANT_DIG_BITS == 0))
2881 b_is_small = (b_size <= MANT_DIG_DIGITS or
2882 (b_size == MANT_DIG_DIGITS+1 and
2883 b.digit(MANT_DIG_DIGITS) >> MANT_DIG_BITS == 0))
2884 if a_is_small and b_is_small:
2885 a_size -= 1
2886 da = float(a.digit(a_size))
2887 while True:
2888 a_size -= 1
2889 if a_size < 0:
2890 break
2891 da = da * BASE_AS_FLOAT + a.digit(a_size)
2892
2893 b_size -= 1
2894 db = float(b.digit(b_size))
2895 while True:
2896 b_size -= 1
2897 if b_size < 0:
2898 break
2899 db = db * BASE_AS_FLOAT + b.digit(b_size)
2900
2901 return _truediv_result(da / db, negate)
2902
2903 # Catch obvious cases of underflow and overflow
2904 diff = a_size - b_size
2905 if diff > sys.maxint/SHIFT - 1:
2906 return _truediv_overflow() # Extreme overflow
2907 elif diff < 1 - sys.maxint/SHIFT:
2908 return _truediv_result(0.0, negate) # Extreme underflow
2909 # Next line is now safe from overflowing integers
2910 diff = (diff * SHIFT + bits_in_digit(a.digit(a_size - 1)) -
2911 bits_in_digit(b.digit(b_size - 1)))
2912 # Now diff = a_bits - b_bits.
2913 if diff > DBL_MAX_EXP:
2914 return _truediv_overflow()
2915 elif diff < DBL_MIN_EXP - DBL_MANT_DIG - 1:
2916 return _truediv_result(0.0, negate)
2917
2918 # Choose value for shift; see comments for step 1 in CPython.
2919 shift = max(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2
2920
2921 inexact = False
2922
2923 # x = abs(a * 2**-shift)
2924 if shift <= 0:
2925 x = a.lshift(-shift)
2926 else:
2927 x = a.rshift(shift, dont_invert=True)
2928 # set inexact if any of the bits shifted out is nonzero
2929 if not a.eq(x.lshift(shift)):
2930 inexact = True
2931
2932 # x //= b. If the remainder is nonzero, set inexact.
2933 x, rem = _divrem(x, b)
2934 if rem.tobool():
2935 inexact = True
2936
2937 assert x.tobool() # result of division is never zero
2938 x_size = x.numdigits()
2939 x_bits = (x_size-1)*SHIFT + bits_in_digit(x.digit(x_size-1))
2940
2941 # The number of extra bits that have to be rounded away.
2942 extra_bits = max(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
2943 assert extra_bits == 2 or extra_bits == 3
2944
2945 # Round by remembering a modified copy of the low digit of x
2946 mask = r_uint(1 << (extra_bits - 1))
2947 low = x.udigit(0) | r_uint(inexact)
2948 if (low & mask) != 0 and (low & (3*mask-1)) != 0:
2949 low += mask
2950 x_digit_0 = low & ~(mask-1)
2951
2952 # Convert x to a double dx; the conversion is exact.
2953 x_size -= 1
2954 dx = 0.0
2955 while x_size > 0:
2956 dx += x.digit(x_size)
2957 dx *= BASE_AS_FLOAT
2958 x_size -= 1
2959 dx += x_digit_0
2960
2961 # Check whether ldexp result will overflow a double.
2962 if (shift + x_bits >= DBL_MAX_EXP and
2963 (shift + x_bits > DBL_MAX_EXP or dx == math.ldexp(1.0, x_bits))):
2964 return _truediv_overflow()
2965
2966 return _truediv_result(math.ldexp(dx, shift), negate)
2967
2968 # ____________________________________________________________
2969
2970 BASE8 = '01234567'
2971 BASE10 = '0123456789'
2972 BASE16 = '0123456789abcdef'
2973
2974 def _format_base2_notzero(a, digits, prefix='', suffix='', max_str_digits=0):
2975 base = len(digits)
2976 # JRH: special case for power-of-2 bases
2977 accum = 0
2978 accumbits = 0 # # of bits in accum
2979 basebits = 0
2980 i = base
2981 while i > 1:
2982 basebits += 1
2983 i >>= 1
2984
2985 # Compute a rough upper bound for the length of the string
2986 size_a = a.numdigits()
2987 i = 5 + len(prefix) + len(suffix) + (size_a*SHIFT + basebits-1) // basebits
2988 result = [chr(0)] * i
2989 next_char_index = i
2990 j = len(suffix)
2991 while j > 0:
2992 next_char_index -= 1
2993 j -= 1
2994 result[next_char_index] = suffix[j]
2995
2996 i = 0
2997 while i < size_a:
2998 accum |= a.widedigit(i) << accumbits
2999 accumbits += SHIFT
3000 assert accumbits >= basebits
3001 while 1:
3002 cdigit = intmask(accum & (base - 1))
3003 next_char_index -= 1
3004 assert next_char_index >= 0
3005 result[next_char_index] = digits[cdigit]
3006 accumbits -= basebits
3007 accum >>= basebits
3008 if i < size_a - 1:
3009 if accumbits < basebits:
3010 break
3011 else:
3012 if accum <= 0:
3013 break
3014 i += 1
3015 j = len(prefix)
3016 while j > 0:
3017 next_char_index -= 1
3018 j -= 1
3019 result[next_char_index] = prefix[j]
3020
3021 if a.get_sign() < 0:
3022 next_char_index -= 1
3023 result[next_char_index] = '-'
3024
3025 assert next_char_index >= 0 # otherwise, buffer overflow (this is also a
3026 # hint for the annotator for the slice below)
3027 return ''.join(result[next_char_index:])
3028
3029
3030 class PartsCacheBase(object):
3031 def __init__(self, base):
3032 mindigits = 1
3033 curr = base
3034 while 1:
3035 try:
3036 next = ovfcheck(curr * base)
3037 except OverflowError:
3038 break
3039 if next >= MASK:
3040 break
3041 curr = next
3042 mindigits += 1
3043 self.mindigits = mindigits
3044 part = rbigint.fromint(curr)
3045 self.lowest_part = curr
3046 self.parts_cache = [part]
3047
3048 class _PartsCache(object):
3049 def __init__(self):
3050 # 36 - 3, because bases 0, 1 make no sense
3051 # and 2 is handled differently
3052 self.parts_cache = [None] * 34
3053
3054 def get_cached_parts(self, base):
3055 index = base - 3
3056 res = self.parts_cache[index]
3057 if res is None:
3058 res = PartsCacheBase(base)
3059 self.parts_cache[index] = res
3060 return res
3061
3062
3063 _parts_cache = _PartsCache()
3064 _parts_cache_10 = _parts_cache.get_cached_parts(10)
3065
3066
3067 def _format_int_general(val, digits):
3068 base = len(digits)
3069 out = []
3070 while val:
3071 out.append(digits[val % base])
3072 val //= base
3073 out.reverse()
3074 return "".join(out)
3075
3076 def _format_int10(val, digits):
3077 return str(val)
3078
3079 _format10_table2 = "".join(str(i // 10) + str(i % 10) for i in range(100))
3080
3081 def _format_int10_18digits(val, builder):
3082 assert 0 <= val < 10**18
3083 top2 = val // 10**16
3084 assert top2 < 100
3085 val = val % 10**16
3086 a = val // 10**8
3087 b = val % 10**8
3088
3089 aa = a // 10**4
3090 ab = a % 10**4
3091 ba = b // 10**4
3092 bb = b % 10**4
3093
3094 aaa = aa // 10**2
3095 aab = aa % 10**2
3096 aba = ab // 10**2
3097 abb = ab % 10**2
3098 baa = ba // 10**2
3099 bab = ba % 10**2
3100 bba = bb // 10**2
3101 bbb = bb % 10**2
3102 builder.append_slice(_format10_table2, 2*top2, 2*top2 + 2)
3103 builder.append_slice(_format10_table2, 2*aaa, 2*aaa + 2)
3104 builder.append_slice(_format10_table2, 2*aab, 2*aab + 2)
3105 builder.append_slice(_format10_table2, 2*aba, 2*aba + 2)
3106 builder.append_slice(_format10_table2, 2*abb, 2*abb + 2)
3107 builder.append_slice(_format10_table2, 2*baa, 2*baa + 2)
3108 builder.append_slice(_format10_table2, 2*bab, 2*bab + 2)
3109 builder.append_slice(_format10_table2, 2*bba, 2*bba + 2)
3110 builder.append_slice(_format10_table2, 2*bbb, 2*bbb + 2)
3111
3112 @specialize.arg(6)
3113 def _format_recursive(x, i, output, pcb, digits, size_prefix, _format_int, max_str_digits):
3114 while i > 0:
3115 top, x = x.divmod(pcb.parts_cache[i]) # split the number
3116 if not top.tobool() and output.getlength() == size_prefix:
3117 # the top half can often be 0, because the number isn't perfectly a
3118 # power of the base
3119 pass
3120 else:
3121 _format_recursive(top, i-1, output, pcb, digits, size_prefix, _format_int, max_str_digits)
3122 # do the second recursive call by means of manual tail calling
3123 i -= 1
3124 # bottomed out with mindigits sized pieces
3125 # use str of ints
3126 mindigits = pcb.mindigits
3127 curlen = output.getlength()
3128 # the last divmod is guaranteed to return two ints
3129 high, low = _format_lowest_level_divmod_int_results(x, pcb.lowest_part)
3130 # this checks whether any digit has been appended yet
3131 lowdone = False
3132 if curlen == size_prefix:
3133 if high:
3134 s = _format_int(high, digits)
3135 output.append(s)
3136 curlen += len(s)
3137 else:
3138 if low:
3139 s = _format_int(low, digits)
3140 output.append(s)
3141 curlen += len(s)
3142 lowdone = True
3143 else:
3144 if SHIFT == 63 and _format_int is _format_int10 and mindigits == 18:
3145 _format_int10_18digits(high, output)
3146 else:
3147 s = _format_int(high, digits)
3148 output.append_multiple_char(digits[0], mindigits - len(s))
3149 output.append(s)
3150 curlen += mindigits
3151 if not lowdone:
3152 if SHIFT == 63 and _format_int is _format_int10 and mindigits == 18:
3153 _format_int10_18digits(low, output)
3154 else:
3155 s = _format_int(low, digits)
3156 output.append_multiple_char(digits[0], mindigits - len(s))
3157 output.append(s)
3158 curlen += mindigits
3159 if max_str_digits > 0 and curlen - size_prefix > max_str_digits:
3160 raise MaxIntError("requested output too large")
3161
3162 @always_inline
3163 def _format_lowest_level_divmod_int_results(x, iother):
3164 # this is only useful in the context of _format_recursive, where we know
3165 # that at the lowest levels the division leaves a result that fits into an
3166 # int (and the mod does anyway fit into an int)
3167 # x must be smaller than iother**2
3168 # iother must be positive
3169 if not x.tobool():
3170 return 0, 0
3171 assert iother > 0 and iother <= MASK
3172 size = x.numdigits() - 1
3173 if size == 1:
3174 rem = x.uwidedigit(1)
3175 assert rem < iother # otherwise iother ** 2 >= x
3176 else:
3177 rem = _unsigned_widen_digit(0)
3178 rem = (rem << SHIFT) | x.uwidedigit(0)
3179 div = rem // iother
3180 rem -= div * iother
3181 return rffi.cast(lltype.Signed, div), rffi.cast(lltype.Signed, rem)
3182
3183 def _format(x, digits, prefix='', suffix='', max_str_digits=0):
3184 if x.get_sign() == 0:
3185 return prefix + "0" + suffix
3186 base = len(digits)
3187 assert base >= 2 and base <= 36
3188 if (base & (base - 1)) == 0:
3189 # base is 2, 4, 8, 16, ...
3190 return _format_base2_notzero(x, digits, prefix, suffix, max_str_digits)
3191 negative = x.get_sign() < 0
3192 if negative:
3193 x = x.neg()
3194
3195 pcb = _parts_cache.get_cached_parts(base)
3196 mindigits = pcb.mindigits
3197 stringsize = mindigits
3198 startindex = 0
3199 pts = pcb.parts_cache
3200 for startindex, part in enumerate(pts):
3201 if not part.lt(x):
3202 break
3203 stringsize *= 2 # XXX can this overflow on 32 bit?
3204 else:
3205 # not enough parts computed yet
3206 while pts[-1].lt(x):
3207 pts.append(pts[-1].int_pow(2))
3208 stringsize *= 2
3209
3210 startindex = len(pts) - 1
3211
3212 # remove first base**2**i greater than x
3213 startindex -= 1
3214
3215 stringsize += len(prefix) + len(suffix) + negative
3216 output = StringBuilder(stringsize)
3217 if negative:
3218 output.append('-')
3219 output.append(prefix)
3220 if startindex < 0:
3221 if digits == BASE10:
3222 s = _format_int10(x.toint(), digits)
3223 else:
3224 s = _format_int_general(x.toint(), digits)
3225 output.append(s)
3226 else:
3227 if digits == BASE10:
3228 _format_recursive(
3229 x, startindex, output, pcb, digits, output.getlength(),
3230 _format_int10, max_str_digits)
3231 else:
3232 _format_recursive(
3233 x, startindex, output, pcb, digits, output.getlength(),
3234 _format_int_general, max_str_digits)
3235
3236 output.append(suffix)
3237 return output.build()
3238
3239
3240 @specialize.arg(1)
3241 def _bitwise(a, op, b): # '&', '|', '^'
3242 """ Bitwise and/or/xor operations """
3243
3244 if a.get_sign() < 0:
3245 a = a.invert()
3246 maska = MASK
3247 else:
3248 maska = 0
3249 if b.get_sign() < 0:
3250 b = b.invert()
3251 maskb = MASK
3252 else:
3253 maskb = 0
3254
3255 negz = 0
3256 if op == '^':
3257 if maska != maskb:
3258 maska ^= MASK
3259 negz = -1
3260 elif op == '&':
3261 if maska and maskb:
3262 op = '|'
3263 maska ^= MASK
3264 maskb ^= MASK
3265 negz = -1
3266 elif op == '|':
3267 if maska or maskb:
3268 op = '&'
3269 maska ^= MASK
3270 maskb ^= MASK
3271 negz = -1
3272 else:
3273 assert 0, "unreachable"
3274
3275 # JRH: The original logic here was to allocate the result value (z)
3276 # as the longer of the two operands. However, there are some cases
3277 # where the result is guaranteed to be shorter than that: AND of two
3278 # positives, OR of two negatives: use the shorter number. AND with
3279 # mixed signs: use the positive number. OR with mixed signs: use the
3280 # negative number. After the transformations above, op will be '&'
3281 # iff one of these cases applies, and mask will be non-0 for operands
3282 # whose length should be ignored.
3283
3284 size_a = a.numdigits()
3285 size_b = b.numdigits()
3286 if op == '&':
3287 if maska:
3288 size_z = size_b
3289 else:
3290 if maskb:
3291 size_z = size_a
3292 else:
3293 size_z = min(size_a, size_b)
3294 else:
3295 size_z = max(size_a, size_b)
3296
3297 z = rbigint([NULLDIGIT] * size_z, 1, size_z)
3298 i = 0
3299 while i < size_z:
3300 if i < size_a:
3301 diga = a.digit(i) ^ maska
3302 else:
3303 diga = maska
3304 if i < size_b:
3305 digb = b.digit(i) ^ maskb
3306 else:
3307 digb = maskb
3308
3309 if op == '&':
3310 z.setdigit(i, diga & digb)
3311 elif op == '|':
3312 z.setdigit(i, diga | digb)
3313 elif op == '^':
3314 z.setdigit(i, diga ^ digb)
3315 i += 1
3316
3317 z._normalize()
3318 if negz == 0:
3319 return z
3320
3321 return z.invert()
3322
3323 @specialize.arg(1)
3324 def _int_bitwise(a, op, b): # '&', '|', '^'
3325 """ Bitwise and/or/xor operations """
3326
3327 if not int_in_valid_range(b):
3328 # Fallback to long.
3329 return _bitwise(a, op, rbigint.fromint(b))
3330
3331 if a.get_sign() < 0:
3332 a = a.invert()
3333 maska = MASK
3334 else:
3335 maska = 0
3336 if b < 0:
3337 b = ~b
3338 maskb = MASK
3339 else:
3340 maskb = 0
3341
3342 negz = 0
3343 if op == '^':
3344 if maska != maskb:
3345 maska ^= MASK
3346 negz = -1
3347 elif op == '&':
3348 if maska and maskb:
3349 op = '|'
3350 maska ^= MASK
3351 maskb ^= MASK
3352 negz = -1
3353 elif op == '|':
3354 if maska or maskb:
3355 op = '&'
3356 maska ^= MASK
3357 maskb ^= MASK
3358 negz = -1
3359
3360 # JRH: The original logic here was to allocate the result value (z)
3361 # as the longer of the two operands. However, there are some cases
3362 # where the result is guaranteed to be shorter than that: AND of two
3363 # positives, OR of two negatives: use the shorter number. AND with
3364 # mixed signs: use the positive number. OR with mixed signs: use the
3365 # negative number. After the transformations above, op will be '&'
3366 # iff one of these cases applies, and mask will be non-0 for operands
3367 # whose length should be ignored.
3368
3369 size_a = a.numdigits()
3370 if op == '&':
3371 if maska:
3372 size_z = 1
3373 else:
3374 if maskb:
3375 size_z = size_a
3376 else:
3377 size_z = 1
3378 else:
3379 size_z = size_a
3380
3381 z = rbigint([NULLDIGIT] * size_z, 1, size_z)
3382 i = 0
3383 while i < size_z:
3384 if i < size_a:
3385 diga = a.digit(i) ^ maska
3386 else:
3387 diga = maska
3388 if i == 0:
3389 digb = b ^ maskb
3390 else:
3391 digb = maskb
3392
3393 if op == '&':
3394 z.setdigit(i, diga & digb)
3395 elif op == '|':
3396 z.setdigit(i, diga | digb)
3397 elif op == '^':
3398 z.setdigit(i, diga ^ digb)
3399 i += 1
3400
3401 z._normalize()
3402 if negz == 0:
3403 return z
3404
3405 return z.invert()
3406
3407 ULONGLONG_BOUND = r_ulonglong(1L << (r_longlong.BITS-1))
3408 LONGLONG_MIN = r_longlong(-(1L << (r_longlong.BITS-1)))
3409
3410 def _AsLongLong(v):
3411 """
3412 Get a r_longlong integer from a bigint object.
3413 Raises OverflowError if overflow occurs.
3414 """
3415 x = _AsULonglong_ignore_sign(v)
3416 # grr grr grr
3417 if x >= ULONGLONG_BOUND:
3418 if x == ULONGLONG_BOUND and v.get_sign() < 0:
3419 x = LONGLONG_MIN
3420 else:
3421 raise OverflowError
3422 else:
3423 x = r_longlong(x)
3424 if v.get_sign() < 0:
3425 x = -x
3426 return x
3427
3428 def _AsULonglong_ignore_sign(v):
3429 x = r_ulonglong(0)
3430 i = v.numdigits() - 1
3431 while i >= 0:
3432 prev = x
3433 x = (x << SHIFT) + r_ulonglong(v.widedigit(i))
3434 if (x >> SHIFT) != prev:
3435 raise OverflowError(
3436 "long int too large to convert to unsigned long long int")
3437 i -= 1
3438 return x
3439
3440 def make_unsigned_mask_conversion(T):
3441 def _As_unsigned_mask(v):
3442 x = T(0)
3443 i = v.numdigits() - 1
3444 while i >= 0:
3445 x = (x << SHIFT) + T(v.digit(i))
3446 i -= 1
3447 if v.get_sign() < 0:
3448 x = -x
3449 return x
3450 return _As_unsigned_mask
3451
3452 _AsULonglong_mask = make_unsigned_mask_conversion(r_ulonglong)
3453 _AsUInt_mask = make_unsigned_mask_conversion(r_uint)
3454
3455 def _hash(v):
3456 # This is designed so that Python ints and longs with the
3457 # same value hash to the same value, otherwise comparisons
3458 # of mapping keys will turn out weird. Moreover, purely
3459 # to please decimal.py, we return a hash that satisfies
3460 # hash(x) == hash(x % ULONG_MAX). In particular, this
3461 # implies that hash(x) == hash(x % (2**64-1)).
3462 i = v.numdigits() - 1
3463 sign = v.get_sign()
3464 x = r_uint(0)
3465 LONG_BIT_SHIFT = LONG_BIT - SHIFT
3466 while i >= 0:
3467 # Force a native long #-bits (32 or 64) circular shift
3468 x = (x << SHIFT) | (x >> LONG_BIT_SHIFT)
3469 x += v.udigit(i)
3470 # If the addition above overflowed we compensate by
3471 # incrementing. This preserves the value modulo
3472 # ULONG_MAX.
3473 if x < v.udigit(i):
3474 x += 1
3475 i -= 1
3476 res = intmask(intmask(x) * sign)
3477 return res
3478
3479 #_________________________________________________________________
3480
3481 # a few internal helpers
3482
3483 def digits_max_for_base(base):
3484 dec_per_digit = 1
3485 while base ** dec_per_digit < MASK:
3486 dec_per_digit += 1
3487 dec_per_digit -= 1
3488 return base ** dec_per_digit
3489
3490 BASE_MAX = [0, 1] + [digits_max_for_base(_base) for _base in range(2, 37)]
3491 DEC_MAX = digits_max_for_base(10)
3492 assert DEC_MAX == BASE_MAX[10]
3493
3494 def _decimalstr_to_bigint(s, start=0, lim=-1):
3495 # a string that has been already parsed to be decimal and valid,
3496 # is turned into a bigint
3497 p = start
3498 if lim < 0:
3499 lim = len(s)
3500 sign = False
3501 if s[p] == '-':
3502 sign = True
3503 p += 1
3504 elif s[p] == '+':
3505 p += 1
3506
3507 a = NULLRBIGINT
3508 tens = 1
3509 dig = 0
3510 ord0 = ord('0')
3511 while p < lim:
3512 dig = dig * 10 + ord(s[p]) - ord0
3513 p += 1
3514 tens *= 10
3515 if tens == DEC_MAX or p == lim:
3516 if a is not None:
3517 a = _muladd1(a, tens, dig)
3518 else:
3519 assert dig & MASK == dig
3520 a = rbigint([_store_digit(dig)], int(dig != 0))
3521 tens = 1
3522 dig = 0
3523 if sign and a.get_sign() == 1:
3524 a._set_sign(-1)
3525 return a
3526
3527 def parse_digit_string(parser):
3528 # helper for fromstr
3529 base = parser.base
3530 if (base & (base - 1)) == 0 and base >= 2:
3531 return parse_string_from_binary_base(parser)
3532 if base == 10 and (parser.end - parser.start) > HOLDER.MINSIZE_STR2INT:
3533 # check for errors and potentially remove underscores
3534 s, start, end = parser._all_digits10()
3535 a = _str_to_int_big_base10(s, start, end, HOLDER.STR2INT_LIMIT)
3536 a._set_sign(a.get_sign() * parser.sign)
3537 return a
3538 a = NULLRBIGINT
3539 digitmax = BASE_MAX[base]
3540 baseexp, dig = 1, 0
3541 while True:
3542 digit = parser.next_digit()
3543 if baseexp == digitmax or digit < 0:
3544 if a is not None:
3545 a = _muladd1(a, baseexp, dig)
3546 else:
3547 assert dig & MASK == dig
3548 a = rbigint([_store_digit(dig)], int(dig != 0))
3549 if digit < 0:
3550 break
3551 dig = digit
3552 baseexp = base
3553 else:
3554 dig = dig * base + digit
3555 baseexp *= base
3556 a._set_sign(a.get_sign() * parser.sign)
3557 return a
3558
3559
3560 FIVERBIGINT = rbigint.fromint(5)
3561
3562 def _str_to_int_big_w5pow(w, mem, limit):
3563 """Return 5**w and store the result.
3564 Also possibly save some intermediate results. In context, these
3565 are likely to be reused across various levels of the conversion
3566 to 'int'.
3567 """
3568 result = mem.get(w, None)
3569 if result is None:
3570 if w <= limit:
3571 result = FIVERBIGINT.int_pow(w)
3572 elif w - 1 in mem:
3573 result = mem[w - 1].int_mul(5)
3574 else:
3575 w2 = w >> 1
3576 # If w happens to be odd, w-w2 is one larger then w2
3577 # now. Recurse on the smaller first (w2), so that it's
3578 # in the cache and the larger (w-w2) can be handled by
3579 # the cheaper `w-1 in mem` branch instead.
3580 result = _str_to_int_big_w5pow(w2, mem, limit).mul(
3581 _str_to_int_big_w5pow(w - w2, mem, limit))
3582 mem[w] = result
3583 return result
3584
3585 def _str_to_int_big_inner10(s, a, b, mem, limit):
3586 diff = b - a
3587 if diff <= limit:
3588 return _decimalstr_to_bigint(s, a, b)
3589 # choose the midpoint rounding up, as that yields slightly fewer entries in
3590 # mem, see comment in _str_to_int_big_w5pow too
3591 mid = a + (diff + 1) // 2
3592 right = _str_to_int_big_inner10(s, mid, b, mem, limit)
3593 left = _str_to_int_big_inner10(s, a, mid, mem, limit)
3594 left = left.mul(_str_to_int_big_w5pow(b - mid, mem, limit)).lshift(b - mid)
3595 return right.add(left)
3596
3597 def _str_to_int_big_base10(s, start, end, limit=20):
3598 """Asymptotically fast conversion of a 'str' to an 'int'."""
3599
3600 # Function due to Bjorn Martinsson. See GH issue #90716 for details.
3601 # https://github.com/python/cpython/issues/90716
3602 #
3603 # The implementation in longobject.c of base conversion algorithms
3604 # between power-of-2 and non-power-of-2 bases are quadratic time.
3605 # This function implements a divide-and-conquer algorithm making use
3606 # of Python's built in big int multiplication. Since Python uses the
3607 # Karatsuba algorithm for multiplication, the time complexity
3608 # of this function is O(len(s)**1.58).
3609
3610 mem = {}
3611 result = _str_to_int_big_inner10(s, start, end, mem, limit)
3612 return result
3613
3614 def parse_string_from_binary_base(parser):
3615 # The point to this routine is that it takes time linear in the number of
3616 # string characters.
3617 from rpython.rlib.rstring import ParseStringError
3618
3619 base = parser.base
3620 if base == 2: bits_per_char = 1
3621 elif base == 4: bits_per_char = 2
3622 elif base == 8: bits_per_char = 3
3623 elif base == 16: bits_per_char = 4
3624 elif base == 32: bits_per_char = 5
3625 else:
3626 raise AssertionError
3627
3628 # n <- total number of bits needed, while moving 'parser' to the end
3629 n = 0
3630 while parser.next_digit() >= 0:
3631 n += 1
3632
3633 # b <- number of Python digits needed, = ceiling(n/SHIFT). */
3634 try:
3635 b = ovfcheck(n * bits_per_char)
3636 b = ovfcheck(b + (SHIFT - 1))
3637 except OverflowError:
3638 raise ParseStringError("long string too large to convert")
3639 b = (b // SHIFT) or 1
3640 z = rbigint([NULLDIGIT] * b, sign=parser.sign)
3641
3642 # Read string from right, and fill in long from left; i.e.,
3643 # from least to most significant in both.
3644 accum = _widen_digit(0)
3645 bits_in_accum = 0
3646 pdigit = 0
3647 for _ in range(n):
3648 k = parser.prev_digit()
3649 accum |= _widen_digit(k) << bits_in_accum
3650 bits_in_accum += bits_per_char
3651 if bits_in_accum >= SHIFT:
3652 z.setdigit(pdigit, accum)
3653 pdigit += 1
3654 assert pdigit <= b
3655 accum >>= SHIFT
3656 bits_in_accum -= SHIFT
3657
3658 if bits_in_accum:
3659 z.setdigit(pdigit, accum)
3660 z._normalize()
3661 return z
3662
3663 @jit.elidable
3664 def gcd_binary(a, b):
3665 """ Compute the greatest common divisor of non-negative integers a and b
3666 using the binary GCD algorithm. Raises ValueError on negative input. """
3667 if a < 0 or b < 0:
3668 raise ValueError
3669
3670 if a == 0:
3671 return b
3672
3673 if b == 0:
3674 return a
3675
3676 shift = 0
3677 while (a | b) & 1 == 0:
3678 a >>= 1
3679 b >>= 1
3680 shift += 1
3681
3682 while a & 1 == 0:
3683 a >>= 1
3684
3685 while b & 1 == 0:
3686 b >>= 1
3687
3688 while a != b:
3689 a, b = abs(a - b), min(a, b)
3690 while a & 1 == 0:
3691 a >>= 1
3692
3693 return a << shift
3694
3695 def lehmer_xgcd(a, b):
3696 s_old, s_new = 1, 0
3697 t_old, t_new = 0, 1
3698 while b >> (SHIFT >> 1):
3699 q, r = a // b, a % b
3700
3701 a, b = b, r
3702 s_old, s_new = s_new, s_old - q * s_new
3703 t_old, t_new = t_new, t_old - q * t_new
3704
3705 return s_old, t_old, s_new, t_new
3706
3707 @jit.elidable
3708 def gcd_lehmer(a, b):
3709 if a.lt(b):
3710 a, b = b, a
3711
3712 while b.numdigits() > 1:
3713 a_ms = a.digit(abs(a.numdigits()-1))
3714
3715 x = 0
3716 while a_ms & (0xFF << SHIFT-8) == 0:
3717 a_ms <<= 8
3718 x += 8
3719
3720 while a_ms & (1 << SHIFT-1) == 0:
3721 a_ms <<= 1
3722 x += 1
3723
3724 a_ms |= a.digit(abs(a.numdigits()-2)) >> SHIFT-x
3725
3726 if a.numdigits() == b.numdigits():
3727 b_ms = (b.digit(abs(b.numdigits()-1)) << x) | (b.digit(abs(b.numdigits()-2)) >> SHIFT-x)
3728 elif a.numdigits() == b.numdigits()+1:
3729 b_ms = b.digit(abs(b.numdigits()-1)) >> SHIFT-x
3730 else:
3731 b_ms = 0
3732
3733 if b_ms >> (SHIFT+1 >> 1) == 0:
3734 a, b = b, a.mod(b)
3735 continue
3736
3737 s_old, t_old, s_new, t_new = lehmer_xgcd(a_ms, b_ms)
3738
3739 n_a = a.int_mul(s_new).add(b.int_mul(t_new)).abs()
3740 b = a.int_mul(s_old).add(b.int_mul(t_old)).abs()
3741 a = n_a
3742
3743 if a.lt(b):
3744 a, b = b, a
3745
3746 if not b.tobool():
3747 return a
3748
3749 a = a.mod(b)
3750 return rbigint.fromint(gcd_binary(b.toint(), a.toint()))
3751
3752
3753 # if the bigint has more digits than this, it cannot fit into an int
3754 # Also, if it has less digits than this, then it must be <=sys.maxint in
3755 # absolute value and so it must fit an int.
3756 MAX_DIGITS_THAT_CAN_FIT_IN_INT = rbigint.fromint(-sys.maxint - 1).numdigits()
3757
3758
3759 # _________________________________________________________________
3760 # tobytes and frombytes for integers
3761
3762 @jit.elidable
3763 def frombytes_int(s, byteorder, signed):
3764 """ like rbigint.frombytes but returns an int. raises OverflowError if not
3765 possible """
3766 if byteorder not in ('big', 'little'):
3767 raise InvalidEndiannessError()
3768 if not s:
3769 return 0
3770
3771 if byteorder == 'big':
3772 msb = ord(s[0])
3773 itr = range(len(s)-1, -1, -1)
3774 else:
3775 msb = ord(s[-1])
3776 itr = range(0, len(s))
3777
3778 sign = -1 if msb >= 0x80 and signed else 1
3779 result = r_uint(0)
3780 bitpos = 0
3781 pad_byte = 0xdead
3782
3783 for i in itr:
3784 c = r_uint(ord(s[i]))
3785 if bitpos == LONG_BIT - 8:
3786 if signed and c & (1 << 7): # signed and negative
3787 pad_byte = 0xff
3788 else:
3789 pad_byte = 0x00
3790
3791 if bitpos >= LONG_BIT:
3792 # Extra bytes are only OK if they're padding (0x00 or 0xff)
3793 if c != pad_byte:
3794 raise OverflowError("value does not fit in int")
3795 else:
3796 result |= c << bitpos
3797 bitpos += 8
3798 if signed and bitpos <= LONG_BIT:
3799 # sign extend
3800 m = r_uint(1) << (bitpos - 1)
3801 result = (result ^ m) - m
3802
3803 result = intmask(result)
3804
3805 if sign == -1:
3806 assert result < 0
3807 elif not signed and result < 0:
3808 raise OverflowError("value does not fit in int")
3809
3810 return result
3811
3812
3813 @jit.elidable
3814 def tobytes_int(intval, nbytes, byteorder, signed):
3815 """ like rbigint.tobytes, but starts from an int """
3816 if byteorder not in ('big', 'little'):
3817 raise InvalidEndiannessError()
3818 if not signed and intval < 0:
3819 raise InvalidSignednessError()
3820
3821 bswap = byteorder == 'big'
3822 result = StringBuilder(nbytes)
3823
3824 currval = intval
3825 byte = 0
3826 for i in range(nbytes):
3827 byte = currval & 0xff
3828 result.append(chr(byte))
3829 currval >>= 8
3830 if currval != 0 and currval != -1:
3831 raise OverflowError
3832
3833 digits = result.build()
3834 if nbytes > 0 and signed:
3835 # If not already set, we cannot contain the sign bit
3836 if (intval < 0) != (byte >= 0x80):
3837 raise OverflowError()
3838
3839 if bswap:
3840 # Bah, this is very inefficient. At least it's not
3841 # quadratic.
3842 length = len(digits)
3843 if length >= 0:
3844 digits = ''.join([digits[i] for i in range(length-1, -1, -1)])
3845 return digits
3846