]> git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/PyMod-2.7.2/Objects/longobject.c
AppPkg|Python: Files from the Python 2.7.2 distribution that must be modified to...
[mirror_edk2.git] / AppPkg / Applications / Python / PyMod-2.7.2 / Objects / longobject.c
1 /* Long (arbitrary precision) integer object implementation */
2
3 /* XXX The functional organization of this file is terrible */
4
5 #include "Python.h"
6 #include "longintrepr.h"
7 #include "structseq.h"
8
9 #include <float.h>
10 #include <ctype.h>
11 #include <stddef.h>
12
13 /* For long multiplication, use the O(N**2) school algorithm unless
14 * both operands contain more than KARATSUBA_CUTOFF digits (this
15 * being an internal Python long digit, in base PyLong_BASE).
16 */
17 #define KARATSUBA_CUTOFF 70
18 #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
19
20 /* For exponentiation, use the binary left-to-right algorithm
21 * unless the exponent contains more than FIVEARY_CUTOFF digits.
22 * In that case, do 5 bits at a time. The potential drawback is that
23 * a table of 2**5 intermediate results is computed.
24 */
25 #define FIVEARY_CUTOFF 8
26
27 #ifndef ABS
28 #define ABS(x) ((x) < 0 ? -(x) : (x))
29 #endif
30
31 #ifndef MAX
32 #define MAX(x, y) ((x) < (y) ? (y) : (x))
33 #endif
34
35 #ifndef MIN
36 #define MIN(x, y) ((x) > (y) ? (y) : (x))
37 #endif
38
39 #define SIGCHECK(PyTryBlock) \
40 do { \
41 if (--_Py_Ticker < 0) { \
42 _Py_Ticker = _Py_CheckInterval; \
43 if (PyErr_CheckSignals()) PyTryBlock \
44 } \
45 } while(0)
46
47 /* Normalize (remove leading zeros from) a long int object.
48 Doesn't attempt to free the storage--in most cases, due to the nature
49 of the algorithms used, this could save at most be one word anyway. */
50
51 static PyLongObject *
52 long_normalize(register PyLongObject *v)
53 {
54 Py_ssize_t j = ABS(Py_SIZE(v));
55 Py_ssize_t i = j;
56
57 while (i > 0 && v->ob_digit[i-1] == 0)
58 --i;
59 if (i != j)
60 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
61 return v;
62 }
63
64 /* Allocate a new long int object with size digits.
65 Return NULL and set exception if we run out of memory. */
66
67 #define MAX_LONG_DIGITS \
68 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
69
70 PyLongObject *
71 _PyLong_New(Py_ssize_t size)
72 {
73 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
74 PyErr_SetString(PyExc_OverflowError,
75 "too many digits in integer");
76 return NULL;
77 }
78 /* coverity[ampersand_in_size] */
79 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
80 overflow */
81 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
82 }
83
84 PyObject *
85 _PyLong_Copy(PyLongObject *src)
86 {
87 PyLongObject *result;
88 Py_ssize_t i;
89
90 assert(src != NULL);
91 i = src->ob_size;
92 if (i < 0)
93 i = -(i);
94 result = _PyLong_New(i);
95 if (result != NULL) {
96 result->ob_size = src->ob_size;
97 while (--i >= 0)
98 result->ob_digit[i] = src->ob_digit[i];
99 }
100 return (PyObject *)result;
101 }
102
103 /* Create a new long int object from a C long int */
104
105 PyObject *
106 PyLong_FromLong(long ival)
107 {
108 PyLongObject *v;
109 unsigned long abs_ival;
110 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
111 int ndigits = 0;
112 int negative = 0;
113
114 if (ival < 0) {
115 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
116 ANSI C says that the result of -ival is undefined when ival
117 == LONG_MIN. Hence the following workaround. */
118 abs_ival = (unsigned long)(-1-ival) + 1;
119 negative = 1;
120 }
121 else {
122 abs_ival = (unsigned long)ival;
123 }
124
125 /* Count the number of Python digits.
126 We used to pick 5 ("big enough for anything"), but that's a
127 waste of time and space given that 5*15 = 75 bits are rarely
128 needed. */
129 t = abs_ival;
130 while (t) {
131 ++ndigits;
132 t >>= PyLong_SHIFT;
133 }
134 v = _PyLong_New(ndigits);
135 if (v != NULL) {
136 digit *p = v->ob_digit;
137 v->ob_size = negative ? -ndigits : ndigits;
138 t = abs_ival;
139 while (t) {
140 *p++ = (digit)(t & PyLong_MASK);
141 t >>= PyLong_SHIFT;
142 }
143 }
144 return (PyObject *)v;
145 }
146
147 /* Create a new long int object from a C unsigned long int */
148
149 PyObject *
150 PyLong_FromUnsignedLong(unsigned long ival)
151 {
152 PyLongObject *v;
153 unsigned long t;
154 int ndigits = 0;
155
156 /* Count the number of Python digits. */
157 t = (unsigned long)ival;
158 while (t) {
159 ++ndigits;
160 t >>= PyLong_SHIFT;
161 }
162 v = _PyLong_New(ndigits);
163 if (v != NULL) {
164 digit *p = v->ob_digit;
165 Py_SIZE(v) = ndigits;
166 while (ival) {
167 *p++ = (digit)(ival & PyLong_MASK);
168 ival >>= PyLong_SHIFT;
169 }
170 }
171 return (PyObject *)v;
172 }
173
174 /* Create a new long int object from a C double */
175
176 PyObject *
177 PyLong_FromDouble(double dval)
178 {
179 PyLongObject *v;
180 double frac;
181 int i, ndig, expo, neg;
182 neg = 0;
183 if (Py_IS_INFINITY(dval)) {
184 PyErr_SetString(PyExc_OverflowError,
185 "cannot convert float infinity to integer");
186 return NULL;
187 }
188 if (Py_IS_NAN(dval)) {
189 PyErr_SetString(PyExc_ValueError,
190 "cannot convert float NaN to integer");
191 return NULL;
192 }
193 if (dval < 0.0) {
194 neg = 1;
195 dval = -dval;
196 }
197 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
198 if (expo <= 0)
199 return PyLong_FromLong(0L);
200 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
201 v = _PyLong_New(ndig);
202 if (v == NULL)
203 return NULL;
204 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
205 for (i = ndig; --i >= 0; ) {
206 digit bits = (digit)frac;
207 v->ob_digit[i] = bits;
208 frac = frac - (double)bits;
209 frac = ldexp(frac, PyLong_SHIFT);
210 }
211 if (neg)
212 Py_SIZE(v) = -(Py_SIZE(v));
213 return (PyObject *)v;
214 }
215
216 /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
217 * anything about what happens when a signed integer operation overflows,
218 * and some compilers think they're doing you a favor by being "clever"
219 * then. The bit pattern for the largest postive signed long is
220 * (unsigned long)LONG_MAX, and for the smallest negative signed long
221 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
222 * However, some other compilers warn about applying unary minus to an
223 * unsigned operand. Hence the weird "0-".
224 */
225 #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
226 #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
227
228 /* Get a C long int from a Python long or Python int object.
229 On overflow, returns -1 and sets *overflow to 1 or -1 depending
230 on the sign of the result. Otherwise *overflow is 0.
231
232 For other errors (e.g., type error), returns -1 and sets an error
233 condition.
234 */
235
236 long
237 PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
238 {
239 /* This version by Tim Peters */
240 register PyLongObject *v;
241 unsigned long x, prev;
242 long res;
243 Py_ssize_t i;
244 int sign;
245 int do_decref = 0; /* if nb_int was called */
246
247 *overflow = 0;
248 if (vv == NULL) {
249 PyErr_BadInternalCall();
250 return -1;
251 }
252
253 if(PyInt_Check(vv))
254 return PyInt_AsLong(vv);
255
256 if (!PyLong_Check(vv)) {
257 PyNumberMethods *nb;
258 nb = vv->ob_type->tp_as_number;
259 if (nb == NULL || nb->nb_int == NULL) {
260 PyErr_SetString(PyExc_TypeError,
261 "an integer is required");
262 return -1;
263 }
264 vv = (*nb->nb_int) (vv);
265 if (vv == NULL)
266 return -1;
267 do_decref = 1;
268 if(PyInt_Check(vv)) {
269 res = PyInt_AsLong(vv);
270 goto exit;
271 }
272 if (!PyLong_Check(vv)) {
273 Py_DECREF(vv);
274 PyErr_SetString(PyExc_TypeError,
275 "nb_int should return int object");
276 return -1;
277 }
278 }
279
280 res = -1;
281 v = (PyLongObject *)vv;
282 i = Py_SIZE(v);
283
284 switch (i) {
285 case -1:
286 res = -(sdigit)v->ob_digit[0];
287 break;
288 case 0:
289 res = 0;
290 break;
291 case 1:
292 res = v->ob_digit[0];
293 break;
294 default:
295 sign = 1;
296 x = 0;
297 if (i < 0) {
298 sign = -1;
299 i = -(i);
300 }
301 while (--i >= 0) {
302 prev = x;
303 x = (x << PyLong_SHIFT) + v->ob_digit[i];
304 if ((x >> PyLong_SHIFT) != prev) {
305 *overflow = sign;
306 goto exit;
307 }
308 }
309 /* Haven't lost any bits, but casting to long requires extra
310 * care (see comment above).
311 */
312 if (x <= (unsigned long)LONG_MAX) {
313 res = (long)x * sign;
314 }
315 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
316 res = LONG_MIN;
317 }
318 else {
319 *overflow = sign;
320 /* res is already set to -1 */
321 }
322 }
323 exit:
324 if (do_decref) {
325 Py_DECREF(vv);
326 }
327 return res;
328 }
329
330 /* Get a C long int from a long int object.
331 Returns -1 and sets an error condition if overflow occurs. */
332
333 long
334 PyLong_AsLong(PyObject *obj)
335 {
336 int overflow;
337 long result = PyLong_AsLongAndOverflow(obj, &overflow);
338 if (overflow) {
339 /* XXX: could be cute and give a different
340 message for overflow == -1 */
341 PyErr_SetString(PyExc_OverflowError,
342 "Python int too large to convert to C long");
343 }
344 return result;
345 }
346
347 /* Get a Py_ssize_t from a long int object.
348 Returns -1 and sets an error condition if overflow occurs. */
349
350 Py_ssize_t
351 PyLong_AsSsize_t(PyObject *vv) {
352 register PyLongObject *v;
353 size_t x, prev;
354 Py_ssize_t i;
355 int sign;
356
357 if (vv == NULL || !PyLong_Check(vv)) {
358 PyErr_BadInternalCall();
359 return -1;
360 }
361 v = (PyLongObject *)vv;
362 i = v->ob_size;
363 sign = 1;
364 x = 0;
365 if (i < 0) {
366 sign = -1;
367 i = -(i);
368 }
369 while (--i >= 0) {
370 prev = x;
371 x = (x << PyLong_SHIFT) | v->ob_digit[i];
372 if ((x >> PyLong_SHIFT) != prev)
373 goto overflow;
374 }
375 /* Haven't lost any bits, but casting to a signed type requires
376 * extra care (see comment above).
377 */
378 if (x <= (size_t)PY_SSIZE_T_MAX) {
379 return (Py_ssize_t)x * sign;
380 }
381 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
382 return PY_SSIZE_T_MIN;
383 }
384 /* else overflow */
385
386 overflow:
387 PyErr_SetString(PyExc_OverflowError,
388 "long int too large to convert to int");
389 return -1;
390 }
391
392 /* Get a C unsigned long int from a long int object.
393 Returns -1 and sets an error condition if overflow occurs. */
394
395 unsigned long
396 PyLong_AsUnsignedLong(PyObject *vv)
397 {
398 register PyLongObject *v;
399 unsigned long x, prev;
400 Py_ssize_t i;
401
402 if (vv == NULL || !PyLong_Check(vv)) {
403 if (vv != NULL && PyInt_Check(vv)) {
404 long val = PyInt_AsLong(vv);
405 if (val < 0) {
406 PyErr_SetString(PyExc_OverflowError,
407 "can't convert negative value "
408 "to unsigned long");
409 return (unsigned long) -1;
410 }
411 return val;
412 }
413 PyErr_BadInternalCall();
414 return (unsigned long) -1;
415 }
416 v = (PyLongObject *)vv;
417 i = Py_SIZE(v);
418 x = 0;
419 if (i < 0) {
420 PyErr_SetString(PyExc_OverflowError,
421 "can't convert negative value to unsigned long");
422 return (unsigned long) -1;
423 }
424 while (--i >= 0) {
425 prev = x;
426 x = (x << PyLong_SHIFT) | v->ob_digit[i];
427 if ((x >> PyLong_SHIFT) != prev) {
428 PyErr_SetString(PyExc_OverflowError,
429 "long int too large to convert");
430 return (unsigned long) -1;
431 }
432 }
433 return x;
434 }
435
436 /* Get a C unsigned long int from a long int object, ignoring the high bits.
437 Returns -1 and sets an error condition if an error occurs. */
438
439 unsigned long
440 PyLong_AsUnsignedLongMask(PyObject *vv)
441 {
442 register PyLongObject *v;
443 unsigned long x;
444 Py_ssize_t i;
445 int sign;
446
447 if (vv == NULL || !PyLong_Check(vv)) {
448 if (vv != NULL && PyInt_Check(vv))
449 return PyInt_AsUnsignedLongMask(vv);
450 PyErr_BadInternalCall();
451 return (unsigned long) -1;
452 }
453 v = (PyLongObject *)vv;
454 i = v->ob_size;
455 sign = 1;
456 x = 0;
457 if (i < 0) {
458 sign = -1;
459 i = -i;
460 }
461 while (--i >= 0) {
462 x = (x << PyLong_SHIFT) | v->ob_digit[i];
463 }
464 return x * sign;
465 }
466
467 int
468 _PyLong_Sign(PyObject *vv)
469 {
470 PyLongObject *v = (PyLongObject *)vv;
471
472 assert(v != NULL);
473 assert(PyLong_Check(v));
474
475 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
476 }
477
478 size_t
479 _PyLong_NumBits(PyObject *vv)
480 {
481 PyLongObject *v = (PyLongObject *)vv;
482 size_t result = 0;
483 Py_ssize_t ndigits;
484
485 assert(v != NULL);
486 assert(PyLong_Check(v));
487 ndigits = ABS(Py_SIZE(v));
488 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
489 if (ndigits > 0) {
490 digit msd = v->ob_digit[ndigits - 1];
491
492 result = (ndigits - 1) * PyLong_SHIFT;
493 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
494 goto Overflow;
495 do {
496 ++result;
497 if (result == 0)
498 goto Overflow;
499 msd >>= 1;
500 } while (msd);
501 }
502 return result;
503
504 Overflow:
505 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
506 "to express in a platform size_t");
507 return (size_t)-1;
508 }
509
510 PyObject *
511 _PyLong_FromByteArray(const unsigned char* bytes, size_t n,
512 int little_endian, int is_signed)
513 {
514 const unsigned char* pstartbyte; /* LSB of bytes */
515 int incr; /* direction to move pstartbyte */
516 const unsigned char* pendbyte; /* MSB of bytes */
517 size_t numsignificantbytes; /* number of bytes that matter */
518 Py_ssize_t ndigits; /* number of Python long digits */
519 PyLongObject* v; /* result */
520 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
521
522 if (n == 0)
523 return PyLong_FromLong(0L);
524
525 if (little_endian) {
526 pstartbyte = bytes;
527 pendbyte = bytes + n - 1;
528 incr = 1;
529 }
530 else {
531 pstartbyte = bytes + n - 1;
532 pendbyte = bytes;
533 incr = -1;
534 }
535
536 if (is_signed)
537 is_signed = *pendbyte >= 0x80;
538
539 /* Compute numsignificantbytes. This consists of finding the most
540 significant byte. Leading 0 bytes are insignificant if the number
541 is positive, and leading 0xff bytes if negative. */
542 {
543 size_t i;
544 const unsigned char* p = pendbyte;
545 const int pincr = -incr; /* search MSB to LSB */
546 const unsigned char insignficant = is_signed ? 0xff : 0x00;
547
548 for (i = 0; i < n; ++i, p += pincr) {
549 if (*p != insignficant)
550 break;
551 }
552 numsignificantbytes = n - i;
553 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
554 actually has 2 significant bytes. OTOH, 0xff0001 ==
555 -0x00ffff, so we wouldn't *need* to bump it there; but we
556 do for 0xffff = -0x0001. To be safe without bothering to
557 check every case, bump it regardless. */
558 if (is_signed && numsignificantbytes < n)
559 ++numsignificantbytes;
560 }
561
562 /* How many Python long digits do we need? We have
563 8*numsignificantbytes bits, and each Python long digit has
564 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
565 /* catch overflow before it happens */
566 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
567 PyErr_SetString(PyExc_OverflowError,
568 "byte array too long to convert to int");
569 return NULL;
570 }
571 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
572 v = _PyLong_New(ndigits);
573 if (v == NULL)
574 return NULL;
575
576 /* Copy the bits over. The tricky parts are computing 2's-comp on
577 the fly for signed numbers, and dealing with the mismatch between
578 8-bit bytes and (probably) 15-bit Python digits.*/
579 {
580 size_t i;
581 twodigits carry = 1; /* for 2's-comp calculation */
582 twodigits accum = 0; /* sliding register */
583 unsigned int accumbits = 0; /* number of bits in accum */
584 const unsigned char* p = pstartbyte;
585
586 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
587 twodigits thisbyte = *p;
588 /* Compute correction for 2's comp, if needed. */
589 if (is_signed) {
590 thisbyte = (0xff ^ thisbyte) + carry;
591 carry = thisbyte >> 8;
592 thisbyte &= 0xff;
593 }
594 /* Because we're going LSB to MSB, thisbyte is
595 more significant than what's already in accum,
596 so needs to be prepended to accum. */
597 accum |= (twodigits)thisbyte << accumbits;
598 accumbits += 8;
599 if (accumbits >= PyLong_SHIFT) {
600 /* There's enough to fill a Python digit. */
601 assert(idigit < ndigits);
602 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
603 ++idigit;
604 accum >>= PyLong_SHIFT;
605 accumbits -= PyLong_SHIFT;
606 assert(accumbits < PyLong_SHIFT);
607 }
608 }
609 assert(accumbits < PyLong_SHIFT);
610 if (accumbits) {
611 assert(idigit < ndigits);
612 v->ob_digit[idigit] = (digit)accum;
613 ++idigit;
614 }
615 }
616
617 Py_SIZE(v) = is_signed ? -idigit : idigit;
618 return (PyObject *)long_normalize(v);
619 }
620
621 int
622 _PyLong_AsByteArray(PyLongObject* v,
623 unsigned char* bytes, size_t n,
624 int little_endian, int is_signed)
625 {
626 Py_ssize_t i; /* index into v->ob_digit */
627 Py_ssize_t ndigits; /* |v->ob_size| */
628 twodigits accum; /* sliding register */
629 unsigned int accumbits; /* # bits in accum */
630 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
631 digit carry; /* for computing 2's-comp */
632 size_t j; /* # bytes filled */
633 unsigned char* p; /* pointer to next byte in bytes */
634 int pincr; /* direction to move p */
635
636 assert(v != NULL && PyLong_Check(v));
637
638 if (Py_SIZE(v) < 0) {
639 ndigits = -(Py_SIZE(v));
640 if (!is_signed) {
641 PyErr_SetString(PyExc_OverflowError,
642 "can't convert negative long to unsigned");
643 return -1;
644 }
645 do_twos_comp = 1;
646 }
647 else {
648 ndigits = Py_SIZE(v);
649 do_twos_comp = 0;
650 }
651
652 if (little_endian) {
653 p = bytes;
654 pincr = 1;
655 }
656 else {
657 p = bytes + n - 1;
658 pincr = -1;
659 }
660
661 /* Copy over all the Python digits.
662 It's crucial that every Python digit except for the MSD contribute
663 exactly PyLong_SHIFT bits to the total, so first assert that the long is
664 normalized. */
665 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
666 j = 0;
667 accum = 0;
668 accumbits = 0;
669 carry = do_twos_comp ? 1 : 0;
670 for (i = 0; i < ndigits; ++i) {
671 digit thisdigit = v->ob_digit[i];
672 if (do_twos_comp) {
673 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
674 carry = thisdigit >> PyLong_SHIFT;
675 thisdigit &= PyLong_MASK;
676 }
677 /* Because we're going LSB to MSB, thisdigit is more
678 significant than what's already in accum, so needs to be
679 prepended to accum. */
680 accum |= (twodigits)thisdigit << accumbits;
681
682 /* The most-significant digit may be (probably is) at least
683 partly empty. */
684 if (i == ndigits - 1) {
685 /* Count # of sign bits -- they needn't be stored,
686 * although for signed conversion we need later to
687 * make sure at least one sign bit gets stored. */
688 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
689 while (s != 0) {
690 s >>= 1;
691 accumbits++;
692 }
693 }
694 else
695 accumbits += PyLong_SHIFT;
696
697 /* Store as many bytes as possible. */
698 while (accumbits >= 8) {
699 if (j >= n)
700 goto Overflow;
701 ++j;
702 *p = (unsigned char)(accum & 0xff);
703 p += pincr;
704 accumbits -= 8;
705 accum >>= 8;
706 }
707 }
708
709 /* Store the straggler (if any). */
710 assert(accumbits < 8);
711 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
712 if (accumbits > 0) {
713 if (j >= n)
714 goto Overflow;
715 ++j;
716 if (do_twos_comp) {
717 /* Fill leading bits of the byte with sign bits
718 (appropriately pretending that the long had an
719 infinite supply of sign bits). */
720 accum |= (~(twodigits)0) << accumbits;
721 }
722 *p = (unsigned char)(accum & 0xff);
723 p += pincr;
724 }
725 else if (j == n && n > 0 && is_signed) {
726 /* The main loop filled the byte array exactly, so the code
727 just above didn't get to ensure there's a sign bit, and the
728 loop below wouldn't add one either. Make sure a sign bit
729 exists. */
730 unsigned char msb = *(p - pincr);
731 int sign_bit_set = msb >= 0x80;
732 assert(accumbits == 0);
733 if (sign_bit_set == do_twos_comp)
734 return 0;
735 else
736 goto Overflow;
737 }
738
739 /* Fill remaining bytes with copies of the sign bit. */
740 {
741 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
742 for ( ; j < n; ++j, p += pincr)
743 *p = signbyte;
744 }
745
746 return 0;
747
748 Overflow:
749 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
750 return -1;
751
752 }
753
754 /* Create a new long (or int) object from a C pointer */
755
756 PyObject *
757 PyLong_FromVoidPtr(void *p)
758 {
759 #if SIZEOF_VOID_P <= SIZEOF_LONG
760 if ((long)p < 0)
761 return PyLong_FromUnsignedLong((unsigned long)p);
762 return PyInt_FromLong((long)p);
763 #else
764
765 #ifndef HAVE_LONG_LONG
766 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
767 #endif
768 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
769 # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
770 #endif
771 /* optimize null pointers */
772 if (p == NULL)
773 return PyInt_FromLong(0);
774 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
775
776 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
777 }
778
779 /* Get a C pointer from a long object (or an int object in some cases) */
780
781 void *
782 PyLong_AsVoidPtr(PyObject *vv)
783 {
784 /* This function will allow int or long objects. If vv is neither,
785 then the PyLong_AsLong*() functions will raise the exception:
786 PyExc_SystemError, "bad argument to internal function"
787 */
788 #if SIZEOF_VOID_P <= SIZEOF_LONG
789 long x;
790
791 if (PyInt_Check(vv))
792 x = PyInt_AS_LONG(vv);
793 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
794 x = PyLong_AsLong(vv);
795 else
796 x = PyLong_AsUnsignedLong(vv);
797 #else
798
799 #ifndef HAVE_LONG_LONG
800 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
801 #endif
802 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
803 # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
804 #endif
805 PY_LONG_LONG x;
806
807 if (PyInt_Check(vv))
808 x = PyInt_AS_LONG(vv);
809 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
810 x = PyLong_AsLongLong(vv);
811 else
812 x = PyLong_AsUnsignedLongLong(vv);
813
814 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
815
816 if (x == -1 && PyErr_Occurred())
817 return NULL;
818 return (void *)x;
819 }
820
821 #ifdef HAVE_LONG_LONG
822
823 /* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
824 * rewritten to use the newer PyLong_{As,From}ByteArray API.
825 */
826
827 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
828 #define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
829
830 /* Create a new long int object from a C PY_LONG_LONG int. */
831
832 PyObject *
833 PyLong_FromLongLong(PY_LONG_LONG ival)
834 {
835 PyLongObject *v;
836 unsigned PY_LONG_LONG abs_ival;
837 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
838 int ndigits = 0;
839 int negative = 0;
840
841 if (ival < 0) {
842 /* avoid signed overflow on negation; see comments
843 in PyLong_FromLong above. */
844 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
845 negative = 1;
846 }
847 else {
848 abs_ival = (unsigned PY_LONG_LONG)ival;
849 }
850
851 /* Count the number of Python digits.
852 We used to pick 5 ("big enough for anything"), but that's a
853 waste of time and space given that 5*15 = 75 bits are rarely
854 needed. */
855 t = abs_ival;
856 while (t) {
857 ++ndigits;
858 t >>= PyLong_SHIFT;
859 }
860 v = _PyLong_New(ndigits);
861 if (v != NULL) {
862 digit *p = v->ob_digit;
863 Py_SIZE(v) = negative ? -ndigits : ndigits;
864 t = abs_ival;
865 while (t) {
866 *p++ = (digit)(t & PyLong_MASK);
867 t >>= PyLong_SHIFT;
868 }
869 }
870 return (PyObject *)v;
871 }
872
873 /* Create a new long int object from a C unsigned PY_LONG_LONG int. */
874
875 PyObject *
876 PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
877 {
878 PyLongObject *v;
879 unsigned PY_LONG_LONG t;
880 int ndigits = 0;
881
882 /* Count the number of Python digits. */
883 t = (unsigned PY_LONG_LONG)ival;
884 while (t) {
885 ++ndigits;
886 t >>= PyLong_SHIFT;
887 }
888 v = _PyLong_New(ndigits);
889 if (v != NULL) {
890 digit *p = v->ob_digit;
891 Py_SIZE(v) = ndigits;
892 while (ival) {
893 *p++ = (digit)(ival & PyLong_MASK);
894 ival >>= PyLong_SHIFT;
895 }
896 }
897 return (PyObject *)v;
898 }
899
900 /* Create a new long int object from a C Py_ssize_t. */
901
902 PyObject *
903 PyLong_FromSsize_t(Py_ssize_t ival)
904 {
905 Py_ssize_t bytes = ival;
906 int one = 1;
907 return _PyLong_FromByteArray((unsigned char *)&bytes,
908 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
909 }
910
911 /* Create a new long int object from a C size_t. */
912
913 PyObject *
914 PyLong_FromSize_t(size_t ival)
915 {
916 size_t bytes = ival;
917 int one = 1;
918 return _PyLong_FromByteArray((unsigned char *)&bytes,
919 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
920 }
921
922 /* Get a C PY_LONG_LONG int from a long int object.
923 Return -1 and set an error if overflow occurs. */
924
925 PY_LONG_LONG
926 PyLong_AsLongLong(PyObject *vv)
927 {
928 PY_LONG_LONG bytes;
929 int one = 1;
930 int res;
931
932 if (vv == NULL) {
933 PyErr_BadInternalCall();
934 return -1;
935 }
936 if (!PyLong_Check(vv)) {
937 PyNumberMethods *nb;
938 PyObject *io;
939 if (PyInt_Check(vv))
940 return (PY_LONG_LONG)PyInt_AsLong(vv);
941 if ((nb = vv->ob_type->tp_as_number) == NULL ||
942 nb->nb_int == NULL) {
943 PyErr_SetString(PyExc_TypeError, "an integer is required");
944 return -1;
945 }
946 io = (*nb->nb_int) (vv);
947 if (io == NULL)
948 return -1;
949 if (PyInt_Check(io)) {
950 bytes = PyInt_AsLong(io);
951 Py_DECREF(io);
952 return bytes;
953 }
954 if (PyLong_Check(io)) {
955 bytes = PyLong_AsLongLong(io);
956 Py_DECREF(io);
957 return bytes;
958 }
959 Py_DECREF(io);
960 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
961 return -1;
962 }
963
964 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
965 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
966
967 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
968 if (res < 0)
969 return (PY_LONG_LONG)-1;
970 else
971 return bytes;
972 }
973
974 /* Get a C unsigned PY_LONG_LONG int from a long int object.
975 Return -1 and set an error if overflow occurs. */
976
977 unsigned PY_LONG_LONG
978 PyLong_AsUnsignedLongLong(PyObject *vv)
979 {
980 unsigned PY_LONG_LONG bytes;
981 int one = 1;
982 int res;
983
984 if (vv == NULL || !PyLong_Check(vv)) {
985 PyErr_BadInternalCall();
986 return (unsigned PY_LONG_LONG)-1;
987 }
988
989 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
990 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
991
992 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
993 if (res < 0)
994 return (unsigned PY_LONG_LONG)res;
995 else
996 return bytes;
997 }
998
999 /* Get a C unsigned long int from a long int object, ignoring the high bits.
1000 Returns -1 and sets an error condition if an error occurs. */
1001
1002 unsigned PY_LONG_LONG
1003 PyLong_AsUnsignedLongLongMask(PyObject *vv)
1004 {
1005 register PyLongObject *v;
1006 unsigned PY_LONG_LONG x;
1007 Py_ssize_t i;
1008 int sign;
1009
1010 if (vv == NULL || !PyLong_Check(vv)) {
1011 PyErr_BadInternalCall();
1012 return (unsigned long) -1;
1013 }
1014 v = (PyLongObject *)vv;
1015 i = v->ob_size;
1016 sign = 1;
1017 x = 0;
1018 if (i < 0) {
1019 sign = -1;
1020 i = -i;
1021 }
1022 while (--i >= 0) {
1023 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1024 }
1025 return x * sign;
1026 }
1027
1028 /* Get a C long long int from a Python long or Python int object.
1029 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1030 on the sign of the result. Otherwise *overflow is 0.
1031
1032 For other errors (e.g., type error), returns -1 and sets an error
1033 condition.
1034 */
1035
1036 PY_LONG_LONG
1037 PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1038 {
1039 /* This version by Tim Peters */
1040 register PyLongObject *v;
1041 unsigned PY_LONG_LONG x, prev;
1042 PY_LONG_LONG res;
1043 Py_ssize_t i;
1044 int sign;
1045 int do_decref = 0; /* if nb_int was called */
1046
1047 *overflow = 0;
1048 if (vv == NULL) {
1049 PyErr_BadInternalCall();
1050 return -1;
1051 }
1052
1053 if (PyInt_Check(vv))
1054 return PyInt_AsLong(vv);
1055
1056 if (!PyLong_Check(vv)) {
1057 PyNumberMethods *nb;
1058 nb = vv->ob_type->tp_as_number;
1059 if (nb == NULL || nb->nb_int == NULL) {
1060 PyErr_SetString(PyExc_TypeError,
1061 "an integer is required");
1062 return -1;
1063 }
1064 vv = (*nb->nb_int) (vv);
1065 if (vv == NULL)
1066 return -1;
1067 do_decref = 1;
1068 if(PyInt_Check(vv)) {
1069 res = PyInt_AsLong(vv);
1070 goto exit;
1071 }
1072 if (!PyLong_Check(vv)) {
1073 Py_DECREF(vv);
1074 PyErr_SetString(PyExc_TypeError,
1075 "nb_int should return int object");
1076 return -1;
1077 }
1078 }
1079
1080 res = -1;
1081 v = (PyLongObject *)vv;
1082 i = Py_SIZE(v);
1083
1084 switch (i) {
1085 case -1:
1086 res = -(sdigit)v->ob_digit[0];
1087 break;
1088 case 0:
1089 res = 0;
1090 break;
1091 case 1:
1092 res = v->ob_digit[0];
1093 break;
1094 default:
1095 sign = 1;
1096 x = 0;
1097 if (i < 0) {
1098 sign = -1;
1099 i = -(i);
1100 }
1101 while (--i >= 0) {
1102 prev = x;
1103 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1104 if ((x >> PyLong_SHIFT) != prev) {
1105 *overflow = sign;
1106 goto exit;
1107 }
1108 }
1109 /* Haven't lost any bits, but casting to long requires extra
1110 * care (see comment above).
1111 */
1112 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1113 res = (PY_LONG_LONG)x * sign;
1114 }
1115 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1116 res = PY_LLONG_MIN;
1117 }
1118 else {
1119 *overflow = sign;
1120 /* res is already set to -1 */
1121 }
1122 }
1123 exit:
1124 if (do_decref) {
1125 Py_DECREF(vv);
1126 }
1127 return res;
1128 }
1129
1130 #undef IS_LITTLE_ENDIAN
1131
1132 #endif /* HAVE_LONG_LONG */
1133
1134
1135 static int
1136 convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
1137 if (PyLong_Check(v)) {
1138 *a = (PyLongObject *) v;
1139 Py_INCREF(v);
1140 }
1141 else if (PyInt_Check(v)) {
1142 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1143 }
1144 else {
1145 return 0;
1146 }
1147 if (PyLong_Check(w)) {
1148 *b = (PyLongObject *) w;
1149 Py_INCREF(w);
1150 }
1151 else if (PyInt_Check(w)) {
1152 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1153 }
1154 else {
1155 Py_DECREF(*a);
1156 return 0;
1157 }
1158 return 1;
1159 }
1160
1161 #define CONVERT_BINOP(v, w, a, b) \
1162 do { \
1163 if (!convert_binop(v, w, a, b)) { \
1164 Py_INCREF(Py_NotImplemented); \
1165 return Py_NotImplemented; \
1166 } \
1167 } while(0) \
1168
1169 /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1170 2**k if d is nonzero, else 0. */
1171
1172 static const unsigned char BitLengthTable[32] = {
1173 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1174 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1175 };
1176
1177 static int
1178 bits_in_digit(digit d)
1179 {
1180 int d_bits = 0;
1181 while (d >= 32) {
1182 d_bits += 6;
1183 d >>= 6;
1184 }
1185 d_bits += (int)BitLengthTable[d];
1186 return d_bits;
1187 }
1188
1189 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1190 * is modified in place, by adding y to it. Carries are propagated as far as
1191 * x[m-1], and the remaining carry (0 or 1) is returned.
1192 */
1193 static digit
1194 v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1195 {
1196 Py_ssize_t i;
1197 digit carry = 0;
1198
1199 assert(m >= n);
1200 for (i = 0; i < n; ++i) {
1201 carry += x[i] + y[i];
1202 x[i] = carry & PyLong_MASK;
1203 carry >>= PyLong_SHIFT;
1204 assert((carry & 1) == carry);
1205 }
1206 for (; carry && i < m; ++i) {
1207 carry += x[i];
1208 x[i] = carry & PyLong_MASK;
1209 carry >>= PyLong_SHIFT;
1210 assert((carry & 1) == carry);
1211 }
1212 return carry;
1213 }
1214
1215 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1216 * is modified in place, by subtracting y from it. Borrows are propagated as
1217 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1218 */
1219 static digit
1220 v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
1221 {
1222 Py_ssize_t i;
1223 digit borrow = 0;
1224
1225 assert(m >= n);
1226 for (i = 0; i < n; ++i) {
1227 borrow = x[i] - y[i] - borrow;
1228 x[i] = borrow & PyLong_MASK;
1229 borrow >>= PyLong_SHIFT;
1230 borrow &= 1; /* keep only 1 sign bit */
1231 }
1232 for (; borrow && i < m; ++i) {
1233 borrow = x[i] - borrow;
1234 x[i] = borrow & PyLong_MASK;
1235 borrow >>= PyLong_SHIFT;
1236 borrow &= 1;
1237 }
1238 return borrow;
1239 }
1240
1241 /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1242 * result in z[0:m], and return the d bits shifted out of the top.
1243 */
1244 static digit
1245 v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
1246 {
1247 Py_ssize_t i;
1248 digit carry = 0;
1249
1250 assert(0 <= d && d < PyLong_SHIFT);
1251 for (i=0; i < m; i++) {
1252 twodigits acc = (twodigits)a[i] << d | carry;
1253 z[i] = (digit)acc & PyLong_MASK;
1254 carry = (digit)(acc >> PyLong_SHIFT);
1255 }
1256 return carry;
1257 }
1258
1259 /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1260 * result in z[0:m], and return the d bits shifted out of the bottom.
1261 */
1262 static digit
1263 v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1264 {
1265 Py_ssize_t i;
1266 digit carry = 0;
1267 digit mask = ((digit)1 << d) - 1U;
1268
1269 assert(0 <= d && d < PyLong_SHIFT);
1270 for (i=m; i-- > 0;) {
1271 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1272 carry = (digit)acc & mask;
1273 z[i] = (digit)(acc >> d);
1274 }
1275 return carry;
1276 }
1277
1278 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1279 in pout, and returning the remainder. pin and pout point at the LSD.
1280 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1281 _PyLong_Format, but that should be done with great care since longs are
1282 immutable. */
1283
1284 static digit
1285 inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
1286 {
1287 twodigits rem = 0;
1288
1289 assert(n > 0 && n <= PyLong_MASK);
1290 pin += size;
1291 pout += size;
1292 while (--size >= 0) {
1293 digit hi;
1294 rem = (rem << PyLong_SHIFT) | *--pin;
1295 *--pout = hi = (digit)(rem / n);
1296 rem -= (twodigits)hi * n;
1297 }
1298 return (digit)rem;
1299 }
1300
1301 /* Divide a long integer by a digit, returning both the quotient
1302 (as function result) and the remainder (through *prem).
1303 The sign of a is ignored; n should not be zero. */
1304
1305 static PyLongObject *
1306 divrem1(PyLongObject *a, digit n, digit *prem)
1307 {
1308 const Py_ssize_t size = ABS(Py_SIZE(a));
1309 PyLongObject *z;
1310
1311 assert(n > 0 && n <= PyLong_MASK);
1312 z = _PyLong_New(size);
1313 if (z == NULL)
1314 return NULL;
1315 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1316 return long_normalize(z);
1317 }
1318
1319 /* Convert a long integer to a base 10 string. Returns a new non-shared
1320 string. (Return value is non-shared so that callers can modify the
1321 returned value if necessary.) */
1322
1323 static PyObject *
1324 long_to_decimal_string(PyObject *aa, int addL)
1325 {
1326 PyLongObject *scratch, *a;
1327 PyObject *str;
1328 Py_ssize_t size, strlen, size_a, i, j;
1329 digit *pout, *pin, rem, tenpow;
1330 char *p;
1331 int negative;
1332
1333 a = (PyLongObject *)aa;
1334 if (a == NULL || !PyLong_Check(a)) {
1335 PyErr_BadInternalCall();
1336 return NULL;
1337 }
1338 size_a = ABS(Py_SIZE(a));
1339 negative = Py_SIZE(a) < 0;
1340
1341 /* quick and dirty upper bound for the number of digits
1342 required to express a in base _PyLong_DECIMAL_BASE:
1343
1344 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1345
1346 But log2(a) < size_a * PyLong_SHIFT, and
1347 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1348 > 3 * _PyLong_DECIMAL_SHIFT
1349 */
1350 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1351 PyErr_SetString(PyExc_OverflowError,
1352 "long is too large to format");
1353 return NULL;
1354 }
1355 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1356 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1357 scratch = _PyLong_New(size);
1358 if (scratch == NULL)
1359 return NULL;
1360
1361 /* convert array of base _PyLong_BASE digits in pin to an array of
1362 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1363 Volume 2 (3rd edn), section 4.4, Method 1b). */
1364 pin = a->ob_digit;
1365 pout = scratch->ob_digit;
1366 size = 0;
1367 for (i = size_a; --i >= 0; ) {
1368 digit hi = pin[i];
1369 for (j = 0; j < size; j++) {
1370 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1371 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1372 pout[j] = (digit)(z - (twodigits)hi *
1373 _PyLong_DECIMAL_BASE);
1374 }
1375 while (hi) {
1376 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1377 hi /= _PyLong_DECIMAL_BASE;
1378 }
1379 /* check for keyboard interrupt */
1380 SIGCHECK({
1381 Py_DECREF(scratch);
1382 return NULL;
1383 });
1384 }
1385 /* pout should have at least one digit, so that the case when a = 0
1386 works correctly */
1387 if (size == 0)
1388 pout[size++] = 0;
1389
1390 /* calculate exact length of output string, and allocate */
1391 strlen = (addL != 0) + negative +
1392 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1393 tenpow = 10;
1394 rem = pout[size-1];
1395 while (rem >= tenpow) {
1396 tenpow *= 10;
1397 strlen++;
1398 }
1399 str = PyString_FromStringAndSize(NULL, strlen);
1400 if (str == NULL) {
1401 Py_DECREF(scratch);
1402 return NULL;
1403 }
1404
1405 /* fill the string right-to-left */
1406 p = PyString_AS_STRING(str) + strlen;
1407 *p = '\0';
1408 if (addL)
1409 *--p = 'L';
1410 /* pout[0] through pout[size-2] contribute exactly
1411 _PyLong_DECIMAL_SHIFT digits each */
1412 for (i=0; i < size - 1; i++) {
1413 rem = pout[i];
1414 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1415 *--p = '0' + rem % 10;
1416 rem /= 10;
1417 }
1418 }
1419 /* pout[size-1]: always produce at least one decimal digit */
1420 rem = pout[i];
1421 do {
1422 *--p = '0' + rem % 10;
1423 rem /= 10;
1424 } while (rem != 0);
1425
1426 /* and sign */
1427 if (negative)
1428 *--p = '-';
1429
1430 /* check we've counted correctly */
1431 assert(p == PyString_AS_STRING(str));
1432 Py_DECREF(scratch);
1433 return (PyObject *)str;
1434 }
1435
1436 /* Convert the long to a string object with given base,
1437 appending a base prefix of 0[box] if base is 2, 8 or 16.
1438 Add a trailing "L" if addL is non-zero.
1439 If newstyle is zero, then use the pre-2.6 behavior of octal having
1440 a leading "0", instead of the prefix "0o" */
1441 PyAPI_FUNC(PyObject *)
1442 _PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
1443 {
1444 register PyLongObject *a = (PyLongObject *)aa;
1445 PyStringObject *str;
1446 Py_ssize_t i, sz;
1447 Py_ssize_t size_a;
1448 char *p;
1449 int bits;
1450 char sign = '\0';
1451
1452 if (base == 10)
1453 return long_to_decimal_string((PyObject *)a, addL);
1454
1455 if (a == NULL || !PyLong_Check(a)) {
1456 PyErr_BadInternalCall();
1457 return NULL;
1458 }
1459 assert(base >= 2 && base <= 36);
1460 size_a = ABS(Py_SIZE(a));
1461
1462 /* Compute a rough upper bound for the length of the string */
1463 i = base;
1464 bits = 0;
1465 while (i > 1) {
1466 ++bits;
1467 i >>= 1;
1468 }
1469 i = 5 + (addL ? 1 : 0);
1470 /* ensure we don't get signed overflow in sz calculation */
1471 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
1472 PyErr_SetString(PyExc_OverflowError,
1473 "long is too large to format");
1474 return NULL;
1475 }
1476 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
1477 assert(sz >= 0);
1478 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
1479 if (str == NULL)
1480 return NULL;
1481 p = PyString_AS_STRING(str) + sz;
1482 *p = '\0';
1483 if (addL)
1484 *--p = 'L';
1485 if (a->ob_size < 0)
1486 sign = '-';
1487
1488 if (a->ob_size == 0) {
1489 *--p = '0';
1490 }
1491 else if ((base & (base - 1)) == 0) {
1492 /* JRH: special case for power-of-2 bases */
1493 twodigits accum = 0;
1494 int accumbits = 0; /* # of bits in accum */
1495 int basebits = 1; /* # of bits in base-1 */
1496 i = base;
1497 while ((i >>= 1) > 1)
1498 ++basebits;
1499
1500 for (i = 0; i < size_a; ++i) {
1501 accum |= (twodigits)a->ob_digit[i] << accumbits;
1502 accumbits += PyLong_SHIFT;
1503 assert(accumbits >= basebits);
1504 do {
1505 char cdigit = (char)(accum & (base - 1));
1506 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1507 assert(p > PyString_AS_STRING(str));
1508 *--p = cdigit;
1509 accumbits -= basebits;
1510 accum >>= basebits;
1511 } while (i < size_a-1 ? accumbits >= basebits : accum > 0);
1512 }
1513 }
1514 else {
1515 /* Not 0, and base not a power of 2. Divide repeatedly by
1516 base, but for speed use the highest power of base that
1517 fits in a digit. */
1518 Py_ssize_t size = size_a;
1519 digit *pin = a->ob_digit;
1520 PyLongObject *scratch;
1521 /* powbasw <- largest power of base that fits in a digit. */
1522 digit powbase = base; /* powbase == base ** power */
1523 int power = 1;
1524 for (;;) {
1525 twodigits newpow = powbase * (twodigits)base;
1526 if (newpow >> PyLong_SHIFT)
1527 /* doesn't fit in a digit */
1528 break;
1529 powbase = (digit)newpow;
1530 ++power;
1531 }
1532
1533 /* Get a scratch area for repeated division. */
1534 scratch = _PyLong_New(size);
1535 if (scratch == NULL) {
1536 Py_DECREF(str);
1537 return NULL;
1538 }
1539
1540 /* Repeatedly divide by powbase. */
1541 do {
1542 int ntostore = power;
1543 digit rem = inplace_divrem1(scratch->ob_digit,
1544 pin, size, powbase);
1545 pin = scratch->ob_digit; /* no need to use a again */
1546 if (pin[size - 1] == 0)
1547 --size;
1548 SIGCHECK({
1549 Py_DECREF(scratch);
1550 Py_DECREF(str);
1551 return NULL;
1552 });
1553
1554 /* Break rem into digits. */
1555 assert(ntostore > 0);
1556 do {
1557 digit nextrem = (digit)(rem / base);
1558 char c = (char)(rem - nextrem * base);
1559 assert(p > PyString_AS_STRING(str));
1560 c += (c < 10) ? '0' : 'a'-10;
1561 *--p = c;
1562 rem = nextrem;
1563 --ntostore;
1564 /* Termination is a bit delicate: must not
1565 store leading zeroes, so must get out if
1566 remaining quotient and rem are both 0. */
1567 } while (ntostore && (size || rem));
1568 } while (size != 0);
1569 Py_DECREF(scratch);
1570 }
1571
1572 if (base == 2) {
1573 *--p = 'b';
1574 *--p = '0';
1575 }
1576 else if (base == 8) {
1577 if (newstyle) {
1578 *--p = 'o';
1579 *--p = '0';
1580 }
1581 else
1582 if (size_a != 0)
1583 *--p = '0';
1584 }
1585 else if (base == 16) {
1586 *--p = 'x';
1587 *--p = '0';
1588 }
1589 else if (base != 10) {
1590 *--p = '#';
1591 *--p = '0' + base%10;
1592 if (base > 10)
1593 *--p = '0' + base/10;
1594 }
1595 if (sign)
1596 *--p = sign;
1597 if (p != PyString_AS_STRING(str)) {
1598 char *q = PyString_AS_STRING(str);
1599 assert(p > q);
1600 do {
1601 } while ((*q++ = *p++) != '\0');
1602 q--;
1603 _PyString_Resize((PyObject **)&str,
1604 (Py_ssize_t) (q - PyString_AS_STRING(str)));
1605 }
1606 return (PyObject *)str;
1607 }
1608
1609 /* Table of digit values for 8-bit string -> integer conversion.
1610 * '0' maps to 0, ..., '9' maps to 9.
1611 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1612 * All other indices map to 37.
1613 * Note that when converting a base B string, a char c is a legitimate
1614 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1615 */
1616 int _PyLong_DigitValue[256] = {
1617 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1618 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1619 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1620 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1621 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1622 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1623 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1624 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1625 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1626 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1627 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1628 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1629 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1630 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1631 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1632 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1633 };
1634
1635 /* *str points to the first digit in a string of base `base` digits. base
1636 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1637 * non-digit (which may be *str!). A normalized long is returned.
1638 * The point to this routine is that it takes time linear in the number of
1639 * string characters.
1640 */
1641 static PyLongObject *
1642 long_from_binary_base(char **str, int base)
1643 {
1644 char *p = *str;
1645 char *start = p;
1646 int bits_per_char;
1647 Py_ssize_t n;
1648 PyLongObject *z;
1649 twodigits accum;
1650 int bits_in_accum;
1651 digit *pdigit;
1652
1653 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1654 n = base;
1655 for (bits_per_char = -1; n; ++bits_per_char)
1656 n >>= 1;
1657 /* n <- total # of bits needed, while setting p to end-of-string */
1658 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1659 ++p;
1660 *str = p;
1661 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1662 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1663 if (n / bits_per_char < p - start) {
1664 PyErr_SetString(PyExc_ValueError,
1665 "long string too large to convert");
1666 return NULL;
1667 }
1668 n = n / PyLong_SHIFT;
1669 z = _PyLong_New(n);
1670 if (z == NULL)
1671 return NULL;
1672 /* Read string from right, and fill in long from left; i.e.,
1673 * from least to most significant in both.
1674 */
1675 accum = 0;
1676 bits_in_accum = 0;
1677 pdigit = z->ob_digit;
1678 while (--p >= start) {
1679 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
1680 assert(k >= 0 && k < base);
1681 accum |= (twodigits)k << bits_in_accum;
1682 bits_in_accum += bits_per_char;
1683 if (bits_in_accum >= PyLong_SHIFT) {
1684 *pdigit++ = (digit)(accum & PyLong_MASK);
1685 assert(pdigit - z->ob_digit <= n);
1686 accum >>= PyLong_SHIFT;
1687 bits_in_accum -= PyLong_SHIFT;
1688 assert(bits_in_accum < PyLong_SHIFT);
1689 }
1690 }
1691 if (bits_in_accum) {
1692 assert(bits_in_accum <= PyLong_SHIFT);
1693 *pdigit++ = (digit)accum;
1694 assert(pdigit - z->ob_digit <= n);
1695 }
1696 while (pdigit - z->ob_digit < n)
1697 *pdigit++ = 0;
1698 return long_normalize(z);
1699 }
1700
1701 PyObject *
1702 PyLong_FromString(char *str, char **pend, int base)
1703 {
1704 int sign = 1;
1705 char *start, *orig_str = str;
1706 PyLongObject *z;
1707 PyObject *strobj, *strrepr;
1708 Py_ssize_t slen;
1709
1710 if ((base != 0 && base < 2) || base > 36) {
1711 PyErr_SetString(PyExc_ValueError,
1712 "long() arg 2 must be >= 2 and <= 36");
1713 return NULL;
1714 }
1715 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1716 str++;
1717 if (*str == '+')
1718 ++str;
1719 else if (*str == '-') {
1720 ++str;
1721 sign = -1;
1722 }
1723 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1724 str++;
1725 if (base == 0) {
1726 /* No base given. Deduce the base from the contents
1727 of the string */
1728 if (str[0] != '0')
1729 base = 10;
1730 else if (str[1] == 'x' || str[1] == 'X')
1731 base = 16;
1732 else if (str[1] == 'o' || str[1] == 'O')
1733 base = 8;
1734 else if (str[1] == 'b' || str[1] == 'B')
1735 base = 2;
1736 else
1737 /* "old" (C-style) octal literal, still valid in
1738 2.x, although illegal in 3.x */
1739 base = 8;
1740 }
1741 /* Whether or not we were deducing the base, skip leading chars
1742 as needed */
1743 if (str[0] == '0' &&
1744 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1745 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1746 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1747 str += 2;
1748
1749 start = str;
1750 if ((base & (base - 1)) == 0)
1751 z = long_from_binary_base(&str, base);
1752 else {
1753 /***
1754 Binary bases can be converted in time linear in the number of digits, because
1755 Python's representation base is binary. Other bases (including decimal!) use
1756 the simple quadratic-time algorithm below, complicated by some speed tricks.
1757
1758 First some math: the largest integer that can be expressed in N base-B digits
1759 is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1760 case number of Python digits needed to hold it is the smallest integer n s.t.
1761
1762 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1763 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1764 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
1765
1766 The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so
1767 we can compute this quickly. A Python long with that much space is reserved
1768 near the start, and the result is computed into it.
1769
1770 The input string is actually treated as being in base base**i (i.e., i digits
1771 are processed at a time), where two more static arrays hold:
1772
1773 convwidth_base[base] = the largest integer i such that
1774 base**i <= PyLong_BASE
1775 convmultmax_base[base] = base ** convwidth_base[base]
1776
1777 The first of these is the largest i such that i consecutive input digits
1778 must fit in a single Python digit. The second is effectively the input
1779 base we're really using.
1780
1781 Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1782 convmultmax_base[base], the result is "simply"
1783
1784 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1785
1786 where B = convmultmax_base[base].
1787
1788 Error analysis: as above, the number of Python digits `n` needed is worst-
1789 case
1790
1791 n >= N * log(B)/log(PyLong_BASE)
1792
1793 where `N` is the number of input digits in base `B`. This is computed via
1794
1795 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1796
1797 below. Two numeric concerns are how much space this can waste, and whether
1798 the computed result can be too small. To be concrete, assume PyLong_BASE =
1799 2**15, which is the default (and it's unlikely anyone changes that).
1800
1801 Waste isn't a problem: provided the first input digit isn't 0, the difference
1802 between the worst-case input with N digits and the smallest input with N
1803 digits is about a factor of B, but B is small compared to PyLong_BASE so at
1804 most one allocated Python digit can remain unused on that count. If
1805 N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating
1806 that and adding 1 returns a result 1 larger than necessary. However, that
1807 can't happen: whenever B is a power of 2, long_from_binary_base() is called
1808 instead, and it's impossible for B**i to be an integer power of 2**15 when B
1809 is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
1810 an exact integer when B is not a power of 2, since B**i has a prime factor
1811 other than 2 in that case, but (2**15)**j's only prime factor is 2).
1812
1813 The computed result can be too small if the true value of
1814 N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but
1815 due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient,
1816 and/or multiplying that by N) yields a numeric result a little less than that
1817 integer. Unfortunately, "how close can a transcendental function get to an
1818 integer over some range?" questions are generally theoretically intractable.
1819 Computer analysis via continued fractions is practical: expand
1820 log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the
1821 best" rational approximations. Then j*log(B)/log(PyLong_BASE) is
1822 approximately equal to (the integer) i. This shows that we can get very close
1823 to being in trouble, but very rarely. For example, 76573 is a denominator in
1824 one of the continued-fraction approximations to log(10)/log(2**15), and
1825 indeed:
1826
1827 >>> log(10)/log(2**15)*76573
1828 16958.000000654003
1829
1830 is very close to an integer. If we were working with IEEE single-precision,
1831 rounding errors could kill us. Finding worst cases in IEEE double-precision
1832 requires better-than-double-precision log() functions, and Tim didn't bother.
1833 Instead the code checks to see whether the allocated space is enough as each
1834 new Python digit is added, and copies the whole thing to a larger long if not.
1835 This should happen extremely rarely, and in fact I don't have a test case
1836 that triggers it(!). Instead the code was tested by artificially allocating
1837 just 1 digit at the start, so that the copying code was exercised for every
1838 digit beyond the first.
1839 ***/
1840 register twodigits c; /* current input character */
1841 Py_ssize_t size_z;
1842 int i;
1843 int convwidth;
1844 twodigits convmultmax, convmult;
1845 digit *pz, *pzstop;
1846 char* scan;
1847
1848 static double log_base_PyLong_BASE[37] = {0.0e0,};
1849 static int convwidth_base[37] = {0,};
1850 static twodigits convmultmax_base[37] = {0,};
1851
1852 if (log_base_PyLong_BASE[base] == 0.0) {
1853 twodigits convmax = base;
1854 int i = 1;
1855
1856 log_base_PyLong_BASE[base] = (log((double)base) /
1857 log((double)PyLong_BASE));
1858 for (;;) {
1859 twodigits next = convmax * base;
1860 if (next > PyLong_BASE)
1861 break;
1862 convmax = next;
1863 ++i;
1864 }
1865 convmultmax_base[base] = convmax;
1866 assert(i > 0);
1867 convwidth_base[base] = i;
1868 }
1869
1870 /* Find length of the string of numeric characters. */
1871 scan = str;
1872 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
1873 ++scan;
1874
1875 /* Create a long object that can contain the largest possible
1876 * integer with this base and length. Note that there's no
1877 * need to initialize z->ob_digit -- no slot is read up before
1878 * being stored into.
1879 */
1880 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1881 /* Uncomment next line to test exceedingly rare copy code */
1882 /* size_z = 1; */
1883 assert(size_z > 0);
1884 z = _PyLong_New(size_z);
1885 if (z == NULL)
1886 return NULL;
1887 Py_SIZE(z) = 0;
1888
1889 /* `convwidth` consecutive input digits are treated as a single
1890 * digit in base `convmultmax`.
1891 */
1892 convwidth = convwidth_base[base];
1893 convmultmax = convmultmax_base[base];
1894
1895 /* Work ;-) */
1896 while (str < scan) {
1897 /* grab up to convwidth digits from the input string */
1898 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
1899 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1900 c = (twodigits)(c * base +
1901 _PyLong_DigitValue[Py_CHARMASK(*str)]);
1902 assert(c < PyLong_BASE);
1903 }
1904
1905 convmult = convmultmax;
1906 /* Calculate the shift only if we couldn't get
1907 * convwidth digits.
1908 */
1909 if (i != convwidth) {
1910 convmult = base;
1911 for ( ; i > 1; --i)
1912 convmult *= base;
1913 }
1914
1915 /* Multiply z by convmult, and add c. */
1916 pz = z->ob_digit;
1917 pzstop = pz + Py_SIZE(z);
1918 for (; pz < pzstop; ++pz) {
1919 c += (twodigits)*pz * convmult;
1920 *pz = (digit)(c & PyLong_MASK);
1921 c >>= PyLong_SHIFT;
1922 }
1923 /* carry off the current end? */
1924 if (c) {
1925 assert(c < PyLong_BASE);
1926 if (Py_SIZE(z) < size_z) {
1927 *pz = (digit)c;
1928 ++Py_SIZE(z);
1929 }
1930 else {
1931 PyLongObject *tmp;
1932 /* Extremely rare. Get more space. */
1933 assert(Py_SIZE(z) == size_z);
1934 tmp = _PyLong_New(size_z + 1);
1935 if (tmp == NULL) {
1936 Py_DECREF(z);
1937 return NULL;
1938 }
1939 memcpy(tmp->ob_digit,
1940 z->ob_digit,
1941 sizeof(digit) * size_z);
1942 Py_DECREF(z);
1943 z = tmp;
1944 z->ob_digit[size_z] = (digit)c;
1945 ++size_z;
1946 }
1947 }
1948 }
1949 }
1950 if (z == NULL)
1951 return NULL;
1952 if (str == start)
1953 goto onError;
1954 if (sign < 0)
1955 Py_SIZE(z) = -(Py_SIZE(z));
1956 if (*str == 'L' || *str == 'l')
1957 str++;
1958 while (*str && isspace(Py_CHARMASK(*str)))
1959 str++;
1960 if (*str != '\0')
1961 goto onError;
1962 if (pend)
1963 *pend = str;
1964 return (PyObject *) z;
1965
1966 onError:
1967 Py_XDECREF(z);
1968 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
1969 strobj = PyString_FromStringAndSize(orig_str, slen);
1970 if (strobj == NULL)
1971 return NULL;
1972 strrepr = PyObject_Repr(strobj);
1973 Py_DECREF(strobj);
1974 if (strrepr == NULL)
1975 return NULL;
1976 PyErr_Format(PyExc_ValueError,
1977 "invalid literal for long() with base %d: %s",
1978 base, PyString_AS_STRING(strrepr));
1979 Py_DECREF(strrepr);
1980 return NULL;
1981 }
1982
1983 #ifdef Py_USING_UNICODE
1984 PyObject *
1985 PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
1986 {
1987 PyObject *result;
1988 char *buffer = (char *)PyMem_MALLOC(length+1);
1989
1990 if (buffer == NULL)
1991 return NULL;
1992
1993 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1994 PyMem_FREE(buffer);
1995 return NULL;
1996 }
1997 result = PyLong_FromString(buffer, NULL, base);
1998 PyMem_FREE(buffer);
1999 return result;
2000 }
2001 #endif
2002
2003 /* forward */
2004 static PyLongObject *x_divrem
2005 (PyLongObject *, PyLongObject *, PyLongObject **);
2006 static PyObject *long_long(PyObject *v);
2007
2008 /* Long division with remainder, top-level routine */
2009
2010 static int
2011 long_divrem(PyLongObject *a, PyLongObject *b,
2012 PyLongObject **pdiv, PyLongObject **prem)
2013 {
2014 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2015 PyLongObject *z;
2016
2017 if (size_b == 0) {
2018 PyErr_SetString(PyExc_ZeroDivisionError,
2019 "long division or modulo by zero");
2020 return -1;
2021 }
2022 if (size_a < size_b ||
2023 (size_a == size_b &&
2024 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2025 /* |a| < |b|. */
2026 *pdiv = _PyLong_New(0);
2027 if (*pdiv == NULL)
2028 return -1;
2029 Py_INCREF(a);
2030 *prem = (PyLongObject *) a;
2031 return 0;
2032 }
2033 if (size_b == 1) {
2034 digit rem = 0;
2035 z = divrem1(a, b->ob_digit[0], &rem);
2036 if (z == NULL)
2037 return -1;
2038 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2039 if (*prem == NULL) {
2040 Py_DECREF(z);
2041 return -1;
2042 }
2043 }
2044 else {
2045 z = x_divrem(a, b, prem);
2046 if (z == NULL)
2047 return -1;
2048 }
2049 /* Set the signs.
2050 The quotient z has the sign of a*b;
2051 the remainder r has the sign of a,
2052 so a = b*z + r. */
2053 if ((a->ob_size < 0) != (b->ob_size < 0))
2054 z->ob_size = -(z->ob_size);
2055 if (a->ob_size < 0 && (*prem)->ob_size != 0)
2056 (*prem)->ob_size = -((*prem)->ob_size);
2057 *pdiv = z;
2058 return 0;
2059 }
2060
2061 /* Unsigned long division with remainder -- the algorithm. The arguments v1
2062 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
2063
2064 static PyLongObject *
2065 x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
2066 {
2067 PyLongObject *v, *w, *a;
2068 Py_ssize_t i, k, size_v, size_w;
2069 int d;
2070 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2071 twodigits vv;
2072 sdigit zhi;
2073 stwodigits z;
2074
2075 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2076 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2077 handle the special case when the initial estimate q for a quotient
2078 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2079 that won't overflow a digit. */
2080
2081 /* allocate space; w will also be used to hold the final remainder */
2082 size_v = ABS(Py_SIZE(v1));
2083 size_w = ABS(Py_SIZE(w1));
2084 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2085 v = _PyLong_New(size_v+1);
2086 if (v == NULL) {
2087 *prem = NULL;
2088 return NULL;
2089 }
2090 w = _PyLong_New(size_w);
2091 if (w == NULL) {
2092 Py_DECREF(v);
2093 *prem = NULL;
2094 return NULL;
2095 }
2096
2097 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2098 shift v1 left by the same amount. Results go into w and v. */
2099 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2100 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2101 assert(carry == 0);
2102 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2103 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2104 v->ob_digit[size_v] = carry;
2105 size_v++;
2106 }
2107
2108 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2109 at most (and usually exactly) k = size_v - size_w digits. */
2110 k = size_v - size_w;
2111 assert(k >= 0);
2112 a = _PyLong_New(k);
2113 if (a == NULL) {
2114 Py_DECREF(w);
2115 Py_DECREF(v);
2116 *prem = NULL;
2117 return NULL;
2118 }
2119 v0 = v->ob_digit;
2120 w0 = w->ob_digit;
2121 wm1 = w0[size_w-1];
2122 wm2 = w0[size_w-2];
2123 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2124 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2125 single-digit quotient q, remainder in vk[0:size_w]. */
2126
2127 SIGCHECK({
2128 Py_DECREF(a);
2129 Py_DECREF(w);
2130 Py_DECREF(v);
2131 *prem = NULL;
2132 return NULL;
2133 });
2134
2135 /* estimate quotient digit q; may overestimate by 1 (rare) */
2136 vtop = vk[size_w];
2137 assert(vtop <= wm1);
2138 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2139 q = (digit)(vv / wm1);
2140 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2141 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2142 | vk[size_w-2])) {
2143 --q;
2144 r += wm1;
2145 if (r >= PyLong_BASE)
2146 break;
2147 }
2148 assert(q <= PyLong_BASE);
2149
2150 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2151 zhi = 0;
2152 for (i = 0; i < size_w; ++i) {
2153 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2154 -PyLong_BASE * q <= z < PyLong_BASE */
2155 z = (sdigit)vk[i] + zhi -
2156 (stwodigits)q * (stwodigits)w0[i];
2157 vk[i] = (digit)z & PyLong_MASK;
2158 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2159 z, PyLong_SHIFT);
2160 }
2161
2162 /* add w back if q was too large (this branch taken rarely) */
2163 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2164 if ((sdigit)vtop + zhi < 0) {
2165 carry = 0;
2166 for (i = 0; i < size_w; ++i) {
2167 carry += vk[i] + w0[i];
2168 vk[i] = carry & PyLong_MASK;
2169 carry >>= PyLong_SHIFT;
2170 }
2171 --q;
2172 }
2173
2174 /* store quotient digit */
2175 assert(q < PyLong_BASE);
2176 *--ak = q;
2177 }
2178
2179 /* unshift remainder; we reuse w to store the result */
2180 carry = v_rshift(w0, v0, size_w, d);
2181 assert(carry==0);
2182 Py_DECREF(v);
2183
2184 *prem = long_normalize(w);
2185 return long_normalize(a);
2186 }
2187
2188 /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2189 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2190 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2191 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2192 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2193 -1.0. */
2194
2195 /* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2196 #if DBL_MANT_DIG == 53
2197 #define EXP2_DBL_MANT_DIG 9007199254740992.0
2198 #else
2199 #define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2200 #endif
2201
2202 double
2203 _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2204 {
2205 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2206 /* See below for why x_digits is always large enough. */
2207 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2208 double dx;
2209 /* Correction term for round-half-to-even rounding. For a digit x,
2210 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2211 multiple of 4, rounding ties to a multiple of 8. */
2212 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2213
2214 a_size = ABS(Py_SIZE(a));
2215 if (a_size == 0) {
2216 /* Special case for 0: significand 0.0, exponent 0. */
2217 *e = 0;
2218 return 0.0;
2219 }
2220 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2221 /* The following is an overflow-free version of the check
2222 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2223 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2224 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2225 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2226 goto overflow;
2227 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2228
2229 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2230 (shifting left if a_bits <= DBL_MANT_DIG + 2).
2231
2232 Number of digits needed for result: write // for floor division.
2233 Then if shifting left, we end up using
2234
2235 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2236
2237 digits. If shifting right, we use
2238
2239 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2240
2241 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2242 the inequalities
2243
2244 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2245 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2246 1 + (m - n - 1) // PyLong_SHIFT,
2247
2248 valid for any integers m and n, we find that x_size satisfies
2249
2250 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2251
2252 in both cases.
2253 */
2254 if (a_bits <= DBL_MANT_DIG + 2) {
2255 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2256 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2257 x_size = 0;
2258 while (x_size < shift_digits)
2259 x_digits[x_size++] = 0;
2260 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2261 (int)shift_bits);
2262 x_size += a_size;
2263 x_digits[x_size++] = rem;
2264 }
2265 else {
2266 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2267 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2268 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2269 a_size - shift_digits, (int)shift_bits);
2270 x_size = a_size - shift_digits;
2271 /* For correct rounding below, we need the least significant
2272 bit of x to be 'sticky' for this shift: if any of the bits
2273 shifted out was nonzero, we set the least significant bit
2274 of x. */
2275 if (rem)
2276 x_digits[0] |= 1;
2277 else
2278 while (shift_digits > 0)
2279 if (a->ob_digit[--shift_digits]) {
2280 x_digits[0] |= 1;
2281 break;
2282 }
2283 }
2284 assert(1 <= x_size &&
2285 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
2286
2287 /* Round, and convert to double. */
2288 x_digits[0] += half_even_correction[x_digits[0] & 7];
2289 dx = x_digits[--x_size];
2290 while (x_size > 0)
2291 dx = dx * PyLong_BASE + x_digits[--x_size];
2292
2293 /* Rescale; make correction if result is 1.0. */
2294 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2295 if (dx == 1.0) {
2296 if (a_bits == PY_SSIZE_T_MAX)
2297 goto overflow;
2298 dx = 0.5;
2299 a_bits += 1;
2300 }
2301
2302 *e = a_bits;
2303 return Py_SIZE(a) < 0 ? -dx : dx;
2304
2305 overflow:
2306 /* exponent > PY_SSIZE_T_MAX */
2307 PyErr_SetString(PyExc_OverflowError,
2308 "huge integer: number of bits overflows a Py_ssize_t");
2309 *e = 0;
2310 return -1.0;
2311 }
2312
2313 /* Get a C double from a long int object. Rounds to the nearest double,
2314 using the round-half-to-even rule in the case of a tie. */
2315
2316 double
2317 PyLong_AsDouble(PyObject *v)
2318 {
2319 Py_ssize_t exponent;
2320 double x;
2321
2322 if (v == NULL || !PyLong_Check(v)) {
2323 PyErr_BadInternalCall();
2324 return -1.0;
2325 }
2326 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2327 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2328 PyErr_SetString(PyExc_OverflowError,
2329 "long int too large to convert to float");
2330 return -1.0;
2331 }
2332 return ldexp(x, (int)exponent);
2333 }
2334
2335 /* Methods */
2336
2337 static void
2338 long_dealloc(PyObject *v)
2339 {
2340 Py_TYPE(v)->tp_free(v);
2341 }
2342
2343 static PyObject *
2344 long_repr(PyObject *v)
2345 {
2346 return _PyLong_Format(v, 10, 1, 0);
2347 }
2348
2349 static PyObject *
2350 long_str(PyObject *v)
2351 {
2352 return _PyLong_Format(v, 10, 0, 0);
2353 }
2354
2355 static int
2356 long_compare(PyLongObject *a, PyLongObject *b)
2357 {
2358 Py_ssize_t sign;
2359
2360 if (Py_SIZE(a) != Py_SIZE(b)) {
2361 sign = Py_SIZE(a) - Py_SIZE(b);
2362 }
2363 else {
2364 Py_ssize_t i = ABS(Py_SIZE(a));
2365 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2366 ;
2367 if (i < 0)
2368 sign = 0;
2369 else {
2370 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2371 if (Py_SIZE(a) < 0)
2372 sign = -sign;
2373 }
2374 }
2375 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
2376 }
2377
2378 static long
2379 long_hash(PyLongObject *v)
2380 {
2381 unsigned long x;
2382 Py_ssize_t i;
2383 int sign;
2384
2385 /* This is designed so that Python ints and longs with the
2386 same value hash to the same value, otherwise comparisons
2387 of mapping keys will turn out weird */
2388 i = v->ob_size;
2389 sign = 1;
2390 x = 0;
2391 if (i < 0) {
2392 sign = -1;
2393 i = -(i);
2394 }
2395 /* The following loop produces a C unsigned long x such that x is
2396 congruent to the absolute value of v modulo ULONG_MAX. The
2397 resulting x is nonzero if and only if v is. */
2398 while (--i >= 0) {
2399 /* Force a native long #-bits (32 or 64) circular shift */
2400 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
2401 x += v->ob_digit[i];
2402 /* If the addition above overflowed we compensate by
2403 incrementing. This preserves the value modulo
2404 ULONG_MAX. */
2405 if (x < v->ob_digit[i])
2406 x++;
2407 }
2408 x = x * sign;
2409 if (x == (unsigned long)-1)
2410 x = (unsigned long)-2;
2411 return (long)x;
2412 }
2413
2414
2415 /* Add the absolute values of two long integers. */
2416
2417 static PyLongObject *
2418 x_add(PyLongObject *a, PyLongObject *b)
2419 {
2420 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2421 PyLongObject *z;
2422 Py_ssize_t i;
2423 digit carry = 0;
2424
2425 /* Ensure a is the larger of the two: */
2426 if (size_a < size_b) {
2427 { PyLongObject *temp = a; a = b; b = temp; }
2428 { Py_ssize_t size_temp = size_a;
2429 size_a = size_b;
2430 size_b = size_temp; }
2431 }
2432 z = _PyLong_New(size_a+1);
2433 if (z == NULL)
2434 return NULL;
2435 for (i = 0; i < size_b; ++i) {
2436 carry += a->ob_digit[i] + b->ob_digit[i];
2437 z->ob_digit[i] = carry & PyLong_MASK;
2438 carry >>= PyLong_SHIFT;
2439 }
2440 for (; i < size_a; ++i) {
2441 carry += a->ob_digit[i];
2442 z->ob_digit[i] = carry & PyLong_MASK;
2443 carry >>= PyLong_SHIFT;
2444 }
2445 z->ob_digit[i] = carry;
2446 return long_normalize(z);
2447 }
2448
2449 /* Subtract the absolute values of two integers. */
2450
2451 static PyLongObject *
2452 x_sub(PyLongObject *a, PyLongObject *b)
2453 {
2454 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2455 PyLongObject *z;
2456 Py_ssize_t i;
2457 int sign = 1;
2458 digit borrow = 0;
2459
2460 /* Ensure a is the larger of the two: */
2461 if (size_a < size_b) {
2462 sign = -1;
2463 { PyLongObject *temp = a; a = b; b = temp; }
2464 { Py_ssize_t size_temp = size_a;
2465 size_a = size_b;
2466 size_b = size_temp; }
2467 }
2468 else if (size_a == size_b) {
2469 /* Find highest digit where a and b differ: */
2470 i = size_a;
2471 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2472 ;
2473 if (i < 0)
2474 return _PyLong_New(0);
2475 if (a->ob_digit[i] < b->ob_digit[i]) {
2476 sign = -1;
2477 { PyLongObject *temp = a; a = b; b = temp; }
2478 }
2479 size_a = size_b = i+1;
2480 }
2481 z = _PyLong_New(size_a);
2482 if (z == NULL)
2483 return NULL;
2484 for (i = 0; i < size_b; ++i) {
2485 /* The following assumes unsigned arithmetic
2486 works module 2**N for some N>PyLong_SHIFT. */
2487 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2488 z->ob_digit[i] = borrow & PyLong_MASK;
2489 borrow >>= PyLong_SHIFT;
2490 borrow &= 1; /* Keep only one sign bit */
2491 }
2492 for (; i < size_a; ++i) {
2493 borrow = a->ob_digit[i] - borrow;
2494 z->ob_digit[i] = borrow & PyLong_MASK;
2495 borrow >>= PyLong_SHIFT;
2496 borrow &= 1; /* Keep only one sign bit */
2497 }
2498 assert(borrow == 0);
2499 if (sign < 0)
2500 z->ob_size = -(z->ob_size);
2501 return long_normalize(z);
2502 }
2503
2504 static PyObject *
2505 long_add(PyLongObject *v, PyLongObject *w)
2506 {
2507 PyLongObject *a, *b, *z;
2508
2509 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2510
2511 if (a->ob_size < 0) {
2512 if (b->ob_size < 0) {
2513 z = x_add(a, b);
2514 if (z != NULL && z->ob_size != 0)
2515 z->ob_size = -(z->ob_size);
2516 }
2517 else
2518 z = x_sub(b, a);
2519 }
2520 else {
2521 if (b->ob_size < 0)
2522 z = x_sub(a, b);
2523 else
2524 z = x_add(a, b);
2525 }
2526 Py_DECREF(a);
2527 Py_DECREF(b);
2528 return (PyObject *)z;
2529 }
2530
2531 static PyObject *
2532 long_sub(PyLongObject *v, PyLongObject *w)
2533 {
2534 PyLongObject *a, *b, *z;
2535
2536 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2537
2538 if (a->ob_size < 0) {
2539 if (b->ob_size < 0)
2540 z = x_sub(a, b);
2541 else
2542 z = x_add(a, b);
2543 if (z != NULL && z->ob_size != 0)
2544 z->ob_size = -(z->ob_size);
2545 }
2546 else {
2547 if (b->ob_size < 0)
2548 z = x_add(a, b);
2549 else
2550 z = x_sub(a, b);
2551 }
2552 Py_DECREF(a);
2553 Py_DECREF(b);
2554 return (PyObject *)z;
2555 }
2556
2557 /* Grade school multiplication, ignoring the signs.
2558 * Returns the absolute value of the product, or NULL if error.
2559 */
2560 static PyLongObject *
2561 x_mul(PyLongObject *a, PyLongObject *b)
2562 {
2563 PyLongObject *z;
2564 Py_ssize_t size_a = ABS(Py_SIZE(a));
2565 Py_ssize_t size_b = ABS(Py_SIZE(b));
2566 Py_ssize_t i;
2567
2568 z = _PyLong_New(size_a + size_b);
2569 if (z == NULL)
2570 return NULL;
2571
2572 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2573 if (a == b) {
2574 /* Efficient squaring per HAC, Algorithm 14.16:
2575 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2576 * Gives slightly less than a 2x speedup when a == b,
2577 * via exploiting that each entry in the multiplication
2578 * pyramid appears twice (except for the size_a squares).
2579 */
2580 for (i = 0; i < size_a; ++i) {
2581 twodigits carry;
2582 twodigits f = a->ob_digit[i];
2583 digit *pz = z->ob_digit + (i << 1);
2584 digit *pa = a->ob_digit + i + 1;
2585 digit *paend = a->ob_digit + size_a;
2586
2587 SIGCHECK({
2588 Py_DECREF(z);
2589 return NULL;
2590 });
2591
2592 carry = *pz + f * f;
2593 *pz++ = (digit)(carry & PyLong_MASK);
2594 carry >>= PyLong_SHIFT;
2595 assert(carry <= PyLong_MASK);
2596
2597 /* Now f is added in twice in each column of the
2598 * pyramid it appears. Same as adding f<<1 once.
2599 */
2600 f <<= 1;
2601 while (pa < paend) {
2602 carry += *pz + *pa++ * f;
2603 *pz++ = (digit)(carry & PyLong_MASK);
2604 carry >>= PyLong_SHIFT;
2605 assert(carry <= (PyLong_MASK << 1));
2606 }
2607 if (carry) {
2608 carry += *pz;
2609 *pz++ = (digit)(carry & PyLong_MASK);
2610 carry >>= PyLong_SHIFT;
2611 }
2612 if (carry)
2613 *pz += (digit)(carry & PyLong_MASK);
2614 assert((carry >> PyLong_SHIFT) == 0);
2615 }
2616 }
2617 else { /* a is not the same as b -- gradeschool long mult */
2618 for (i = 0; i < size_a; ++i) {
2619 twodigits carry = 0;
2620 twodigits f = a->ob_digit[i];
2621 digit *pz = z->ob_digit + i;
2622 digit *pb = b->ob_digit;
2623 digit *pbend = b->ob_digit + size_b;
2624
2625 SIGCHECK({
2626 Py_DECREF(z);
2627 return NULL;
2628 });
2629
2630 while (pb < pbend) {
2631 carry += *pz + *pb++ * f;
2632 *pz++ = (digit)(carry & PyLong_MASK);
2633 carry >>= PyLong_SHIFT;
2634 assert(carry <= PyLong_MASK);
2635 }
2636 if (carry)
2637 *pz += (digit)(carry & PyLong_MASK);
2638 assert((carry >> PyLong_SHIFT) == 0);
2639 }
2640 }
2641 return long_normalize(z);
2642 }
2643
2644 /* A helper for Karatsuba multiplication (k_mul).
2645 Takes a long "n" and an integer "size" representing the place to
2646 split, and sets low and high such that abs(n) == (high << size) + low,
2647 viewing the shift as being by digits. The sign bit is ignored, and
2648 the return values are >= 0.
2649 Returns 0 on success, -1 on failure.
2650 */
2651 static int
2652 kmul_split(PyLongObject *n,
2653 Py_ssize_t size,
2654 PyLongObject **high,
2655 PyLongObject **low)
2656 {
2657 PyLongObject *hi, *lo;
2658 Py_ssize_t size_lo, size_hi;
2659 const Py_ssize_t size_n = ABS(Py_SIZE(n));
2660
2661 size_lo = MIN(size_n, size);
2662 size_hi = size_n - size_lo;
2663
2664 if ((hi = _PyLong_New(size_hi)) == NULL)
2665 return -1;
2666 if ((lo = _PyLong_New(size_lo)) == NULL) {
2667 Py_DECREF(hi);
2668 return -1;
2669 }
2670
2671 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2672 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2673
2674 *high = long_normalize(hi);
2675 *low = long_normalize(lo);
2676 return 0;
2677 }
2678
2679 static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2680
2681 /* Karatsuba multiplication. Ignores the input signs, and returns the
2682 * absolute value of the product (or NULL if error).
2683 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2684 */
2685 static PyLongObject *
2686 k_mul(PyLongObject *a, PyLongObject *b)
2687 {
2688 Py_ssize_t asize = ABS(Py_SIZE(a));
2689 Py_ssize_t bsize = ABS(Py_SIZE(b));
2690 PyLongObject *ah = NULL;
2691 PyLongObject *al = NULL;
2692 PyLongObject *bh = NULL;
2693 PyLongObject *bl = NULL;
2694 PyLongObject *ret = NULL;
2695 PyLongObject *t1, *t2, *t3;
2696 Py_ssize_t shift; /* the number of digits we split off */
2697 Py_ssize_t i;
2698
2699 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2700 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2701 * Then the original product is
2702 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2703 * By picking X to be a power of 2, "*X" is just shifting, and it's
2704 * been reduced to 3 multiplies on numbers half the size.
2705 */
2706
2707 /* We want to split based on the larger number; fiddle so that b
2708 * is largest.
2709 */
2710 if (asize > bsize) {
2711 t1 = a;
2712 a = b;
2713 b = t1;
2714
2715 i = asize;
2716 asize = bsize;
2717 bsize = i;
2718 }
2719
2720 /* Use gradeschool math when either number is too small. */
2721 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2722 if (asize <= i) {
2723 if (asize == 0)
2724 return _PyLong_New(0);
2725 else
2726 return x_mul(a, b);
2727 }
2728
2729 /* If a is small compared to b, splitting on b gives a degenerate
2730 * case with ah==0, and Karatsuba may be (even much) less efficient
2731 * than "grade school" then. However, we can still win, by viewing
2732 * b as a string of "big digits", each of width a->ob_size. That
2733 * leads to a sequence of balanced calls to k_mul.
2734 */
2735 if (2 * asize <= bsize)
2736 return k_lopsided_mul(a, b);
2737
2738 /* Split a & b into hi & lo pieces. */
2739 shift = bsize >> 1;
2740 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2741 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
2742
2743 if (a == b) {
2744 bh = ah;
2745 bl = al;
2746 Py_INCREF(bh);
2747 Py_INCREF(bl);
2748 }
2749 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
2750
2751 /* The plan:
2752 * 1. Allocate result space (asize + bsize digits: that's always
2753 * enough).
2754 * 2. Compute ah*bh, and copy into result at 2*shift.
2755 * 3. Compute al*bl, and copy into result at 0. Note that this
2756 * can't overlap with #2.
2757 * 4. Subtract al*bl from the result, starting at shift. This may
2758 * underflow (borrow out of the high digit), but we don't care:
2759 * we're effectively doing unsigned arithmetic mod
2760 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2761 * borrows and carries out of the high digit can be ignored.
2762 * 5. Subtract ah*bh from the result, starting at shift.
2763 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2764 * at shift.
2765 */
2766
2767 /* 1. Allocate result space. */
2768 ret = _PyLong_New(asize + bsize);
2769 if (ret == NULL) goto fail;
2770 #ifdef Py_DEBUG
2771 /* Fill with trash, to catch reference to uninitialized digits. */
2772 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
2773 #endif
2774
2775 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2776 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2777 assert(Py_SIZE(t1) >= 0);
2778 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2779 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2780 Py_SIZE(t1) * sizeof(digit));
2781
2782 /* Zero-out the digits higher than the ah*bh copy. */
2783 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2784 if (i)
2785 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2786 i * sizeof(digit));
2787
2788 /* 3. t2 <- al*bl, and copy into the low digits. */
2789 if ((t2 = k_mul(al, bl)) == NULL) {
2790 Py_DECREF(t1);
2791 goto fail;
2792 }
2793 assert(Py_SIZE(t2) >= 0);
2794 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2795 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
2796
2797 /* Zero out remaining digits. */
2798 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2799 if (i)
2800 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
2801
2802 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2803 * because it's fresher in cache.
2804 */
2805 i = Py_SIZE(ret) - shift; /* # digits after shift */
2806 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2807 Py_DECREF(t2);
2808
2809 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2810 Py_DECREF(t1);
2811
2812 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2813 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2814 Py_DECREF(ah);
2815 Py_DECREF(al);
2816 ah = al = NULL;
2817
2818 if (a == b) {
2819 t2 = t1;
2820 Py_INCREF(t2);
2821 }
2822 else if ((t2 = x_add(bh, bl)) == NULL) {
2823 Py_DECREF(t1);
2824 goto fail;
2825 }
2826 Py_DECREF(bh);
2827 Py_DECREF(bl);
2828 bh = bl = NULL;
2829
2830 t3 = k_mul(t1, t2);
2831 Py_DECREF(t1);
2832 Py_DECREF(t2);
2833 if (t3 == NULL) goto fail;
2834 assert(Py_SIZE(t3) >= 0);
2835
2836 /* Add t3. It's not obvious why we can't run out of room here.
2837 * See the (*) comment after this function.
2838 */
2839 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
2840 Py_DECREF(t3);
2841
2842 return long_normalize(ret);
2843
2844 fail:
2845 Py_XDECREF(ret);
2846 Py_XDECREF(ah);
2847 Py_XDECREF(al);
2848 Py_XDECREF(bh);
2849 Py_XDECREF(bl);
2850 return NULL;
2851 }
2852
2853 /* (*) Why adding t3 can't "run out of room" above.
2854
2855 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2856 to start with:
2857
2858 1. For any integer i, i = c(i/2) + f(i/2). In particular,
2859 bsize = c(bsize/2) + f(bsize/2).
2860 2. shift = f(bsize/2)
2861 3. asize <= bsize
2862 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2863 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
2864
2865 We allocated asize + bsize result digits, and add t3 into them at an offset
2866 of shift. This leaves asize+bsize-shift allocated digit positions for t3
2867 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2868 asize + c(bsize/2) available digit positions.
2869
2870 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2871 at most c(bsize/2) digits + 1 bit.
2872
2873 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2874 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2875 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
2876
2877 The product (ah+al)*(bh+bl) therefore has at most
2878
2879 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
2880
2881 and we have asize + c(bsize/2) available digit positions. We need to show
2882 this is always enough. An instance of c(bsize/2) cancels out in both, so
2883 the question reduces to whether asize digits is enough to hold
2884 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2885 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2886 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2887 digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
2888 asize == bsize, then we're asking whether bsize digits is enough to hold
2889 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2890 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2891 bsize >= KARATSUBA_CUTOFF >= 2.
2892
2893 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2894 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2895 ah*bh and al*bl too.
2896 */
2897
2898 /* b has at least twice the digits of a, and a is big enough that Karatsuba
2899 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2900 * of slices, each with a->ob_size digits, and multiply the slices by a,
2901 * one at a time. This gives k_mul balanced inputs to work with, and is
2902 * also cache-friendly (we compute one double-width slice of the result
2903 * at a time, then move on, never backtracking except for the helpful
2904 * single-width slice overlap between successive partial sums).
2905 */
2906 static PyLongObject *
2907 k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2908 {
2909 const Py_ssize_t asize = ABS(Py_SIZE(a));
2910 Py_ssize_t bsize = ABS(Py_SIZE(b));
2911 Py_ssize_t nbdone; /* # of b digits already multiplied */
2912 PyLongObject *ret;
2913 PyLongObject *bslice = NULL;
2914
2915 assert(asize > KARATSUBA_CUTOFF);
2916 assert(2 * asize <= bsize);
2917
2918 /* Allocate result space, and zero it out. */
2919 ret = _PyLong_New(asize + bsize);
2920 if (ret == NULL)
2921 return NULL;
2922 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
2923
2924 /* Successive slices of b are copied into bslice. */
2925 bslice = _PyLong_New(asize);
2926 if (bslice == NULL)
2927 goto fail;
2928
2929 nbdone = 0;
2930 while (bsize > 0) {
2931 PyLongObject *product;
2932 const Py_ssize_t nbtouse = MIN(bsize, asize);
2933
2934 /* Multiply the next slice of b by a. */
2935 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2936 nbtouse * sizeof(digit));
2937 Py_SIZE(bslice) = nbtouse;
2938 product = k_mul(a, bslice);
2939 if (product == NULL)
2940 goto fail;
2941
2942 /* Add into result. */
2943 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2944 product->ob_digit, Py_SIZE(product));
2945 Py_DECREF(product);
2946
2947 bsize -= nbtouse;
2948 nbdone += nbtouse;
2949 }
2950
2951 Py_DECREF(bslice);
2952 return long_normalize(ret);
2953
2954 fail:
2955 Py_DECREF(ret);
2956 Py_XDECREF(bslice);
2957 return NULL;
2958 }
2959
2960 static PyObject *
2961 long_mul(PyLongObject *v, PyLongObject *w)
2962 {
2963 PyLongObject *a, *b, *z;
2964
2965 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
2966 Py_INCREF(Py_NotImplemented);
2967 return Py_NotImplemented;
2968 }
2969
2970 z = k_mul(a, b);
2971 /* Negate if exactly one of the inputs is negative. */
2972 if (((a->ob_size ^ b->ob_size) < 0) && z)
2973 z->ob_size = -(z->ob_size);
2974 Py_DECREF(a);
2975 Py_DECREF(b);
2976 return (PyObject *)z;
2977 }
2978
2979 /* The / and % operators are now defined in terms of divmod().
2980 The expression a mod b has the value a - b*floor(a/b).
2981 The long_divrem function gives the remainder after division of
2982 |a| by |b|, with the sign of a. This is also expressed
2983 as a - b*trunc(a/b), if trunc truncates towards zero.
2984 Some examples:
2985 a b a rem b a mod b
2986 13 10 3 3
2987 -13 10 -3 7
2988 13 -10 3 -7
2989 -13 -10 -3 -3
2990 So, to get from rem to mod, we have to add b if a and b
2991 have different signs. We then subtract one from the 'div'
2992 part of the outcome to keep the invariant intact. */
2993
2994 /* Compute
2995 * *pdiv, *pmod = divmod(v, w)
2996 * NULL can be passed for pdiv or pmod, in which case that part of
2997 * the result is simply thrown away. The caller owns a reference to
2998 * each of these it requests (does not pass NULL for).
2999 */
3000 static int
3001 l_divmod(PyLongObject *v, PyLongObject *w,
3002 PyLongObject **pdiv, PyLongObject **pmod)
3003 {
3004 PyLongObject *div, *mod;
3005
3006 if (long_divrem(v, w, &div, &mod) < 0)
3007 return -1;
3008 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3009 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3010 PyLongObject *temp;
3011 PyLongObject *one;
3012 temp = (PyLongObject *) long_add(mod, w);
3013 Py_DECREF(mod);
3014 mod = temp;
3015 if (mod == NULL) {
3016 Py_DECREF(div);
3017 return -1;
3018 }
3019 one = (PyLongObject *) PyLong_FromLong(1L);
3020 if (one == NULL ||
3021 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3022 Py_DECREF(mod);
3023 Py_DECREF(div);
3024 Py_XDECREF(one);
3025 return -1;
3026 }
3027 Py_DECREF(one);
3028 Py_DECREF(div);
3029 div = temp;
3030 }
3031 if (pdiv != NULL)
3032 *pdiv = div;
3033 else
3034 Py_DECREF(div);
3035
3036 if (pmod != NULL)
3037 *pmod = mod;
3038 else
3039 Py_DECREF(mod);
3040
3041 return 0;
3042 }
3043
3044 static PyObject *
3045 long_div(PyObject *v, PyObject *w)
3046 {
3047 PyLongObject *a, *b, *div;
3048
3049 CONVERT_BINOP(v, w, &a, &b);
3050 if (l_divmod(a, b, &div, NULL) < 0)
3051 div = NULL;
3052 Py_DECREF(a);
3053 Py_DECREF(b);
3054 return (PyObject *)div;
3055 }
3056
3057 static PyObject *
3058 long_classic_div(PyObject *v, PyObject *w)
3059 {
3060 PyLongObject *a, *b, *div;
3061
3062 CONVERT_BINOP(v, w, &a, &b);
3063 if (Py_DivisionWarningFlag &&
3064 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
3065 div = NULL;
3066 else if (l_divmod(a, b, &div, NULL) < 0)
3067 div = NULL;
3068 Py_DECREF(a);
3069 Py_DECREF(b);
3070 return (PyObject *)div;
3071 }
3072
3073 /* PyLong/PyLong -> float, with correctly rounded result. */
3074
3075 #define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3076 #define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3077
3078 static PyObject *
3079 long_true_divide(PyObject *v, PyObject *w)
3080 {
3081 PyLongObject *a, *b, *x;
3082 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3083 digit mask, low;
3084 int inexact, negate, a_is_small, b_is_small;
3085 double dx, result;
3086
3087 CONVERT_BINOP(v, w, &a, &b);
3088
3089 /*
3090 Method in a nutshell:
3091
3092 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3093 1. choose a suitable integer 'shift'
3094 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3095 3. adjust x for correct rounding
3096 4. convert x to a double dx with the same value
3097 5. return ldexp(dx, shift).
3098
3099 In more detail:
3100
3101 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3102 returns either 0.0 or -0.0, depending on the sign of b. For a and
3103 b both nonzero, ignore signs of a and b, and add the sign back in
3104 at the end. Now write a_bits and b_bits for the bit lengths of a
3105 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3106 for b). Then
3107
3108 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3109
3110 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3111 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3112 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3113 the way, we can assume that
3114
3115 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3116
3117 1. The integer 'shift' is chosen so that x has the right number of
3118 bits for a double, plus two or three extra bits that will be used
3119 in the rounding decisions. Writing a_bits and b_bits for the
3120 number of significant bits in a and b respectively, a
3121 straightforward formula for shift is:
3122
3123 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3124
3125 This is fine in the usual case, but if a/b is smaller than the
3126 smallest normal float then it can lead to double rounding on an
3127 IEEE 754 platform, giving incorrectly rounded results. So we
3128 adjust the formula slightly. The actual formula used is:
3129
3130 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3131
3132 2. The quantity x is computed by first shifting a (left -shift bits
3133 if shift <= 0, right shift bits if shift > 0) and then dividing by
3134 b. For both the shift and the division, we keep track of whether
3135 the result is inexact, in a flag 'inexact'; this information is
3136 needed at the rounding stage.
3137
3138 With the choice of shift above, together with our assumption that
3139 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3140 that x >= 1.
3141
3142 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3143 this with an exactly representable float of the form
3144
3145 round(x/2**extra_bits) * 2**(extra_bits+shift).
3146
3147 For float representability, we need x/2**extra_bits <
3148 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3149 DBL_MANT_DIG. This translates to the condition:
3150
3151 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3152
3153 To round, we just modify the bottom digit of x in-place; this can
3154 end up giving a digit with value > PyLONG_MASK, but that's not a
3155 problem since digits can hold values up to 2*PyLONG_MASK+1.
3156
3157 With the original choices for shift above, extra_bits will always
3158 be 2 or 3. Then rounding under the round-half-to-even rule, we
3159 round up iff the most significant of the extra bits is 1, and
3160 either: (a) the computation of x in step 2 had an inexact result,
3161 or (b) at least one other of the extra bits is 1, or (c) the least
3162 significant bit of x (above those to be rounded) is 1.
3163
3164 4. Conversion to a double is straightforward; all floating-point
3165 operations involved in the conversion are exact, so there's no
3166 danger of rounding errors.
3167
3168 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3169 The result will always be exactly representable as a double, except
3170 in the case that it overflows. To avoid dependence on the exact
3171 behaviour of ldexp on overflow, we check for overflow before
3172 applying ldexp. The result of ldexp is adjusted for sign before
3173 returning.
3174 */
3175
3176 /* Reduce to case where a and b are both positive. */
3177 a_size = ABS(Py_SIZE(a));
3178 b_size = ABS(Py_SIZE(b));
3179 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3180 if (b_size == 0) {
3181 PyErr_SetString(PyExc_ZeroDivisionError,
3182 "division by zero");
3183 goto error;
3184 }
3185 if (a_size == 0)
3186 goto underflow_or_zero;
3187
3188 /* Fast path for a and b small (exactly representable in a double).
3189 Relies on floating-point division being correctly rounded; results
3190 may be subject to double rounding on x86 machines that operate with
3191 the x87 FPU set to 64-bit precision. */
3192 a_is_small = a_size <= MANT_DIG_DIGITS ||
3193 (a_size == MANT_DIG_DIGITS+1 &&
3194 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3195 b_is_small = b_size <= MANT_DIG_DIGITS ||
3196 (b_size == MANT_DIG_DIGITS+1 &&
3197 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3198 if (a_is_small && b_is_small) {
3199 double da, db;
3200 da = a->ob_digit[--a_size];
3201 while (a_size > 0)
3202 da = da * PyLong_BASE + a->ob_digit[--a_size];
3203 db = b->ob_digit[--b_size];
3204 while (b_size > 0)
3205 db = db * PyLong_BASE + b->ob_digit[--b_size];
3206 result = da / db;
3207 goto success;
3208 }
3209
3210 /* Catch obvious cases of underflow and overflow */
3211 diff = a_size - b_size;
3212 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3213 /* Extreme overflow */
3214 goto overflow;
3215 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3216 /* Extreme underflow */
3217 goto underflow_or_zero;
3218 /* Next line is now safe from overflowing a Py_ssize_t */
3219 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3220 bits_in_digit(b->ob_digit[b_size - 1]);
3221 /* Now diff = a_bits - b_bits. */
3222 if (diff > DBL_MAX_EXP)
3223 goto overflow;
3224 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3225 goto underflow_or_zero;
3226
3227 /* Choose value for shift; see comments for step 1 above. */
3228 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3229
3230 inexact = 0;
3231
3232 /* x = abs(a * 2**-shift) */
3233 if (shift <= 0) {
3234 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3235 digit rem;
3236 /* x = a << -shift */
3237 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3238 /* In practice, it's probably impossible to end up
3239 here. Both a and b would have to be enormous,
3240 using close to SIZE_T_MAX bytes of memory each. */
3241 PyErr_SetString(PyExc_OverflowError,
3242 "intermediate overflow during division");
3243 goto error;
3244 }
3245 x = _PyLong_New(a_size + shift_digits + 1);
3246 if (x == NULL)
3247 goto error;
3248 for (i = 0; i < shift_digits; i++)
3249 x->ob_digit[i] = 0;
3250 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3251 a_size, -shift % PyLong_SHIFT);
3252 x->ob_digit[a_size + shift_digits] = rem;
3253 }
3254 else {
3255 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3256 digit rem;
3257 /* x = a >> shift */
3258 assert(a_size >= shift_digits);
3259 x = _PyLong_New(a_size - shift_digits);
3260 if (x == NULL)
3261 goto error;
3262 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3263 a_size - shift_digits, shift % PyLong_SHIFT);
3264 /* set inexact if any of the bits shifted out is nonzero */
3265 if (rem)
3266 inexact = 1;
3267 while (!inexact && shift_digits > 0)
3268 if (a->ob_digit[--shift_digits])
3269 inexact = 1;
3270 }
3271 long_normalize(x);
3272 x_size = Py_SIZE(x);
3273
3274 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3275 reference to x, so it's safe to modify it in-place. */
3276 if (b_size == 1) {
3277 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3278 b->ob_digit[0]);
3279 long_normalize(x);
3280 if (rem)
3281 inexact = 1;
3282 }
3283 else {
3284 PyLongObject *div, *rem;
3285 div = x_divrem(x, b, &rem);
3286 Py_DECREF(x);
3287 x = div;
3288 if (x == NULL)
3289 goto error;
3290 if (Py_SIZE(rem))
3291 inexact = 1;
3292 Py_DECREF(rem);
3293 }
3294 x_size = ABS(Py_SIZE(x));
3295 assert(x_size > 0); /* result of division is never zero */
3296 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3297
3298 /* The number of extra bits that have to be rounded away. */
3299 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3300 assert(extra_bits == 2 || extra_bits == 3);
3301
3302 /* Round by directly modifying the low digit of x. */
3303 mask = (digit)1 << (extra_bits - 1);
3304 low = x->ob_digit[0] | inexact;
3305 if (low & mask && low & (3*mask-1))
3306 low += mask;
3307 x->ob_digit[0] = low & ~(mask-1U);
3308
3309 /* Convert x to a double dx; the conversion is exact. */
3310 dx = x->ob_digit[--x_size];
3311 while (x_size > 0)
3312 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3313 Py_DECREF(x);
3314
3315 /* Check whether ldexp result will overflow a double. */
3316 if (shift + x_bits >= DBL_MAX_EXP &&
3317 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3318 goto overflow;
3319 result = ldexp(dx, (int)shift);
3320
3321 success:
3322 Py_DECREF(a);
3323 Py_DECREF(b);
3324 return PyFloat_FromDouble(negate ? -result : result);
3325
3326 underflow_or_zero:
3327 Py_DECREF(a);
3328 Py_DECREF(b);
3329 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3330
3331 overflow:
3332 PyErr_SetString(PyExc_OverflowError,
3333 "integer division result too large for a float");
3334 error:
3335 Py_DECREF(a);
3336 Py_DECREF(b);
3337 return NULL;
3338 }
3339
3340 static PyObject *
3341 long_mod(PyObject *v, PyObject *w)
3342 {
3343 PyLongObject *a, *b, *mod;
3344
3345 CONVERT_BINOP(v, w, &a, &b);
3346
3347 if (l_divmod(a, b, NULL, &mod) < 0)
3348 mod = NULL;
3349 Py_DECREF(a);
3350 Py_DECREF(b);
3351 return (PyObject *)mod;
3352 }
3353
3354 static PyObject *
3355 long_divmod(PyObject *v, PyObject *w)
3356 {
3357 PyLongObject *a, *b, *div, *mod;
3358 PyObject *z;
3359
3360 CONVERT_BINOP(v, w, &a, &b);
3361
3362 if (l_divmod(a, b, &div, &mod) < 0) {
3363 Py_DECREF(a);
3364 Py_DECREF(b);
3365 return NULL;
3366 }
3367 z = PyTuple_New(2);
3368 if (z != NULL) {
3369 PyTuple_SetItem(z, 0, (PyObject *) div);
3370 PyTuple_SetItem(z, 1, (PyObject *) mod);
3371 }
3372 else {
3373 Py_DECREF(div);
3374 Py_DECREF(mod);
3375 }
3376 Py_DECREF(a);
3377 Py_DECREF(b);
3378 return z;
3379 }
3380
3381 /* pow(v, w, x) */
3382 static PyObject *
3383 long_pow(PyObject *v, PyObject *w, PyObject *x)
3384 {
3385 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3386 int negativeOutput = 0; /* if x<0 return negative output */
3387
3388 PyLongObject *z = NULL; /* accumulated result */
3389 Py_ssize_t i, j, k; /* counters */
3390 PyLongObject *temp = NULL;
3391
3392 /* 5-ary values. If the exponent is large enough, table is
3393 * precomputed so that table[i] == a**i % c for i in range(32).
3394 */
3395 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3396 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3397
3398 /* a, b, c = v, w, x */
3399 CONVERT_BINOP(v, w, &a, &b);
3400 if (PyLong_Check(x)) {
3401 c = (PyLongObject *)x;
3402 Py_INCREF(x);
3403 }
3404 else if (PyInt_Check(x)) {
3405 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
3406 if (c == NULL)
3407 goto Error;
3408 }
3409 else if (x == Py_None)
3410 c = NULL;
3411 else {
3412 Py_DECREF(a);
3413 Py_DECREF(b);
3414 Py_INCREF(Py_NotImplemented);
3415 return Py_NotImplemented;
3416 }
3417
3418 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3419 if (c) {
3420 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
3421 "cannot be negative when 3rd argument specified");
3422 goto Error;
3423 }
3424 else {
3425 /* else return a float. This works because we know
3426 that this calls float_pow() which converts its
3427 arguments to double. */
3428 Py_DECREF(a);
3429 Py_DECREF(b);
3430 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3431 }
3432 }
3433
3434 if (c) {
3435 /* if modulus == 0:
3436 raise ValueError() */
3437 if (Py_SIZE(c) == 0) {
3438 PyErr_SetString(PyExc_ValueError,
3439 "pow() 3rd argument cannot be 0");
3440 goto Error;
3441 }
3442
3443 /* if modulus < 0:
3444 negativeOutput = True
3445 modulus = -modulus */
3446 if (Py_SIZE(c) < 0) {
3447 negativeOutput = 1;
3448 temp = (PyLongObject *)_PyLong_Copy(c);
3449 if (temp == NULL)
3450 goto Error;
3451 Py_DECREF(c);
3452 c = temp;
3453 temp = NULL;
3454 c->ob_size = - c->ob_size;
3455 }
3456
3457 /* if modulus == 1:
3458 return 0 */
3459 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3460 z = (PyLongObject *)PyLong_FromLong(0L);
3461 goto Done;
3462 }
3463
3464 /* if base < 0:
3465 base = base % modulus
3466 Having the base positive just makes things easier. */
3467 if (Py_SIZE(a) < 0) {
3468 if (l_divmod(a, c, NULL, &temp) < 0)
3469 goto Error;
3470 Py_DECREF(a);
3471 a = temp;
3472 temp = NULL;
3473 }
3474 }
3475
3476 /* At this point a, b, and c are guaranteed non-negative UNLESS
3477 c is NULL, in which case a may be negative. */
3478
3479 z = (PyLongObject *)PyLong_FromLong(1L);
3480 if (z == NULL)
3481 goto Error;
3482
3483 /* Perform a modular reduction, X = X % c, but leave X alone if c
3484 * is NULL.
3485 */
3486 #define REDUCE(X) \
3487 do { \
3488 if (c != NULL) { \
3489 if (l_divmod(X, c, NULL, &temp) < 0) \
3490 goto Error; \
3491 Py_XDECREF(X); \
3492 X = temp; \
3493 temp = NULL; \
3494 } \
3495 } while(0)
3496
3497 /* Multiply two values, then reduce the result:
3498 result = X*Y % c. If c is NULL, skip the mod. */
3499 #define MULT(X, Y, result) \
3500 do { \
3501 temp = (PyLongObject *)long_mul(X, Y); \
3502 if (temp == NULL) \
3503 goto Error; \
3504 Py_XDECREF(result); \
3505 result = temp; \
3506 temp = NULL; \
3507 REDUCE(result); \
3508 } while(0)
3509
3510 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3511 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3512 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3513 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3514 digit bi = b->ob_digit[i];
3515
3516 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
3517 MULT(z, z, z);
3518 if (bi & j)
3519 MULT(z, a, z);
3520 }
3521 }
3522 }
3523 else {
3524 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3525 Py_INCREF(z); /* still holds 1L */
3526 table[0] = z;
3527 for (i = 1; i < 32; ++i)
3528 MULT(table[i-1], a, table[i]);
3529
3530 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3531 const digit bi = b->ob_digit[i];
3532
3533 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3534 const int index = (bi >> j) & 0x1f;
3535 for (k = 0; k < 5; ++k)
3536 MULT(z, z, z);
3537 if (index)
3538 MULT(z, table[index], z);
3539 }
3540 }
3541 }
3542
3543 if (negativeOutput && (Py_SIZE(z) != 0)) {
3544 temp = (PyLongObject *)long_sub(z, c);
3545 if (temp == NULL)
3546 goto Error;
3547 Py_DECREF(z);
3548 z = temp;
3549 temp = NULL;
3550 }
3551 goto Done;
3552
3553 Error:
3554 if (z != NULL) {
3555 Py_DECREF(z);
3556 z = NULL;
3557 }
3558 /* fall through */
3559 Done:
3560 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3561 for (i = 0; i < 32; ++i)
3562 Py_XDECREF(table[i]);
3563 }
3564 Py_DECREF(a);
3565 Py_DECREF(b);
3566 Py_XDECREF(c);
3567 Py_XDECREF(temp);
3568 return (PyObject *)z;
3569 }
3570
3571 static PyObject *
3572 long_invert(PyLongObject *v)
3573 {
3574 /* Implement ~x as -(x+1) */
3575 PyLongObject *x;
3576 PyLongObject *w;
3577 w = (PyLongObject *)PyLong_FromLong(1L);
3578 if (w == NULL)
3579 return NULL;
3580 x = (PyLongObject *) long_add(v, w);
3581 Py_DECREF(w);
3582 if (x == NULL)
3583 return NULL;
3584 Py_SIZE(x) = -(Py_SIZE(x));
3585 return (PyObject *)x;
3586 }
3587
3588 static PyObject *
3589 long_neg(PyLongObject *v)
3590 {
3591 PyLongObject *z;
3592 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
3593 /* -0 == 0 */
3594 Py_INCREF(v);
3595 return (PyObject *) v;
3596 }
3597 z = (PyLongObject *)_PyLong_Copy(v);
3598 if (z != NULL)
3599 z->ob_size = -(v->ob_size);
3600 return (PyObject *)z;
3601 }
3602
3603 static PyObject *
3604 long_abs(PyLongObject *v)
3605 {
3606 if (v->ob_size < 0)
3607 return long_neg(v);
3608 else
3609 return long_long((PyObject *)v);
3610 }
3611
3612 static int
3613 long_nonzero(PyLongObject *v)
3614 {
3615 return Py_SIZE(v) != 0;
3616 }
3617
3618 static PyObject *
3619 long_rshift(PyLongObject *v, PyLongObject *w)
3620 {
3621 PyLongObject *a, *b;
3622 PyLongObject *z = NULL;
3623 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3624 digit lomask, himask;
3625
3626 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
3627
3628 if (Py_SIZE(a) < 0) {
3629 /* Right shifting negative numbers is harder */
3630 PyLongObject *a1, *a2;
3631 a1 = (PyLongObject *) long_invert(a);
3632 if (a1 == NULL)
3633 goto rshift_error;
3634 a2 = (PyLongObject *) long_rshift(a1, b);
3635 Py_DECREF(a1);
3636 if (a2 == NULL)
3637 goto rshift_error;
3638 z = (PyLongObject *) long_invert(a2);
3639 Py_DECREF(a2);
3640 }
3641 else {
3642 shiftby = PyLong_AsSsize_t((PyObject *)b);
3643 if (shiftby == -1L && PyErr_Occurred())
3644 goto rshift_error;
3645 if (shiftby < 0) {
3646 PyErr_SetString(PyExc_ValueError,
3647 "negative shift count");
3648 goto rshift_error;
3649 }
3650 wordshift = shiftby / PyLong_SHIFT;
3651 newsize = ABS(Py_SIZE(a)) - wordshift;
3652 if (newsize <= 0) {
3653 z = _PyLong_New(0);
3654 Py_DECREF(a);
3655 Py_DECREF(b);
3656 return (PyObject *)z;
3657 }
3658 loshift = shiftby % PyLong_SHIFT;
3659 hishift = PyLong_SHIFT - loshift;
3660 lomask = ((digit)1 << hishift) - 1;
3661 himask = PyLong_MASK ^ lomask;
3662 z = _PyLong_New(newsize);
3663 if (z == NULL)
3664 goto rshift_error;
3665 if (Py_SIZE(a) < 0)
3666 Py_SIZE(z) = -(Py_SIZE(z));
3667 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3668 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3669 if (i+1 < newsize)
3670 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
3671 }
3672 z = long_normalize(z);
3673 }
3674 rshift_error:
3675 Py_DECREF(a);
3676 Py_DECREF(b);
3677 return (PyObject *) z;
3678
3679 }
3680
3681 static PyObject *
3682 long_lshift(PyObject *v, PyObject *w)
3683 {
3684 /* This version due to Tim Peters */
3685 PyLongObject *a, *b;
3686 PyLongObject *z = NULL;
3687 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3688 twodigits accum;
3689
3690 CONVERT_BINOP(v, w, &a, &b);
3691
3692 shiftby = PyLong_AsSsize_t((PyObject *)b);
3693 if (shiftby == -1L && PyErr_Occurred())
3694 goto lshift_error;
3695 if (shiftby < 0) {
3696 PyErr_SetString(PyExc_ValueError, "negative shift count");
3697 goto lshift_error;
3698 }
3699 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3700 wordshift = shiftby / PyLong_SHIFT;
3701 remshift = shiftby - wordshift * PyLong_SHIFT;
3702
3703 oldsize = ABS(a->ob_size);
3704 newsize = oldsize + wordshift;
3705 if (remshift)
3706 ++newsize;
3707 z = _PyLong_New(newsize);
3708 if (z == NULL)
3709 goto lshift_error;
3710 if (a->ob_size < 0)
3711 z->ob_size = -(z->ob_size);
3712 for (i = 0; i < wordshift; i++)
3713 z->ob_digit[i] = 0;
3714 accum = 0;
3715 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3716 accum |= (twodigits)a->ob_digit[j] << remshift;
3717 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3718 accum >>= PyLong_SHIFT;
3719 }
3720 if (remshift)
3721 z->ob_digit[newsize-1] = (digit)accum;
3722 else
3723 assert(!accum);
3724 z = long_normalize(z);
3725 lshift_error:
3726 Py_DECREF(a);
3727 Py_DECREF(b);
3728 return (PyObject *) z;
3729 }
3730
3731 /* Compute two's complement of digit vector a[0:m], writing result to
3732 z[0:m]. The digit vector a need not be normalized, but should not
3733 be entirely zero. a and z may point to the same digit vector. */
3734
3735 static void
3736 v_complement(digit *z, digit *a, Py_ssize_t m)
3737 {
3738 Py_ssize_t i;
3739 digit carry = 1;
3740 for (i = 0; i < m; ++i) {
3741 carry += a[i] ^ PyLong_MASK;
3742 z[i] = carry & PyLong_MASK;
3743 carry >>= PyLong_SHIFT;
3744 }
3745 assert(carry == 0);
3746 }
3747
3748 /* Bitwise and/xor/or operations */
3749
3750 static PyObject *
3751 long_bitwise(PyLongObject *a,
3752 int op, /* '&', '|', '^' */
3753 PyLongObject *b)
3754 {
3755 int nega, negb, negz;
3756 Py_ssize_t size_a, size_b, size_z, i;
3757 PyLongObject *z;
3758
3759 /* Bitwise operations for negative numbers operate as though
3760 on a two's complement representation. So convert arguments
3761 from sign-magnitude to two's complement, and convert the
3762 result back to sign-magnitude at the end. */
3763
3764 /* If a is negative, replace it by its two's complement. */
3765 size_a = ABS(Py_SIZE(a));
3766 nega = Py_SIZE(a) < 0;
3767 if (nega) {
3768 z = _PyLong_New(size_a);
3769 if (z == NULL)
3770 return NULL;
3771 v_complement(z->ob_digit, a->ob_digit, size_a);
3772 a = z;
3773 }
3774 else
3775 /* Keep reference count consistent. */
3776 Py_INCREF(a);
3777
3778 /* Same for b. */
3779 size_b = ABS(Py_SIZE(b));
3780 negb = Py_SIZE(b) < 0;
3781 if (negb) {
3782 z = _PyLong_New(size_b);
3783 if (z == NULL) {
3784 Py_DECREF(a);
3785 return NULL;
3786 }
3787 v_complement(z->ob_digit, b->ob_digit, size_b);
3788 b = z;
3789 }
3790 else
3791 Py_INCREF(b);
3792
3793 /* Swap a and b if necessary to ensure size_a >= size_b. */
3794 if (size_a < size_b) {
3795 z = a; a = b; b = z;
3796 size_z = size_a; size_a = size_b; size_b = size_z;
3797 negz = nega; nega = negb; negb = negz;
3798 }
3799
3800 /* JRH: The original logic here was to allocate the result value (z)
3801 as the longer of the two operands. However, there are some cases
3802 where the result is guaranteed to be shorter than that: AND of two
3803 positives, OR of two negatives: use the shorter number. AND with
3804 mixed signs: use the positive number. OR with mixed signs: use the
3805 negative number.
3806 */
3807 switch (op) {
3808 case '^':
3809 negz = nega ^ negb;
3810 size_z = size_a;
3811 break;
3812 case '&':
3813 negz = nega & negb;
3814 size_z = negb ? size_a : size_b;
3815 break;
3816 case '|':
3817 negz = nega | negb;
3818 size_z = negb ? size_b : size_a;
3819 break;
3820 default:
3821 PyErr_BadArgument();
3822 return NULL;
3823 }
3824
3825 /* We allow an extra digit if z is negative, to make sure that
3826 the final two's complement of z doesn't overflow. */
3827 z = _PyLong_New(size_z + negz);
3828 if (z == NULL) {
3829 Py_DECREF(a);
3830 Py_DECREF(b);
3831 return NULL;
3832 }
3833
3834 /* Compute digits for overlap of a and b. */
3835 switch(op) {
3836 case '&':
3837 for (i = 0; i < size_b; ++i)
3838 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3839 break;
3840 case '|':
3841 for (i = 0; i < size_b; ++i)
3842 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3843 break;
3844 case '^':
3845 for (i = 0; i < size_b; ++i)
3846 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3847 break;
3848 default:
3849 PyErr_BadArgument();
3850 return NULL;
3851 }
3852
3853 /* Copy any remaining digits of a, inverting if necessary. */
3854 if (op == '^' && negb)
3855 for (; i < size_z; ++i)
3856 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3857 else if (i < size_z)
3858 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3859 (size_z-i)*sizeof(digit));
3860
3861 /* Complement result if negative. */
3862 if (negz) {
3863 Py_SIZE(z) = -(Py_SIZE(z));
3864 z->ob_digit[size_z] = PyLong_MASK;
3865 v_complement(z->ob_digit, z->ob_digit, size_z+1);
3866 }
3867
3868 Py_DECREF(a);
3869 Py_DECREF(b);
3870 return (PyObject *)long_normalize(z);
3871 }
3872
3873 static PyObject *
3874 long_and(PyObject *v, PyObject *w)
3875 {
3876 PyLongObject *a, *b;
3877 PyObject *c;
3878 CONVERT_BINOP(v, w, &a, &b);
3879 c = long_bitwise(a, '&', b);
3880 Py_DECREF(a);
3881 Py_DECREF(b);
3882 return c;
3883 }
3884
3885 static PyObject *
3886 long_xor(PyObject *v, PyObject *w)
3887 {
3888 PyLongObject *a, *b;
3889 PyObject *c;
3890 CONVERT_BINOP(v, w, &a, &b);
3891 c = long_bitwise(a, '^', b);
3892 Py_DECREF(a);
3893 Py_DECREF(b);
3894 return c;
3895 }
3896
3897 static PyObject *
3898 long_or(PyObject *v, PyObject *w)
3899 {
3900 PyLongObject *a, *b;
3901 PyObject *c;
3902 CONVERT_BINOP(v, w, &a, &b);
3903 c = long_bitwise(a, '|', b);
3904 Py_DECREF(a);
3905 Py_DECREF(b);
3906 return c;
3907 }
3908
3909 static int
3910 long_coerce(PyObject **pv, PyObject **pw)
3911 {
3912 if (PyInt_Check(*pw)) {
3913 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
3914 if (*pw == NULL)
3915 return -1;
3916 Py_INCREF(*pv);
3917 return 0;
3918 }
3919 else if (PyLong_Check(*pw)) {
3920 Py_INCREF(*pv);
3921 Py_INCREF(*pw);
3922 return 0;
3923 }
3924 return 1; /* Can't do it */
3925 }
3926
3927 static PyObject *
3928 long_long(PyObject *v)
3929 {
3930 if (PyLong_CheckExact(v))
3931 Py_INCREF(v);
3932 else
3933 v = _PyLong_Copy((PyLongObject *)v);
3934 return v;
3935 }
3936
3937 static PyObject *
3938 long_int(PyObject *v)
3939 {
3940 long x;
3941 x = PyLong_AsLong(v);
3942 if (PyErr_Occurred()) {
3943 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3944 PyErr_Clear();
3945 if (PyLong_CheckExact(v)) {
3946 Py_INCREF(v);
3947 return v;
3948 }
3949 else
3950 return _PyLong_Copy((PyLongObject *)v);
3951 }
3952 else
3953 return NULL;
3954 }
3955 return PyInt_FromLong(x);
3956 }
3957
3958 static PyObject *
3959 long_float(PyObject *v)
3960 {
3961 double result;
3962 result = PyLong_AsDouble(v);
3963 if (result == -1.0 && PyErr_Occurred())
3964 return NULL;
3965 return PyFloat_FromDouble(result);
3966 }
3967
3968 static PyObject *
3969 long_oct(PyObject *v)
3970 {
3971 return _PyLong_Format(v, 8, 1, 0);
3972 }
3973
3974 static PyObject *
3975 long_hex(PyObject *v)
3976 {
3977 return _PyLong_Format(v, 16, 1, 0);
3978 }
3979
3980 static PyObject *
3981 long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3982
3983 static PyObject *
3984 long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3985 {
3986 PyObject *x = NULL;
3987 int base = -909; /* unlikely! */
3988 static char *kwlist[] = {"x", "base", 0};
3989
3990 if (type != &PyLong_Type)
3991 return long_subtype_new(type, args, kwds); /* Wimp out */
3992 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3993 &x, &base))
3994 return NULL;
3995 if (x == NULL)
3996 return PyLong_FromLong(0L);
3997 if (base == -909)
3998 return PyNumber_Long(x);
3999 else if (PyString_Check(x)) {
4000 /* Since PyLong_FromString doesn't have a length parameter,
4001 * check here for possible NULs in the string. */
4002 char *string = PyString_AS_STRING(x);
4003 if (strlen(string) != (size_t)PyString_Size(x)) {
4004 /* create a repr() of the input string,
4005 * just like PyLong_FromString does. */
4006 PyObject *srepr;
4007 srepr = PyObject_Repr(x);
4008 if (srepr == NULL)
4009 return NULL;
4010 PyErr_Format(PyExc_ValueError,
4011 "invalid literal for long() with base %d: %s",
4012 base, PyString_AS_STRING(srepr));
4013 Py_DECREF(srepr);
4014 return NULL;
4015 }
4016 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
4017 }
4018 #ifdef Py_USING_UNICODE
4019 else if (PyUnicode_Check(x))
4020 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4021 PyUnicode_GET_SIZE(x),
4022 base);
4023 #endif
4024 else {
4025 PyErr_SetString(PyExc_TypeError,
4026 "long() can't convert non-string with explicit base");
4027 return NULL;
4028 }
4029 }
4030
4031 /* Wimpy, slow approach to tp_new calls for subtypes of long:
4032 first create a regular long from whatever arguments we got,
4033 then allocate a subtype instance and initialize it from
4034 the regular long. The regular long is then thrown away.
4035 */
4036 static PyObject *
4037 long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4038 {
4039 PyLongObject *tmp, *newobj;
4040 Py_ssize_t i, n;
4041
4042 assert(PyType_IsSubtype(type, &PyLong_Type));
4043 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4044 if (tmp == NULL)
4045 return NULL;
4046 assert(PyLong_CheckExact(tmp));
4047 n = Py_SIZE(tmp);
4048 if (n < 0)
4049 n = -n;
4050 newobj = (PyLongObject *)type->tp_alloc(type, n);
4051 if (newobj == NULL) {
4052 Py_DECREF(tmp);
4053 return NULL;
4054 }
4055 assert(PyLong_Check(newobj));
4056 Py_SIZE(newobj) = Py_SIZE(tmp);
4057 for (i = 0; i < n; i++)
4058 newobj->ob_digit[i] = tmp->ob_digit[i];
4059 Py_DECREF(tmp);
4060 return (PyObject *)newobj;
4061 }
4062
4063 static PyObject *
4064 long_getnewargs(PyLongObject *v)
4065 {
4066 return Py_BuildValue("(N)", _PyLong_Copy(v));
4067 }
4068
4069 static PyObject *
4070 long_get0(PyLongObject *v, void *context) {
4071 return PyLong_FromLong(0L);
4072 }
4073
4074 static PyObject *
4075 long_get1(PyLongObject *v, void *context) {
4076 return PyLong_FromLong(1L);
4077 }
4078
4079 static PyObject *
4080 long__format__(PyObject *self, PyObject *args)
4081 {
4082 PyObject *format_spec;
4083
4084 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
4085 return NULL;
4086 if (PyBytes_Check(format_spec))
4087 return _PyLong_FormatAdvanced(self,
4088 PyBytes_AS_STRING(format_spec),
4089 PyBytes_GET_SIZE(format_spec));
4090 if (PyUnicode_Check(format_spec)) {
4091 /* Convert format_spec to a str */
4092 PyObject *result;
4093 PyObject *str_spec = PyObject_Str(format_spec);
4094
4095 if (str_spec == NULL)
4096 return NULL;
4097
4098 result = _PyLong_FormatAdvanced(self,
4099 PyBytes_AS_STRING(str_spec),
4100 PyBytes_GET_SIZE(str_spec));
4101
4102 Py_DECREF(str_spec);
4103 return result;
4104 }
4105 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
4106 return NULL;
4107 }
4108
4109 static PyObject *
4110 long_sizeof(PyLongObject *v)
4111 {
4112 Py_ssize_t res;
4113
4114 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
4115 return PyInt_FromSsize_t(res);
4116 }
4117
4118 static PyObject *
4119 long_bit_length(PyLongObject *v)
4120 {
4121 PyLongObject *result, *x, *y;
4122 Py_ssize_t ndigits, msd_bits = 0;
4123 digit msd;
4124
4125 assert(v != NULL);
4126 assert(PyLong_Check(v));
4127
4128 ndigits = ABS(Py_SIZE(v));
4129 if (ndigits == 0)
4130 return PyInt_FromLong(0);
4131
4132 msd = v->ob_digit[ndigits-1];
4133 while (msd >= 32) {
4134 msd_bits += 6;
4135 msd >>= 6;
4136 }
4137 msd_bits += (long)(BitLengthTable[msd]);
4138
4139 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4140 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4141
4142 /* expression above may overflow; use Python integers instead */
4143 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4144 if (result == NULL)
4145 return NULL;
4146 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4147 if (x == NULL)
4148 goto error;
4149 y = (PyLongObject *)long_mul(result, x);
4150 Py_DECREF(x);
4151 if (y == NULL)
4152 goto error;
4153 Py_DECREF(result);
4154 result = y;
4155
4156 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4157 if (x == NULL)
4158 goto error;
4159 y = (PyLongObject *)long_add(result, x);
4160 Py_DECREF(x);
4161 if (y == NULL)
4162 goto error;
4163 Py_DECREF(result);
4164 result = y;
4165
4166 return (PyObject *)result;
4167
4168 error:
4169 Py_DECREF(result);
4170 return NULL;
4171 }
4172
4173 PyDoc_STRVAR(long_bit_length_doc,
4174 "long.bit_length() -> int or long\n\
4175 \n\
4176 Number of bits necessary to represent self in binary.\n\
4177 >>> bin(37L)\n\
4178 '0b100101'\n\
4179 >>> (37L).bit_length()\n\
4180 6");
4181
4182 #if 0
4183 static PyObject *
4184 long_is_finite(PyObject *v)
4185 {
4186 Py_RETURN_TRUE;
4187 }
4188 #endif
4189
4190 static PyMethodDef long_methods[] = {
4191 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4192 "Returns self, the complex conjugate of any long."},
4193 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4194 long_bit_length_doc},
4195 #if 0
4196 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4197 "Returns always True."},
4198 #endif
4199 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4200 "Truncating an Integral returns itself."},
4201 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4202 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4203 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4204 "Returns size in memory, in bytes"},
4205 {NULL, NULL} /* sentinel */
4206 };
4207
4208 static PyGetSetDef long_getset[] = {
4209 {"real",
4210 (getter)long_long, (setter)NULL,
4211 "the real part of a complex number",
4212 NULL},
4213 {"imag",
4214 (getter)long_get0, (setter)NULL,
4215 "the imaginary part of a complex number",
4216 NULL},
4217 {"numerator",
4218 (getter)long_long, (setter)NULL,
4219 "the numerator of a rational number in lowest terms",
4220 NULL},
4221 {"denominator",
4222 (getter)long_get1, (setter)NULL,
4223 "the denominator of a rational number in lowest terms",
4224 NULL},
4225 {NULL} /* Sentinel */
4226 };
4227
4228 PyDoc_STRVAR(long_doc,
4229 "long(x[, base]) -> integer\n\
4230 \n\
4231 Convert a string or number to a long integer, if possible. A floating\n\
4232 point argument will be truncated towards zero (this does not include a\n\
4233 string representation of a floating point number!) When converting a\n\
4234 string, use the optional base. It is an error to supply a base when\n\
4235 converting a non-string.");
4236
4237 static PyNumberMethods long_as_number = {
4238 (binaryfunc)long_add, /*nb_add*/
4239 (binaryfunc)long_sub, /*nb_subtract*/
4240 (binaryfunc)long_mul, /*nb_multiply*/
4241 long_classic_div, /*nb_divide*/
4242 long_mod, /*nb_remainder*/
4243 long_divmod, /*nb_divmod*/
4244 long_pow, /*nb_power*/
4245 (unaryfunc)long_neg, /*nb_negative*/
4246 (unaryfunc)long_long, /*tp_positive*/
4247 (unaryfunc)long_abs, /*tp_absolute*/
4248 (inquiry)long_nonzero, /*tp_nonzero*/
4249 (unaryfunc)long_invert, /*nb_invert*/
4250 long_lshift, /*nb_lshift*/
4251 (binaryfunc)long_rshift, /*nb_rshift*/
4252 long_and, /*nb_and*/
4253 long_xor, /*nb_xor*/
4254 long_or, /*nb_or*/
4255 long_coerce, /*nb_coerce*/
4256 long_int, /*nb_int*/
4257 long_long, /*nb_long*/
4258 long_float, /*nb_float*/
4259 long_oct, /*nb_oct*/
4260 long_hex, /*nb_hex*/
4261 0, /* nb_inplace_add */
4262 0, /* nb_inplace_subtract */
4263 0, /* nb_inplace_multiply */
4264 0, /* nb_inplace_divide */
4265 0, /* nb_inplace_remainder */
4266 0, /* nb_inplace_power */
4267 0, /* nb_inplace_lshift */
4268 0, /* nb_inplace_rshift */
4269 0, /* nb_inplace_and */
4270 0, /* nb_inplace_xor */
4271 0, /* nb_inplace_or */
4272 long_div, /* nb_floor_divide */
4273 long_true_divide, /* nb_true_divide */
4274 0, /* nb_inplace_floor_divide */
4275 0, /* nb_inplace_true_divide */
4276 long_long, /* nb_index */
4277 };
4278
4279 PyTypeObject PyLong_Type = {
4280 PyObject_HEAD_INIT(&PyType_Type)
4281 0, /* ob_size */
4282 "long", /* tp_name */
4283 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4284 sizeof(digit), /* tp_itemsize */
4285 long_dealloc, /* tp_dealloc */
4286 0, /* tp_print */
4287 0, /* tp_getattr */
4288 0, /* tp_setattr */
4289 (cmpfunc)long_compare, /* tp_compare */
4290 long_repr, /* tp_repr */
4291 &long_as_number, /* tp_as_number */
4292 0, /* tp_as_sequence */
4293 0, /* tp_as_mapping */
4294 (hashfunc)long_hash, /* tp_hash */
4295 0, /* tp_call */
4296 long_str, /* tp_str */
4297 PyObject_GenericGetAttr, /* tp_getattro */
4298 0, /* tp_setattro */
4299 0, /* tp_as_buffer */
4300 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4301 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4302 long_doc, /* tp_doc */
4303 0, /* tp_traverse */
4304 0, /* tp_clear */
4305 0, /* tp_richcompare */
4306 0, /* tp_weaklistoffset */
4307 0, /* tp_iter */
4308 0, /* tp_iternext */
4309 long_methods, /* tp_methods */
4310 0, /* tp_members */
4311 long_getset, /* tp_getset */
4312 0, /* tp_base */
4313 0, /* tp_dict */
4314 0, /* tp_descr_get */
4315 0, /* tp_descr_set */
4316 0, /* tp_dictoffset */
4317 0, /* tp_init */
4318 0, /* tp_alloc */
4319 long_new, /* tp_new */
4320 PyObject_Del, /* tp_free */
4321 };
4322
4323 static PyTypeObject Long_InfoType;
4324
4325 PyDoc_STRVAR(long_info__doc__,
4326 "sys.long_info\n\
4327 \n\
4328 A struct sequence that holds information about Python's\n\
4329 internal representation of integers. The attributes are read only.");
4330
4331 static PyStructSequence_Field long_info_fields[] = {
4332 {"bits_per_digit", "size of a digit in bits"},
4333 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
4334 {NULL, NULL}
4335 };
4336
4337 static PyStructSequence_Desc long_info_desc = {
4338 "sys.long_info", /* name */
4339 long_info__doc__, /* doc */
4340 long_info_fields, /* fields */
4341 2 /* number of fields */
4342 };
4343
4344 PyObject *
4345 PyLong_GetInfo(void)
4346 {
4347 PyObject* long_info;
4348 int field = 0;
4349 long_info = PyStructSequence_New(&Long_InfoType);
4350 if (long_info == NULL)
4351 return NULL;
4352 PyStructSequence_SET_ITEM(long_info, field++,
4353 PyInt_FromLong(PyLong_SHIFT));
4354 PyStructSequence_SET_ITEM(long_info, field++,
4355 PyInt_FromLong(sizeof(digit)));
4356 if (PyErr_Occurred()) {
4357 Py_CLEAR(long_info);
4358 return NULL;
4359 }
4360 return long_info;
4361 }
4362
4363 int
4364 _PyLong_Init(void)
4365 {
4366 /* initialize long_info */
4367 if (Long_InfoType.tp_name == 0)
4368 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
4369 return 1;
4370 }