3 /* Long (arbitrary precision) integer object implementation */
5 /* XXX The functional organization of this file is terrible */
8 #include "longintrepr.h"
12 /* For long multiplication, use the O(N**2) school algorithm unless
13 * both operands contain more than KARATSUBA_CUTOFF digits (this
14 * being an internal Python long digit, in base PyLong_BASE).
16 #define KARATSUBA_CUTOFF 70
17 #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
19 /* For exponentiation, use the binary left-to-right algorithm
20 * unless the exponent contains more than FIVEARY_CUTOFF digits.
21 * In that case, do 5 bits at a time. The potential drawback is that
22 * a table of 2**5 intermediate results is computed.
24 #define FIVEARY_CUTOFF 8
26 #define ABS(x) ((x) < 0 ? -(x) : (x))
30 #define MAX(x, y) ((x) < (y) ? (y) : (x))
31 #define MIN(x, y) ((x) > (y) ? (y) : (x))
34 static PyLongObject
*long_normalize(PyLongObject
*);
35 static PyLongObject
*mul1(PyLongObject
*, wdigit
);
36 static PyLongObject
*muladd1(PyLongObject
*, wdigit
, wdigit
);
37 static PyLongObject
*divrem1(PyLongObject
*, digit
, digit
*);
39 #define SIGCHECK(PyTryBlock) \
40 if (--_Py_Ticker < 0) { \
41 _Py_Ticker = _Py_CheckInterval; \
42 if (PyErr_CheckSignals()) PyTryBlock \
45 /* Normalize (remove leading zeros from) a long int object.
46 Doesn't attempt to free the storage--in most cases, due to the nature
47 of the algorithms used, this could save at most be one word anyway. */
50 long_normalize(register PyLongObject
*v
)
52 Py_ssize_t j
= ABS(Py_SIZE(v
));
55 while (i
> 0 && v
->ob_digit
[i
-1] == 0)
58 Py_SIZE(v
) = (Py_SIZE(v
) < 0) ? -(i
) : i
;
62 /* Allocate a new long int object with size digits.
63 Return NULL and set exception if we run out of memory. */
66 _PyLong_New(Py_ssize_t size
)
68 if (size
> PY_SSIZE_T_MAX
) {
72 /* coverity[ampersand_in_size] */
73 /* XXX(nnorwitz): This can overflow --
74 PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
75 return PyObject_NEW_VAR(PyLongObject
, &PyLong_Type
, size
);
79 _PyLong_Copy(PyLongObject
*src
)
88 result
= _PyLong_New(i
);
90 result
->ob_size
= src
->ob_size
;
92 result
->ob_digit
[i
] = src
->ob_digit
[i
];
94 return (PyObject
*)result
;
97 /* Create a new long int object from a C long int */
100 PyLong_FromLong(long ival
)
103 unsigned long abs_ival
;
104 unsigned long t
; /* unsigned so >> doesn't propagate sign bit */
109 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
110 ANSI C says that the result of -ival is undefined when ival
111 == LONG_MIN. Hence the following workaround. */
112 abs_ival
= (unsigned long)(-1-ival
) + 1;
116 abs_ival
= (unsigned long)ival
;
119 /* Count the number of Python digits.
120 We used to pick 5 ("big enough for anything"), but that's a
121 waste of time and space given that 5*15 = 75 bits are rarely
128 v
= _PyLong_New(ndigits
);
130 digit
*p
= v
->ob_digit
;
131 v
->ob_size
= negative
? -ndigits
: ndigits
;
134 *p
++ = (digit
)(t
& PyLong_MASK
);
138 return (PyObject
*)v
;
141 /* Create a new long int object from a C unsigned long int */
144 PyLong_FromUnsignedLong(unsigned long ival
)
150 /* Count the number of Python digits. */
151 t
= (unsigned long)ival
;
156 v
= _PyLong_New(ndigits
);
158 digit
*p
= v
->ob_digit
;
159 Py_SIZE(v
) = ndigits
;
161 *p
++ = (digit
)(ival
& PyLong_MASK
);
162 ival
>>= PyLong_SHIFT
;
165 return (PyObject
*)v
;
168 /* Create a new long int object from a C double */
171 PyLong_FromDouble(double dval
)
175 int i
, ndig
, expo
, neg
;
177 if (Py_IS_INFINITY(dval
)) {
178 PyErr_SetString(PyExc_OverflowError
,
179 "cannot convert float infinity to integer");
182 if (Py_IS_NAN(dval
)) {
183 PyErr_SetString(PyExc_ValueError
,
184 "cannot convert float NaN to integer");
191 frac
= frexp(dval
, &expo
); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
193 return PyLong_FromLong(0L);
194 ndig
= (expo
-1) / PyLong_SHIFT
+ 1; /* Number of 'digits' in result */
195 v
= _PyLong_New(ndig
);
198 frac
= ldexp(frac
, (expo
-1) % PyLong_SHIFT
+ 1);
199 for (i
= ndig
; --i
>= 0; ) {
200 long bits
= (long)frac
;
201 v
->ob_digit
[i
] = (digit
) bits
;
202 frac
= frac
- (double)bits
;
203 frac
= ldexp(frac
, PyLong_SHIFT
);
206 Py_SIZE(v
) = -(Py_SIZE(v
));
207 return (PyObject
*)v
;
210 /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
211 * anything about what happens when a signed integer operation overflows,
212 * and some compilers think they're doing you a favor by being "clever"
213 * then. The bit pattern for the largest postive signed long is
214 * (unsigned long)LONG_MAX, and for the smallest negative signed long
215 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
216 * However, some other compilers warn about applying unary minus to an
217 * unsigned operand. Hence the weird "0-".
219 #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
220 #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
222 /* Get a C long int from a long int object.
223 Returns -1 and sets an error condition if overflow occurs. */
226 PyLong_AsLong(PyObject
*vv
)
228 /* This version by Tim Peters */
229 register PyLongObject
*v
;
230 unsigned long x
, prev
;
234 if (vv
== NULL
|| !PyLong_Check(vv
)) {
235 if (vv
!= NULL
&& PyInt_Check(vv
))
236 return PyInt_AsLong(vv
);
237 PyErr_BadInternalCall();
240 v
= (PyLongObject
*)vv
;
250 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
251 if ((x
>> PyLong_SHIFT
) != prev
)
254 /* Haven't lost any bits, but casting to long requires extra care
255 * (see comment above).
257 if (x
<= (unsigned long)LONG_MAX
) {
258 return (long)x
* sign
;
260 else if (sign
< 0 && x
== PY_ABS_LONG_MIN
) {
266 PyErr_SetString(PyExc_OverflowError
,
267 "long int too large to convert to int");
271 /* Get a Py_ssize_t from a long int object.
272 Returns -1 and sets an error condition if overflow occurs. */
275 PyLong_AsSsize_t(PyObject
*vv
) {
276 register PyLongObject
*v
;
281 if (vv
== NULL
|| !PyLong_Check(vv
)) {
282 PyErr_BadInternalCall();
285 v
= (PyLongObject
*)vv
;
295 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
296 if ((x
>> PyLong_SHIFT
) != prev
)
299 /* Haven't lost any bits, but casting to a signed type requires
300 * extra care (see comment above).
302 if (x
<= (size_t)PY_SSIZE_T_MAX
) {
303 return (Py_ssize_t
)x
* sign
;
305 else if (sign
< 0 && x
== PY_ABS_SSIZE_T_MIN
) {
306 return PY_SSIZE_T_MIN
;
311 PyErr_SetString(PyExc_OverflowError
,
312 "long int too large to convert to int");
316 /* Get a C unsigned long int from a long int object.
317 Returns -1 and sets an error condition if overflow occurs. */
320 PyLong_AsUnsignedLong(PyObject
*vv
)
322 register PyLongObject
*v
;
323 unsigned long x
, prev
;
326 if (vv
== NULL
|| !PyLong_Check(vv
)) {
327 if (vv
!= NULL
&& PyInt_Check(vv
)) {
328 long val
= PyInt_AsLong(vv
);
330 PyErr_SetString(PyExc_OverflowError
,
331 "can't convert negative value to unsigned long");
332 return (unsigned long) -1;
336 PyErr_BadInternalCall();
337 return (unsigned long) -1;
339 v
= (PyLongObject
*)vv
;
343 PyErr_SetString(PyExc_OverflowError
,
344 "can't convert negative value to unsigned long");
345 return (unsigned long) -1;
349 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
350 if ((x
>> PyLong_SHIFT
) != prev
) {
351 PyErr_SetString(PyExc_OverflowError
,
352 "long int too large to convert");
353 return (unsigned long) -1;
359 /* Get a C unsigned long int from a long int object, ignoring the high bits.
360 Returns -1 and sets an error condition if an error occurs. */
363 PyLong_AsUnsignedLongMask(PyObject
*vv
)
365 register PyLongObject
*v
;
370 if (vv
== NULL
|| !PyLong_Check(vv
)) {
371 if (vv
!= NULL
&& PyInt_Check(vv
))
372 return PyInt_AsUnsignedLongMask(vv
);
373 PyErr_BadInternalCall();
374 return (unsigned long) -1;
376 v
= (PyLongObject
*)vv
;
385 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
391 _PyLong_Sign(PyObject
*vv
)
393 PyLongObject
*v
= (PyLongObject
*)vv
;
396 assert(PyLong_Check(v
));
398 return Py_SIZE(v
) == 0 ? 0 : (Py_SIZE(v
) < 0 ? -1 : 1);
402 _PyLong_NumBits(PyObject
*vv
)
404 PyLongObject
*v
= (PyLongObject
*)vv
;
409 assert(PyLong_Check(v
));
410 ndigits
= ABS(Py_SIZE(v
));
411 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
413 digit msd
= v
->ob_digit
[ndigits
- 1];
415 result
= (ndigits
- 1) * PyLong_SHIFT
;
416 if (result
/ PyLong_SHIFT
!= (size_t)(ndigits
- 1))
428 PyErr_SetString(PyExc_OverflowError
, "long has too many bits "
429 "to express in a platform size_t");
434 _PyLong_FromByteArray(const unsigned char* bytes
, size_t n
,
435 int little_endian
, int is_signed
)
437 const unsigned char* pstartbyte
;/* LSB of bytes */
438 int incr
; /* direction to move pstartbyte */
439 const unsigned char* pendbyte
; /* MSB of bytes */
440 size_t numsignificantbytes
; /* number of bytes that matter */
441 size_t ndigits
; /* number of Python long digits */
442 PyLongObject
* v
; /* result */
443 int idigit
= 0; /* next free index in v->ob_digit */
446 return PyLong_FromLong(0L);
450 pendbyte
= bytes
+ n
- 1;
454 pstartbyte
= bytes
+ n
- 1;
460 is_signed
= *pendbyte
>= 0x80;
462 /* Compute numsignificantbytes. This consists of finding the most
463 significant byte. Leading 0 bytes are insignficant if the number
464 is positive, and leading 0xff bytes if negative. */
467 const unsigned char* p
= pendbyte
;
468 const int pincr
= -incr
; /* search MSB to LSB */
469 const unsigned char insignficant
= is_signed
? 0xff : 0x00;
471 for (i
= 0; i
< n
; ++i
, p
+= pincr
) {
472 if (*p
!= insignficant
)
475 numsignificantbytes
= n
- i
;
476 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
477 actually has 2 significant bytes. OTOH, 0xff0001 ==
478 -0x00ffff, so we wouldn't *need* to bump it there; but we
479 do for 0xffff = -0x0001. To be safe without bothering to
480 check every case, bump it regardless. */
481 if (is_signed
&& numsignificantbytes
< n
)
482 ++numsignificantbytes
;
485 /* How many Python long digits do we need? We have
486 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
487 bits, so it's the ceiling of the quotient. */
488 ndigits
= (numsignificantbytes
* 8 + PyLong_SHIFT
- 1) / PyLong_SHIFT
;
489 if (ndigits
> (size_t)INT_MAX
)
490 return PyErr_NoMemory();
491 v
= _PyLong_New((int)ndigits
);
495 /* Copy the bits over. The tricky parts are computing 2's-comp on
496 the fly for signed numbers, and dealing with the mismatch between
497 8-bit bytes and (probably) 15-bit Python digits.*/
500 twodigits carry
= 1; /* for 2's-comp calculation */
501 twodigits accum
= 0; /* sliding register */
502 unsigned int accumbits
= 0; /* number of bits in accum */
503 const unsigned char* p
= pstartbyte
;
505 for (i
= 0; i
< numsignificantbytes
; ++i
, p
+= incr
) {
506 twodigits thisbyte
= *p
;
507 /* Compute correction for 2's comp, if needed. */
509 thisbyte
= (0xff ^ thisbyte
) + carry
;
510 carry
= thisbyte
>> 8;
513 /* Because we're going LSB to MSB, thisbyte is
514 more significant than what's already in accum,
515 so needs to be prepended to accum. */
516 accum
|= thisbyte
<< accumbits
;
518 if (accumbits
>= PyLong_SHIFT
) {
519 /* There's enough to fill a Python digit. */
520 assert(idigit
< (int)ndigits
);
521 v
->ob_digit
[idigit
] = (digit
)(accum
& PyLong_MASK
);
523 accum
>>= PyLong_SHIFT
;
524 accumbits
-= PyLong_SHIFT
;
525 assert(accumbits
< PyLong_SHIFT
);
528 assert(accumbits
< PyLong_SHIFT
);
530 assert(idigit
< (int)ndigits
);
531 v
->ob_digit
[idigit
] = (digit
)accum
;
536 Py_SIZE(v
) = is_signed
? -idigit
: idigit
;
537 return (PyObject
*)long_normalize(v
);
541 _PyLong_AsByteArray(PyLongObject
* v
,
542 unsigned char* bytes
, size_t n
,
543 int little_endian
, int is_signed
)
545 int i
; /* index into v->ob_digit */
546 Py_ssize_t ndigits
; /* |v->ob_size| */
547 twodigits accum
; /* sliding register */
548 unsigned int accumbits
; /* # bits in accum */
549 int do_twos_comp
; /* store 2's-comp? is_signed and v < 0 */
550 twodigits carry
; /* for computing 2's-comp */
551 size_t j
; /* # bytes filled */
552 unsigned char* p
; /* pointer to next byte in bytes */
553 int pincr
; /* direction to move p */
555 assert(v
!= NULL
&& PyLong_Check(v
));
557 if (Py_SIZE(v
) < 0) {
558 ndigits
= -(Py_SIZE(v
));
560 PyErr_SetString(PyExc_TypeError
,
561 "can't convert negative long to unsigned");
567 ndigits
= Py_SIZE(v
);
580 /* Copy over all the Python digits.
581 It's crucial that every Python digit except for the MSD contribute
582 exactly PyLong_SHIFT bits to the total, so first assert that the long is
584 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
588 carry
= do_twos_comp
? 1 : 0;
589 for (i
= 0; i
< ndigits
; ++i
) {
590 twodigits thisdigit
= v
->ob_digit
[i
];
592 thisdigit
= (thisdigit
^ PyLong_MASK
) + carry
;
593 carry
= thisdigit
>> PyLong_SHIFT
;
594 thisdigit
&= PyLong_MASK
;
596 /* Because we're going LSB to MSB, thisdigit is more
597 significant than what's already in accum, so needs to be
598 prepended to accum. */
599 accum
|= thisdigit
<< accumbits
;
600 accumbits
+= PyLong_SHIFT
;
602 /* The most-significant digit may be (probably is) at least
604 if (i
== ndigits
- 1) {
605 /* Count # of sign bits -- they needn't be stored,
606 * although for signed conversion we need later to
607 * make sure at least one sign bit gets stored.
608 * First shift conceptual sign bit to real sign bit.
610 stwodigits s
= (stwodigits
)(thisdigit
<<
611 (8*sizeof(stwodigits
) - PyLong_SHIFT
));
612 unsigned int nsignbits
= 0;
613 while ((s
< 0) == do_twos_comp
&& nsignbits
< PyLong_SHIFT
) {
617 accumbits
-= nsignbits
;
620 /* Store as many bytes as possible. */
621 while (accumbits
>= 8) {
625 *p
= (unsigned char)(accum
& 0xff);
632 /* Store the straggler (if any). */
633 assert(accumbits
< 8);
634 assert(carry
== 0); /* else do_twos_comp and *every* digit was 0 */
640 /* Fill leading bits of the byte with sign bits
641 (appropriately pretending that the long had an
642 infinite supply of sign bits). */
643 accum
|= (~(twodigits
)0) << accumbits
;
645 *p
= (unsigned char)(accum
& 0xff);
648 else if (j
== n
&& n
> 0 && is_signed
) {
649 /* The main loop filled the byte array exactly, so the code
650 just above didn't get to ensure there's a sign bit, and the
651 loop below wouldn't add one either. Make sure a sign bit
653 unsigned char msb
= *(p
- pincr
);
654 int sign_bit_set
= msb
>= 0x80;
655 assert(accumbits
== 0);
656 if (sign_bit_set
== do_twos_comp
)
662 /* Fill remaining bytes with copies of the sign bit. */
664 unsigned char signbyte
= do_twos_comp
? 0xffU
: 0U;
665 for ( ; j
< n
; ++j
, p
+= pincr
)
672 PyErr_SetString(PyExc_OverflowError
, "long too big to convert");
678 _PyLong_AsScaledDouble(PyObject
*vv
, int *exponent
)
680 /* NBITS_WANTED should be > the number of bits in a double's precision,
681 but small enough so that 2**NBITS_WANTED is within the normal double
682 range. nbitsneeded is set to 1 less than that because the most-significant
683 Python digit contains at least 1 significant bit, but we don't want to
684 bother counting them (catering to the worst case cheaply).
686 57 is one more than VAX-D double precision; I (Tim) don't know of a double
687 format with more precision than that; it's 1 larger so that we add in at
688 least one round bit to stand in for the ignored least-significant bits.
690 #define NBITS_WANTED 57
693 const double multiplier
= (double)(1L << PyLong_SHIFT
);
698 if (vv
== NULL
|| !PyLong_Check(vv
)) {
699 PyErr_BadInternalCall();
702 v
= (PyLongObject
*)vv
;
714 x
= (double)v
->ob_digit
[i
];
715 nbitsneeded
= NBITS_WANTED
- 1;
716 /* Invariant: i Python digits remain unaccounted for. */
717 while (i
> 0 && nbitsneeded
> 0) {
719 x
= x
* multiplier
+ (double)v
->ob_digit
[i
];
720 nbitsneeded
-= PyLong_SHIFT
;
722 /* There are i digits we didn't shift in. Pretending they're all
723 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
730 /* Get a C double from a long int object. */
733 PyLong_AsDouble(PyObject
*vv
)
738 if (vv
== NULL
|| !PyLong_Check(vv
)) {
739 PyErr_BadInternalCall();
742 x
= _PyLong_AsScaledDouble(vv
, &e
);
743 if (x
== -1.0 && PyErr_Occurred())
745 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
746 set correctly after a successful _PyLong_AsScaledDouble() call */
748 if (e
> INT_MAX
/ PyLong_SHIFT
)
751 x
= ldexp(x
, e
* PyLong_SHIFT
);
752 if (Py_OVERFLOWED(x
))
757 PyErr_SetString(PyExc_OverflowError
,
758 "long int too large to convert to float");
762 /* Create a new long (or int) object from a C pointer */
765 PyLong_FromVoidPtr(void *p
)
767 #if SIZEOF_VOID_P <= SIZEOF_LONG
769 return PyLong_FromUnsignedLong((unsigned long)p
);
770 return PyInt_FromLong((long)p
);
773 #ifndef HAVE_LONG_LONG
774 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
776 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
777 # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
779 /* optimize null pointers */
781 return PyInt_FromLong(0);
782 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG
)p
);
784 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
787 /* Get a C pointer from a long object (or an int object in some cases) */
790 PyLong_AsVoidPtr(PyObject
*vv
)
792 /* This function will allow int or long objects. If vv is neither,
793 then the PyLong_AsLong*() functions will raise the exception:
794 PyExc_SystemError, "bad argument to internal function"
796 #if SIZEOF_VOID_P <= SIZEOF_LONG
800 x
= PyInt_AS_LONG(vv
);
801 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
802 x
= PyLong_AsLong(vv
);
804 x
= PyLong_AsUnsignedLong(vv
);
807 #ifndef HAVE_LONG_LONG
808 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
810 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
811 # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
816 x
= PyInt_AS_LONG(vv
);
817 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
818 x
= PyLong_AsLongLong(vv
);
820 x
= PyLong_AsUnsignedLongLong(vv
);
822 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
824 if (x
== -1 && PyErr_Occurred())
829 #ifdef HAVE_LONG_LONG
831 /* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
832 * rewritten to use the newer PyLong_{As,From}ByteArray API.
835 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
837 /* Create a new long int object from a C PY_LONG_LONG int. */
840 PyLong_FromLongLong(PY_LONG_LONG ival
)
843 unsigned PY_LONG_LONG abs_ival
;
844 unsigned PY_LONG_LONG t
; /* unsigned so >> doesn't propagate sign bit */
849 /* avoid signed overflow on negation; see comments
850 in PyLong_FromLong above. */
851 abs_ival
= (unsigned PY_LONG_LONG
)(-1-ival
) + 1;
855 abs_ival
= (unsigned PY_LONG_LONG
)ival
;
858 /* Count the number of Python digits.
859 We used to pick 5 ("big enough for anything"), but that's a
860 waste of time and space given that 5*15 = 75 bits are rarely
867 v
= _PyLong_New(ndigits
);
869 digit
*p
= v
->ob_digit
;
870 Py_SIZE(v
) = negative
? -ndigits
: ndigits
;
873 *p
++ = (digit
)(t
& PyLong_MASK
);
877 return (PyObject
*)v
;
880 /* Create a new long int object from a C unsigned PY_LONG_LONG int. */
883 PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival
)
886 unsigned PY_LONG_LONG t
;
889 /* Count the number of Python digits. */
890 t
= (unsigned PY_LONG_LONG
)ival
;
895 v
= _PyLong_New(ndigits
);
897 digit
*p
= v
->ob_digit
;
898 Py_SIZE(v
) = ndigits
;
900 *p
++ = (digit
)(ival
& PyLong_MASK
);
901 ival
>>= PyLong_SHIFT
;
904 return (PyObject
*)v
;
907 /* Create a new long int object from a C Py_ssize_t. */
910 PyLong_FromSsize_t(Py_ssize_t ival
)
912 Py_ssize_t bytes
= ival
;
914 return _PyLong_FromByteArray(
915 (unsigned char *)&bytes
,
916 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 1);
919 /* Create a new long int object from a C size_t. */
922 PyLong_FromSize_t(size_t ival
)
926 return _PyLong_FromByteArray(
927 (unsigned char *)&bytes
,
928 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 0);
931 /* Get a C PY_LONG_LONG int from a long int object.
932 Return -1 and set an error if overflow occurs. */
935 PyLong_AsLongLong(PyObject
*vv
)
942 PyErr_BadInternalCall();
945 if (!PyLong_Check(vv
)) {
949 return (PY_LONG_LONG
)PyInt_AsLong(vv
);
950 if ((nb
= vv
->ob_type
->tp_as_number
) == NULL
||
951 nb
->nb_int
== NULL
) {
952 PyErr_SetString(PyExc_TypeError
, "an integer is required");
955 io
= (*nb
->nb_int
) (vv
);
958 if (PyInt_Check(io
)) {
959 bytes
= PyInt_AsLong(io
);
963 if (PyLong_Check(io
)) {
964 bytes
= PyLong_AsLongLong(io
);
969 PyErr_SetString(PyExc_TypeError
, "integer conversion failed");
973 res
= _PyLong_AsByteArray(
974 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
975 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
977 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
979 return (PY_LONG_LONG
)-1;
984 /* Get a C unsigned PY_LONG_LONG int from a long int object.
985 Return -1 and set an error if overflow occurs. */
987 unsigned PY_LONG_LONG
988 PyLong_AsUnsignedLongLong(PyObject
*vv
)
990 unsigned PY_LONG_LONG bytes
;
994 if (vv
== NULL
|| !PyLong_Check(vv
)) {
995 PyErr_BadInternalCall();
996 return (unsigned PY_LONG_LONG
)-1;
999 res
= _PyLong_AsByteArray(
1000 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
1001 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
1003 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1005 return (unsigned PY_LONG_LONG
)res
;
1010 /* Get a C unsigned long int from a long int object, ignoring the high bits.
1011 Returns -1 and sets an error condition if an error occurs. */
1013 unsigned PY_LONG_LONG
1014 PyLong_AsUnsignedLongLongMask(PyObject
*vv
)
1016 register PyLongObject
*v
;
1017 unsigned PY_LONG_LONG x
;
1021 if (vv
== NULL
|| !PyLong_Check(vv
)) {
1022 PyErr_BadInternalCall();
1023 return (unsigned long) -1;
1025 v
= (PyLongObject
*)vv
;
1034 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
1038 #undef IS_LITTLE_ENDIAN
1040 #endif /* HAVE_LONG_LONG */
1044 convert_binop(PyObject
*v
, PyObject
*w
, PyLongObject
**a
, PyLongObject
**b
) {
1045 if (PyLong_Check(v
)) {
1046 *a
= (PyLongObject
*) v
;
1049 else if (PyInt_Check(v
)) {
1050 *a
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(v
));
1055 if (PyLong_Check(w
)) {
1056 *b
= (PyLongObject
*) w
;
1059 else if (PyInt_Check(w
)) {
1060 *b
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(w
));
1069 #define CONVERT_BINOP(v, w, a, b) \
1070 if (!convert_binop(v, w, a, b)) { \
1071 Py_INCREF(Py_NotImplemented); \
1072 return Py_NotImplemented; \
1075 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1076 * is modified in place, by adding y to it. Carries are propagated as far as
1077 * x[m-1], and the remaining carry (0 or 1) is returned.
1080 v_iadd(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1086 for (i
= 0; i
< n
; ++i
) {
1087 carry
+= x
[i
] + y
[i
];
1088 x
[i
] = carry
& PyLong_MASK
;
1089 carry
>>= PyLong_SHIFT
;
1090 assert((carry
& 1) == carry
);
1092 for (; carry
&& i
< m
; ++i
) {
1094 x
[i
] = carry
& PyLong_MASK
;
1095 carry
>>= PyLong_SHIFT
;
1096 assert((carry
& 1) == carry
);
1101 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1102 * is modified in place, by subtracting y from it. Borrows are propagated as
1103 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1106 v_isub(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1112 for (i
= 0; i
< n
; ++i
) {
1113 borrow
= x
[i
] - y
[i
] - borrow
;
1114 x
[i
] = borrow
& PyLong_MASK
;
1115 borrow
>>= PyLong_SHIFT
;
1116 borrow
&= 1; /* keep only 1 sign bit */
1118 for (; borrow
&& i
< m
; ++i
) {
1119 borrow
= x
[i
] - borrow
;
1120 x
[i
] = borrow
& PyLong_MASK
;
1121 borrow
>>= PyLong_SHIFT
;
1127 /* Multiply by a single digit, ignoring the sign. */
1129 static PyLongObject
*
1130 mul1(PyLongObject
*a
, wdigit n
)
1132 return muladd1(a
, n
, (digit
)0);
1135 /* Multiply by a single digit and add a single digit, ignoring the sign. */
1137 static PyLongObject
*
1138 muladd1(PyLongObject
*a
, wdigit n
, wdigit extra
)
1140 Py_ssize_t size_a
= ABS(Py_SIZE(a
));
1141 PyLongObject
*z
= _PyLong_New(size_a
+1);
1142 twodigits carry
= extra
;
1147 for (i
= 0; i
< size_a
; ++i
) {
1148 carry
+= (twodigits
)a
->ob_digit
[i
] * n
;
1149 z
->ob_digit
[i
] = (digit
) (carry
& PyLong_MASK
);
1150 carry
>>= PyLong_SHIFT
;
1152 z
->ob_digit
[i
] = (digit
) carry
;
1153 return long_normalize(z
);
1156 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1157 in pout, and returning the remainder. pin and pout point at the LSD.
1158 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1159 _PyLong_Format, but that should be done with great care since longs are
1163 inplace_divrem1(digit
*pout
, digit
*pin
, Py_ssize_t size
, digit n
)
1167 assert(n
> 0 && n
<= PyLong_MASK
);
1170 while (--size
>= 0) {
1172 rem
= (rem
<< PyLong_SHIFT
) + *--pin
;
1173 *--pout
= hi
= (digit
)(rem
/ n
);
1179 /* Divide a long integer by a digit, returning both the quotient
1180 (as function result) and the remainder (through *prem).
1181 The sign of a is ignored; n should not be zero. */
1183 static PyLongObject
*
1184 divrem1(PyLongObject
*a
, digit n
, digit
*prem
)
1186 const Py_ssize_t size
= ABS(Py_SIZE(a
));
1189 assert(n
> 0 && n
<= PyLong_MASK
);
1190 z
= _PyLong_New(size
);
1193 *prem
= inplace_divrem1(z
->ob_digit
, a
->ob_digit
, size
, n
);
1194 return long_normalize(z
);
1197 /* Convert the long to a string object with given base,
1198 appending a base prefix of 0[box] if base is 2, 8 or 16.
1199 Add a trailing "L" if addL is non-zero.
1200 If newstyle is zero, then use the pre-2.6 behavior of octal having
1201 a leading "0", instead of the prefix "0o" */
1202 PyAPI_FUNC(PyObject
*)
1203 _PyLong_Format(PyObject
*aa
, int base
, int addL
, int newstyle
)
1205 register PyLongObject
*a
= (PyLongObject
*)aa
;
1206 PyStringObject
*str
;
1207 Py_ssize_t i
, j
, sz
;
1213 if (a
== NULL
|| !PyLong_Check(a
)) {
1214 PyErr_BadInternalCall();
1217 assert(base
>= 2 && base
<= 36);
1218 size_a
= ABS(Py_SIZE(a
));
1220 /* Compute a rough upper bound for the length of the string */
1227 i
= 5 + (addL
? 1 : 0);
1228 j
= size_a
*PyLong_SHIFT
+ bits
-1;
1230 if (j
/ PyLong_SHIFT
< size_a
|| sz
< i
) {
1231 PyErr_SetString(PyExc_OverflowError
,
1232 "long is too large to format");
1235 str
= (PyStringObject
*) PyString_FromStringAndSize((char *)0, sz
);
1238 p
= PyString_AS_STRING(str
) + sz
;
1245 if (a
->ob_size
== 0) {
1248 else if ((base
& (base
- 1)) == 0) {
1249 /* JRH: special case for power-of-2 bases */
1250 twodigits accum
= 0;
1251 int accumbits
= 0; /* # of bits in accum */
1252 int basebits
= 1; /* # of bits in base-1 */
1254 while ((i
>>= 1) > 1)
1257 for (i
= 0; i
< size_a
; ++i
) {
1258 accum
|= (twodigits
)a
->ob_digit
[i
] << accumbits
;
1259 accumbits
+= PyLong_SHIFT
;
1260 assert(accumbits
>= basebits
);
1262 char cdigit
= (char)(accum
& (base
- 1));
1263 cdigit
+= (cdigit
< 10) ? '0' : 'a'-10;
1264 assert(p
> PyString_AS_STRING(str
));
1266 accumbits
-= basebits
;
1268 } while (i
< size_a
-1 ? accumbits
>= basebits
:
1273 /* Not 0, and base not a power of 2. Divide repeatedly by
1274 base, but for speed use the highest power of base that
1276 Py_ssize_t size
= size_a
;
1277 digit
*pin
= a
->ob_digit
;
1278 PyLongObject
*scratch
;
1279 /* powbasw <- largest power of base that fits in a digit. */
1280 digit powbase
= base
; /* powbase == base ** power */
1283 unsigned long newpow
= powbase
* (unsigned long)base
;
1284 if (newpow
>> PyLong_SHIFT
) /* doesn't fit in a digit */
1286 powbase
= (digit
)newpow
;
1290 /* Get a scratch area for repeated division. */
1291 scratch
= _PyLong_New(size
);
1292 if (scratch
== NULL
) {
1297 /* Repeatedly divide by powbase. */
1299 int ntostore
= power
;
1300 digit rem
= inplace_divrem1(scratch
->ob_digit
,
1301 pin
, size
, powbase
);
1302 pin
= scratch
->ob_digit
; /* no need to use a again */
1303 if (pin
[size
- 1] == 0)
1311 /* Break rem into digits. */
1312 assert(ntostore
> 0);
1314 digit nextrem
= (digit
)(rem
/ base
);
1315 char c
= (char)(rem
- nextrem
* base
);
1316 assert(p
> PyString_AS_STRING(str
));
1317 c
+= (c
< 10) ? '0' : 'a'-10;
1321 /* Termination is a bit delicate: must not
1322 store leading zeroes, so must get out if
1323 remaining quotient and rem are both 0. */
1324 } while (ntostore
&& (size
|| rem
));
1325 } while (size
!= 0);
1333 else if (base
== 8) {
1342 else if (base
== 16) {
1346 else if (base
!= 10) {
1348 *--p
= '0' + base
%10;
1350 *--p
= '0' + base
/10;
1354 if (p
!= PyString_AS_STRING(str
)) {
1355 char *q
= PyString_AS_STRING(str
);
1358 } while ((*q
++ = *p
++) != '\0');
1360 _PyString_Resize((PyObject
**)&str
,
1361 (Py_ssize_t
) (q
- PyString_AS_STRING(str
)));
1363 return (PyObject
*)str
;
1366 /* Table of digit values for 8-bit string -> integer conversion.
1367 * '0' maps to 0, ..., '9' maps to 9.
1368 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1369 * All other indices map to 37.
1370 * Note that when converting a base B string, a char c is a legitimate
1371 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1373 int _PyLong_DigitValue
[256] = {
1374 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1375 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1376 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1377 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1378 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1379 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1380 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1381 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1382 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1383 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1384 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1385 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1386 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1387 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1388 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1389 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1392 /* *str points to the first digit in a string of base `base` digits. base
1393 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1394 * non-digit (which may be *str!). A normalized long is returned.
1395 * The point to this routine is that it takes time linear in the number of
1396 * string characters.
1398 static PyLongObject
*
1399 long_from_binary_base(char **str
, int base
)
1410 assert(base
>= 2 && base
<= 32 && (base
& (base
- 1)) == 0);
1412 for (bits_per_char
= -1; n
; ++bits_per_char
)
1414 /* n <- total # of bits needed, while setting p to end-of-string */
1416 while (_PyLong_DigitValue
[Py_CHARMASK(*p
)] < base
)
1419 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1420 n
= (p
- start
) * bits_per_char
+ PyLong_SHIFT
- 1;
1421 if (n
/ bits_per_char
< p
- start
) {
1422 PyErr_SetString(PyExc_ValueError
,
1423 "long string too large to convert");
1426 n
= n
/ PyLong_SHIFT
;
1430 /* Read string from right, and fill in long from left; i.e.,
1431 * from least to most significant in both.
1435 pdigit
= z
->ob_digit
;
1436 while (--p
>= start
) {
1437 int k
= _PyLong_DigitValue
[Py_CHARMASK(*p
)];
1438 assert(k
>= 0 && k
< base
);
1439 accum
|= (twodigits
)(k
<< bits_in_accum
);
1440 bits_in_accum
+= bits_per_char
;
1441 if (bits_in_accum
>= PyLong_SHIFT
) {
1442 *pdigit
++ = (digit
)(accum
& PyLong_MASK
);
1443 assert(pdigit
- z
->ob_digit
<= (int)n
);
1444 accum
>>= PyLong_SHIFT
;
1445 bits_in_accum
-= PyLong_SHIFT
;
1446 assert(bits_in_accum
< PyLong_SHIFT
);
1449 if (bits_in_accum
) {
1450 assert(bits_in_accum
<= PyLong_SHIFT
);
1451 *pdigit
++ = (digit
)accum
;
1452 assert(pdigit
- z
->ob_digit
<= (int)n
);
1454 while (pdigit
- z
->ob_digit
< n
)
1456 return long_normalize(z
);
1460 PyLong_FromString(char *str
, char **pend
, int base
)
1463 char *start
, *orig_str
= str
;
1465 PyObject
*strobj
, *strrepr
;
1468 if ((base
!= 0 && base
< 2) || base
> 36) {
1469 PyErr_SetString(PyExc_ValueError
,
1470 "long() arg 2 must be >= 2 and <= 36");
1473 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1477 else if (*str
== '-') {
1481 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1484 /* No base given. Deduce the base from the contents
1488 else if (str
[1] == 'x' || str
[1] == 'X')
1490 else if (str
[1] == 'o' || str
[1] == 'O')
1492 else if (str
[1] == 'b' || str
[1] == 'B')
1495 /* "old" (C-style) octal literal, still valid in
1496 2.x, although illegal in 3.x */
1499 /* Whether or not we were deducing the base, skip leading chars
1501 if (str
[0] == '0' &&
1502 ((base
== 16 && (str
[1] == 'x' || str
[1] == 'X')) ||
1503 (base
== 8 && (str
[1] == 'o' || str
[1] == 'O')) ||
1504 (base
== 2 && (str
[1] == 'b' || str
[1] == 'B'))))
1508 if ((base
& (base
- 1)) == 0)
1509 z
= long_from_binary_base(&str
, base
);
1512 Binary bases can be converted in time linear in the number of digits, because
1513 Python's representation base is binary. Other bases (including decimal!) use
1514 the simple quadratic-time algorithm below, complicated by some speed tricks.
1516 First some math: the largest integer that can be expressed in N base-B digits
1517 is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1518 case number of Python digits needed to hold it is the smallest integer n s.t.
1520 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1521 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1522 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
1524 The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
1525 this quickly. A Python long with that much space is reserved near the start,
1526 and the result is computed into it.
1528 The input string is actually treated as being in base base**i (i.e., i digits
1529 are processed at a time), where two more static arrays hold:
1531 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
1532 convmultmax_base[base] = base ** convwidth_base[base]
1534 The first of these is the largest i such that i consecutive input digits
1535 must fit in a single Python digit. The second is effectively the input
1536 base we're really using.
1538 Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1539 convmultmax_base[base], the result is "simply"
1541 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1543 where B = convmultmax_base[base].
1545 Error analysis: as above, the number of Python digits `n` needed is worst-
1548 n >= N * log(B)/log(PyLong_BASE)
1550 where `N` is the number of input digits in base `B`. This is computed via
1552 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1554 below. Two numeric concerns are how much space this can waste, and whether
1555 the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
1556 which is the default (and it's unlikely anyone changes that).
1558 Waste isn't a problem: provided the first input digit isn't 0, the difference
1559 between the worst-case input with N digits and the smallest input with N
1560 digits is about a factor of B, but B is small compared to PyLong_BASE so at most
1561 one allocated Python digit can remain unused on that count. If
1562 N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
1563 and adding 1 returns a result 1 larger than necessary. However, that can't
1564 happen: whenever B is a power of 2, long_from_binary_base() is called
1565 instead, and it's impossible for B**i to be an integer power of 2**15 when
1566 B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
1567 an exact integer when B is not a power of 2, since B**i has a prime factor
1568 other than 2 in that case, but (2**15)**j's only prime factor is 2).
1570 The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
1571 is a little bit larger than an exact integer, but due to roundoff errors (in
1572 computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
1573 yields a numeric result a little less than that integer. Unfortunately, "how
1574 close can a transcendental function get to an integer over some range?"
1575 questions are generally theoretically intractable. Computer analysis via
1576 continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
1577 fractions, giving a sequence i/j of "the best" rational approximations. Then
1578 j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
1579 we can get very close to being in trouble, but very rarely. For example,
1580 76573 is a denominator in one of the continued-fraction approximations to
1581 log(10)/log(2**15), and indeed:
1583 >>> log(10)/log(2**15)*76573
1586 is very close to an integer. If we were working with IEEE single-precision,
1587 rounding errors could kill us. Finding worst cases in IEEE double-precision
1588 requires better-than-double-precision log() functions, and Tim didn't bother.
1589 Instead the code checks to see whether the allocated space is enough as each
1590 new Python digit is added, and copies the whole thing to a larger long if not.
1591 This should happen extremely rarely, and in fact I don't have a test case
1592 that triggers it(!). Instead the code was tested by artificially allocating
1593 just 1 digit at the start, so that the copying code was exercised for every
1594 digit beyond the first.
1596 register twodigits c
; /* current input character */
1600 twodigits convmultmax
, convmult
;
1604 static double log_base_PyLong_BASE
[37] = {0.0e0
,};
1605 static int convwidth_base
[37] = {0,};
1606 static twodigits convmultmax_base
[37] = {0,};
1608 if (log_base_PyLong_BASE
[base
] == 0.0) {
1609 twodigits convmax
= base
;
1612 log_base_PyLong_BASE
[base
] = log((double)base
) /
1613 log((double)PyLong_BASE
);
1615 twodigits next
= convmax
* base
;
1616 if (next
> PyLong_BASE
)
1621 convmultmax_base
[base
] = convmax
;
1623 convwidth_base
[base
] = i
;
1626 /* Find length of the string of numeric characters. */
1628 while (_PyLong_DigitValue
[Py_CHARMASK(*scan
)] < base
)
1631 /* Create a long object that can contain the largest possible
1632 * integer with this base and length. Note that there's no
1633 * need to initialize z->ob_digit -- no slot is read up before
1634 * being stored into.
1636 size_z
= (Py_ssize_t
)((scan
- str
) * log_base_PyLong_BASE
[base
]) + 1;
1637 /* Uncomment next line to test exceedingly rare copy code */
1640 z
= _PyLong_New(size_z
);
1645 /* `convwidth` consecutive input digits are treated as a single
1646 * digit in base `convmultmax`.
1648 convwidth
= convwidth_base
[base
];
1649 convmultmax
= convmultmax_base
[base
];
1652 while (str
< scan
) {
1653 /* grab up to convwidth digits from the input string */
1654 c
= (digit
)_PyLong_DigitValue
[Py_CHARMASK(*str
++)];
1655 for (i
= 1; i
< convwidth
&& str
!= scan
; ++i
, ++str
) {
1656 c
= (twodigits
)(c
* base
+
1657 _PyLong_DigitValue
[Py_CHARMASK(*str
)]);
1658 assert(c
< PyLong_BASE
);
1661 convmult
= convmultmax
;
1662 /* Calculate the shift only if we couldn't get
1665 if (i
!= convwidth
) {
1671 /* Multiply z by convmult, and add c. */
1673 pzstop
= pz
+ Py_SIZE(z
);
1674 for (; pz
< pzstop
; ++pz
) {
1675 c
+= (twodigits
)*pz
* convmult
;
1676 *pz
= (digit
)(c
& PyLong_MASK
);
1679 /* carry off the current end? */
1681 assert(c
< PyLong_BASE
);
1682 if (Py_SIZE(z
) < size_z
) {
1688 /* Extremely rare. Get more space. */
1689 assert(Py_SIZE(z
) == size_z
);
1690 tmp
= _PyLong_New(size_z
+ 1);
1695 memcpy(tmp
->ob_digit
,
1697 sizeof(digit
) * size_z
);
1700 z
->ob_digit
[size_z
] = (digit
)c
;
1711 Py_SIZE(z
) = -(Py_SIZE(z
));
1712 if (*str
== 'L' || *str
== 'l')
1714 while (*str
&& isspace(Py_CHARMASK(*str
)))
1720 return (PyObject
*) z
;
1724 slen
= strlen(orig_str
) < 200 ? strlen(orig_str
) : 200;
1725 strobj
= PyString_FromStringAndSize(orig_str
, slen
);
1728 strrepr
= PyObject_Repr(strobj
);
1730 if (strrepr
== NULL
)
1732 PyErr_Format(PyExc_ValueError
,
1733 "invalid literal for long() with base %d: %s",
1734 base
, PyString_AS_STRING(strrepr
));
1739 #ifdef Py_USING_UNICODE
1741 PyLong_FromUnicode(Py_UNICODE
*u
, Py_ssize_t length
, int base
)
1744 char *buffer
= (char *)PyMem_MALLOC(length
+1);
1749 if (PyUnicode_EncodeDecimal(u
, length
, buffer
, NULL
)) {
1753 result
= PyLong_FromString(buffer
, NULL
, base
);
1760 static PyLongObject
*x_divrem
1761 (PyLongObject
*, PyLongObject
*, PyLongObject
**);
1762 static PyObject
*long_long(PyObject
*v
);
1763 static int long_divrem(PyLongObject
*, PyLongObject
*,
1764 PyLongObject
**, PyLongObject
**);
1766 /* Long division with remainder, top-level routine */
1769 long_divrem(PyLongObject
*a
, PyLongObject
*b
,
1770 PyLongObject
**pdiv
, PyLongObject
**prem
)
1772 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
1776 PyErr_SetString(PyExc_ZeroDivisionError
,
1777 "long division or modulo by zero");
1780 if (size_a
< size_b
||
1781 (size_a
== size_b
&&
1782 a
->ob_digit
[size_a
-1] < b
->ob_digit
[size_b
-1])) {
1784 *pdiv
= _PyLong_New(0);
1788 *prem
= (PyLongObject
*) a
;
1793 z
= divrem1(a
, b
->ob_digit
[0], &rem
);
1796 *prem
= (PyLongObject
*) PyLong_FromLong((long)rem
);
1797 if (*prem
== NULL
) {
1803 z
= x_divrem(a
, b
, prem
);
1808 The quotient z has the sign of a*b;
1809 the remainder r has the sign of a,
1811 if ((a
->ob_size
< 0) != (b
->ob_size
< 0))
1812 z
->ob_size
= -(z
->ob_size
);
1813 if (a
->ob_size
< 0 && (*prem
)->ob_size
!= 0)
1814 (*prem
)->ob_size
= -((*prem
)->ob_size
);
1819 /* Unsigned long division with remainder -- the algorithm */
1821 static PyLongObject
*
1822 x_divrem(PyLongObject
*v1
, PyLongObject
*w1
, PyLongObject
**prem
)
1824 Py_ssize_t size_v
= ABS(Py_SIZE(v1
)), size_w
= ABS(Py_SIZE(w1
));
1825 digit d
= (digit
) ((twodigits
)PyLong_BASE
/ (w1
->ob_digit
[size_w
-1] + 1));
1826 PyLongObject
*v
= mul1(v1
, d
);
1827 PyLongObject
*w
= mul1(w1
, d
);
1831 if (v
== NULL
|| w
== NULL
) {
1837 assert(size_v
>= size_w
&& size_w
> 1); /* Assert checks by div() */
1838 assert(Py_REFCNT(v
) == 1); /* Since v will be used as accumulator! */
1839 assert(size_w
== ABS(Py_SIZE(w
))); /* That's how d was calculated */
1841 size_v
= ABS(Py_SIZE(v
));
1842 k
= size_v
- size_w
;
1843 a
= _PyLong_New(k
+ 1);
1845 for (j
= size_v
; a
!= NULL
&& k
>= 0; --j
, --k
) {
1846 digit vj
= (j
>= size_v
) ? 0 : v
->ob_digit
[j
];
1848 stwodigits carry
= 0;
1856 if (vj
== w
->ob_digit
[size_w
-1])
1859 q
= (((twodigits
)vj
<< PyLong_SHIFT
) + v
->ob_digit
[j
-1]) /
1860 w
->ob_digit
[size_w
-1];
1862 while (w
->ob_digit
[size_w
-2]*q
>
1864 ((twodigits
)vj
<< PyLong_SHIFT
)
1866 - q
*w
->ob_digit
[size_w
-1]
1871 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1872 twodigits z
= w
->ob_digit
[i
] * q
;
1873 digit zz
= (digit
) (z
>> PyLong_SHIFT
);
1874 carry
+= v
->ob_digit
[i
+k
] - z
1875 + ((twodigits
)zz
<< PyLong_SHIFT
);
1876 v
->ob_digit
[i
+k
] = (digit
)(carry
& PyLong_MASK
);
1877 carry
= Py_ARITHMETIC_RIGHT_SHIFT(PyLong_BASE_TWODIGITS_TYPE
,
1878 carry
, PyLong_SHIFT
);
1883 carry
+= v
->ob_digit
[i
+k
];
1884 v
->ob_digit
[i
+k
] = 0;
1888 a
->ob_digit
[k
] = (digit
) q
;
1890 assert(carry
== -1);
1891 a
->ob_digit
[k
] = (digit
) q
-1;
1893 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1894 carry
+= v
->ob_digit
[i
+k
] + w
->ob_digit
[i
];
1895 v
->ob_digit
[i
+k
] = (digit
)(carry
& PyLong_MASK
);
1896 carry
= Py_ARITHMETIC_RIGHT_SHIFT(
1897 PyLong_BASE_TWODIGITS_TYPE
,
1898 carry
, PyLong_SHIFT
);
1906 a
= long_normalize(a
);
1907 *prem
= divrem1(v
, d
, &d
);
1908 /* d receives the (unused) remainder */
1909 if (*prem
== NULL
) {
1922 long_dealloc(PyObject
*v
)
1924 Py_TYPE(v
)->tp_free(v
);
1928 long_repr(PyObject
*v
)
1930 return _PyLong_Format(v
, 10, 1, 0);
1934 long_str(PyObject
*v
)
1936 return _PyLong_Format(v
, 10, 0, 0);
1940 long_compare(PyLongObject
*a
, PyLongObject
*b
)
1944 if (Py_SIZE(a
) != Py_SIZE(b
)) {
1945 if (ABS(Py_SIZE(a
)) == 0 && ABS(Py_SIZE(b
)) == 0)
1948 sign
= Py_SIZE(a
) - Py_SIZE(b
);
1951 Py_ssize_t i
= ABS(Py_SIZE(a
));
1952 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1957 sign
= (int)a
->ob_digit
[i
] - (int)b
->ob_digit
[i
];
1962 return sign
< 0 ? -1 : sign
> 0 ? 1 : 0;
1966 long_hash(PyLongObject
*v
)
1972 /* This is designed so that Python ints and longs with the
1973 same value hash to the same value, otherwise comparisons
1974 of mapping keys will turn out weird */
1982 #define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
1983 /* The following loop produces a C long x such that (unsigned long)x
1984 is congruent to the absolute value of v modulo ULONG_MAX. The
1985 resulting x is nonzero if and only if v is. */
1987 /* Force a native long #-bits (32 or 64) circular shift */
1988 x
= ((x
<< PyLong_SHIFT
) & ~PyLong_MASK
) | ((x
>> LONG_BIT_PyLong_SHIFT
) & PyLong_MASK
);
1989 x
+= v
->ob_digit
[i
];
1990 /* If the addition above overflowed (thinking of x as
1991 unsigned), we compensate by incrementing. This preserves
1992 the value modulo ULONG_MAX. */
1993 if ((unsigned long)x
< v
->ob_digit
[i
])
1996 #undef LONG_BIT_PyLong_SHIFT
2004 /* Add the absolute values of two long integers. */
2006 static PyLongObject
*
2007 x_add(PyLongObject
*a
, PyLongObject
*b
)
2009 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
2014 /* Ensure a is the larger of the two: */
2015 if (size_a
< size_b
) {
2016 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2017 { Py_ssize_t size_temp
= size_a
;
2019 size_b
= size_temp
; }
2021 z
= _PyLong_New(size_a
+1);
2024 for (i
= 0; i
< size_b
; ++i
) {
2025 carry
+= a
->ob_digit
[i
] + b
->ob_digit
[i
];
2026 z
->ob_digit
[i
] = carry
& PyLong_MASK
;
2027 carry
>>= PyLong_SHIFT
;
2029 for (; i
< size_a
; ++i
) {
2030 carry
+= a
->ob_digit
[i
];
2031 z
->ob_digit
[i
] = carry
& PyLong_MASK
;
2032 carry
>>= PyLong_SHIFT
;
2034 z
->ob_digit
[i
] = carry
;
2035 return long_normalize(z
);
2038 /* Subtract the absolute values of two integers. */
2040 static PyLongObject
*
2041 x_sub(PyLongObject
*a
, PyLongObject
*b
)
2043 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
2049 /* Ensure a is the larger of the two: */
2050 if (size_a
< size_b
) {
2052 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2053 { Py_ssize_t size_temp
= size_a
;
2055 size_b
= size_temp
; }
2057 else if (size_a
== size_b
) {
2058 /* Find highest digit where a and b differ: */
2060 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
2063 return _PyLong_New(0);
2064 if (a
->ob_digit
[i
] < b
->ob_digit
[i
]) {
2066 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2068 size_a
= size_b
= i
+1;
2070 z
= _PyLong_New(size_a
);
2073 for (i
= 0; i
< size_b
; ++i
) {
2074 /* The following assumes unsigned arithmetic
2075 works module 2**N for some N>PyLong_SHIFT. */
2076 borrow
= a
->ob_digit
[i
] - b
->ob_digit
[i
] - borrow
;
2077 z
->ob_digit
[i
] = borrow
& PyLong_MASK
;
2078 borrow
>>= PyLong_SHIFT
;
2079 borrow
&= 1; /* Keep only one sign bit */
2081 for (; i
< size_a
; ++i
) {
2082 borrow
= a
->ob_digit
[i
] - borrow
;
2083 z
->ob_digit
[i
] = borrow
& PyLong_MASK
;
2084 borrow
>>= PyLong_SHIFT
;
2085 borrow
&= 1; /* Keep only one sign bit */
2087 assert(borrow
== 0);
2089 z
->ob_size
= -(z
->ob_size
);
2090 return long_normalize(z
);
2094 long_add(PyLongObject
*v
, PyLongObject
*w
)
2096 PyLongObject
*a
, *b
, *z
;
2098 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2100 if (a
->ob_size
< 0) {
2101 if (b
->ob_size
< 0) {
2103 if (z
!= NULL
&& z
->ob_size
!= 0)
2104 z
->ob_size
= -(z
->ob_size
);
2117 return (PyObject
*)z
;
2121 long_sub(PyLongObject
*v
, PyLongObject
*w
)
2123 PyLongObject
*a
, *b
, *z
;
2125 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2127 if (a
->ob_size
< 0) {
2132 if (z
!= NULL
&& z
->ob_size
!= 0)
2133 z
->ob_size
= -(z
->ob_size
);
2143 return (PyObject
*)z
;
2146 /* Grade school multiplication, ignoring the signs.
2147 * Returns the absolute value of the product, or NULL if error.
2149 static PyLongObject
*
2150 x_mul(PyLongObject
*a
, PyLongObject
*b
)
2153 Py_ssize_t size_a
= ABS(Py_SIZE(a
));
2154 Py_ssize_t size_b
= ABS(Py_SIZE(b
));
2157 z
= _PyLong_New(size_a
+ size_b
);
2161 memset(z
->ob_digit
, 0, Py_SIZE(z
) * sizeof(digit
));
2163 /* Efficient squaring per HAC, Algorithm 14.16:
2164 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2165 * Gives slightly less than a 2x speedup when a == b,
2166 * via exploiting that each entry in the multiplication
2167 * pyramid appears twice (except for the size_a squares).
2169 for (i
= 0; i
< size_a
; ++i
) {
2171 twodigits f
= a
->ob_digit
[i
];
2172 digit
*pz
= z
->ob_digit
+ (i
<< 1);
2173 digit
*pa
= a
->ob_digit
+ i
+ 1;
2174 digit
*paend
= a
->ob_digit
+ size_a
;
2181 carry
= *pz
+ f
* f
;
2182 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2183 carry
>>= PyLong_SHIFT
;
2184 assert(carry
<= PyLong_MASK
);
2186 /* Now f is added in twice in each column of the
2187 * pyramid it appears. Same as adding f<<1 once.
2190 while (pa
< paend
) {
2191 carry
+= *pz
+ *pa
++ * f
;
2192 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2193 carry
>>= PyLong_SHIFT
;
2194 assert(carry
<= (PyLong_MASK
<< 1));
2198 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2199 carry
>>= PyLong_SHIFT
;
2202 *pz
+= (digit
)(carry
& PyLong_MASK
);
2203 assert((carry
>> PyLong_SHIFT
) == 0);
2206 else { /* a is not the same as b -- gradeschool long mult */
2207 for (i
= 0; i
< size_a
; ++i
) {
2208 twodigits carry
= 0;
2209 twodigits f
= a
->ob_digit
[i
];
2210 digit
*pz
= z
->ob_digit
+ i
;
2211 digit
*pb
= b
->ob_digit
;
2212 digit
*pbend
= b
->ob_digit
+ size_b
;
2219 while (pb
< pbend
) {
2220 carry
+= *pz
+ *pb
++ * f
;
2221 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2222 carry
>>= PyLong_SHIFT
;
2223 assert(carry
<= PyLong_MASK
);
2226 *pz
+= (digit
)(carry
& PyLong_MASK
);
2227 assert((carry
>> PyLong_SHIFT
) == 0);
2230 return long_normalize(z
);
2233 /* A helper for Karatsuba multiplication (k_mul).
2234 Takes a long "n" and an integer "size" representing the place to
2235 split, and sets low and high such that abs(n) == (high << size) + low,
2236 viewing the shift as being by digits. The sign bit is ignored, and
2237 the return values are >= 0.
2238 Returns 0 on success, -1 on failure.
2241 kmul_split(PyLongObject
*n
, Py_ssize_t size
, PyLongObject
**high
, PyLongObject
**low
)
2243 PyLongObject
*hi
, *lo
;
2244 Py_ssize_t size_lo
, size_hi
;
2245 const Py_ssize_t size_n
= ABS(Py_SIZE(n
));
2247 size_lo
= MIN(size_n
, size
);
2248 size_hi
= size_n
- size_lo
;
2250 if ((hi
= _PyLong_New(size_hi
)) == NULL
)
2252 if ((lo
= _PyLong_New(size_lo
)) == NULL
) {
2257 memcpy(lo
->ob_digit
, n
->ob_digit
, size_lo
* sizeof(digit
));
2258 memcpy(hi
->ob_digit
, n
->ob_digit
+ size_lo
, size_hi
* sizeof(digit
));
2260 *high
= long_normalize(hi
);
2261 *low
= long_normalize(lo
);
2265 static PyLongObject
*k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
);
2267 /* Karatsuba multiplication. Ignores the input signs, and returns the
2268 * absolute value of the product (or NULL if error).
2269 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2271 static PyLongObject
*
2272 k_mul(PyLongObject
*a
, PyLongObject
*b
)
2274 Py_ssize_t asize
= ABS(Py_SIZE(a
));
2275 Py_ssize_t bsize
= ABS(Py_SIZE(b
));
2276 PyLongObject
*ah
= NULL
;
2277 PyLongObject
*al
= NULL
;
2278 PyLongObject
*bh
= NULL
;
2279 PyLongObject
*bl
= NULL
;
2280 PyLongObject
*ret
= NULL
;
2281 PyLongObject
*t1
, *t2
, *t3
;
2282 Py_ssize_t shift
; /* the number of digits we split off */
2285 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2286 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2287 * Then the original product is
2288 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2289 * By picking X to be a power of 2, "*X" is just shifting, and it's
2290 * been reduced to 3 multiplies on numbers half the size.
2293 /* We want to split based on the larger number; fiddle so that b
2296 if (asize
> bsize
) {
2306 /* Use gradeschool math when either number is too small. */
2307 i
= a
== b
? KARATSUBA_SQUARE_CUTOFF
: KARATSUBA_CUTOFF
;
2310 return _PyLong_New(0);
2315 /* If a is small compared to b, splitting on b gives a degenerate
2316 * case with ah==0, and Karatsuba may be (even much) less efficient
2317 * than "grade school" then. However, we can still win, by viewing
2318 * b as a string of "big digits", each of width a->ob_size. That
2319 * leads to a sequence of balanced calls to k_mul.
2321 if (2 * asize
<= bsize
)
2322 return k_lopsided_mul(a
, b
);
2324 /* Split a & b into hi & lo pieces. */
2326 if (kmul_split(a
, shift
, &ah
, &al
) < 0) goto fail
;
2327 assert(Py_SIZE(ah
) > 0); /* the split isn't degenerate */
2335 else if (kmul_split(b
, shift
, &bh
, &bl
) < 0) goto fail
;
2338 * 1. Allocate result space (asize + bsize digits: that's always
2340 * 2. Compute ah*bh, and copy into result at 2*shift.
2341 * 3. Compute al*bl, and copy into result at 0. Note that this
2342 * can't overlap with #2.
2343 * 4. Subtract al*bl from the result, starting at shift. This may
2344 * underflow (borrow out of the high digit), but we don't care:
2345 * we're effectively doing unsigned arithmetic mod
2346 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2347 * borrows and carries out of the high digit can be ignored.
2348 * 5. Subtract ah*bh from the result, starting at shift.
2349 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2353 /* 1. Allocate result space. */
2354 ret
= _PyLong_New(asize
+ bsize
);
2355 if (ret
== NULL
) goto fail
;
2357 /* Fill with trash, to catch reference to uninitialized digits. */
2358 memset(ret
->ob_digit
, 0xDF, Py_SIZE(ret
) * sizeof(digit
));
2361 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2362 if ((t1
= k_mul(ah
, bh
)) == NULL
) goto fail
;
2363 assert(Py_SIZE(t1
) >= 0);
2364 assert(2*shift
+ Py_SIZE(t1
) <= Py_SIZE(ret
));
2365 memcpy(ret
->ob_digit
+ 2*shift
, t1
->ob_digit
,
2366 Py_SIZE(t1
) * sizeof(digit
));
2368 /* Zero-out the digits higher than the ah*bh copy. */
2369 i
= Py_SIZE(ret
) - 2*shift
- Py_SIZE(t1
);
2371 memset(ret
->ob_digit
+ 2*shift
+ Py_SIZE(t1
), 0,
2374 /* 3. t2 <- al*bl, and copy into the low digits. */
2375 if ((t2
= k_mul(al
, bl
)) == NULL
) {
2379 assert(Py_SIZE(t2
) >= 0);
2380 assert(Py_SIZE(t2
) <= 2*shift
); /* no overlap with high digits */
2381 memcpy(ret
->ob_digit
, t2
->ob_digit
, Py_SIZE(t2
) * sizeof(digit
));
2383 /* Zero out remaining digits. */
2384 i
= 2*shift
- Py_SIZE(t2
); /* number of uninitialized digits */
2386 memset(ret
->ob_digit
+ Py_SIZE(t2
), 0, i
* sizeof(digit
));
2388 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2389 * because it's fresher in cache.
2391 i
= Py_SIZE(ret
) - shift
; /* # digits after shift */
2392 (void)v_isub(ret
->ob_digit
+ shift
, i
, t2
->ob_digit
, Py_SIZE(t2
));
2395 (void)v_isub(ret
->ob_digit
+ shift
, i
, t1
->ob_digit
, Py_SIZE(t1
));
2398 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2399 if ((t1
= x_add(ah
, al
)) == NULL
) goto fail
;
2408 else if ((t2
= x_add(bh
, bl
)) == NULL
) {
2419 if (t3
== NULL
) goto fail
;
2420 assert(Py_SIZE(t3
) >= 0);
2422 /* Add t3. It's not obvious why we can't run out of room here.
2423 * See the (*) comment after this function.
2425 (void)v_iadd(ret
->ob_digit
+ shift
, i
, t3
->ob_digit
, Py_SIZE(t3
));
2428 return long_normalize(ret
);
2439 /* (*) Why adding t3 can't "run out of room" above.
2441 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2444 1. For any integer i, i = c(i/2) + f(i/2). In particular,
2445 bsize = c(bsize/2) + f(bsize/2).
2446 2. shift = f(bsize/2)
2448 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2449 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
2451 We allocated asize + bsize result digits, and add t3 into them at an offset
2452 of shift. This leaves asize+bsize-shift allocated digit positions for t3
2453 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2454 asize + c(bsize/2) available digit positions.
2456 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2457 at most c(bsize/2) digits + 1 bit.
2459 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2460 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2461 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
2463 The product (ah+al)*(bh+bl) therefore has at most
2465 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
2467 and we have asize + c(bsize/2) available digit positions. We need to show
2468 this is always enough. An instance of c(bsize/2) cancels out in both, so
2469 the question reduces to whether asize digits is enough to hold
2470 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2471 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2472 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2473 digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
2474 asize == bsize, then we're asking whether bsize digits is enough to hold
2475 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2476 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2477 bsize >= KARATSUBA_CUTOFF >= 2.
2479 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2480 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2481 ah*bh and al*bl too.
2484 /* b has at least twice the digits of a, and a is big enough that Karatsuba
2485 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2486 * of slices, each with a->ob_size digits, and multiply the slices by a,
2487 * one at a time. This gives k_mul balanced inputs to work with, and is
2488 * also cache-friendly (we compute one double-width slice of the result
2489 * at a time, then move on, never bactracking except for the helpful
2490 * single-width slice overlap between successive partial sums).
2492 static PyLongObject
*
2493 k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
)
2495 const Py_ssize_t asize
= ABS(Py_SIZE(a
));
2496 Py_ssize_t bsize
= ABS(Py_SIZE(b
));
2497 Py_ssize_t nbdone
; /* # of b digits already multiplied */
2499 PyLongObject
*bslice
= NULL
;
2501 assert(asize
> KARATSUBA_CUTOFF
);
2502 assert(2 * asize
<= bsize
);
2504 /* Allocate result space, and zero it out. */
2505 ret
= _PyLong_New(asize
+ bsize
);
2508 memset(ret
->ob_digit
, 0, Py_SIZE(ret
) * sizeof(digit
));
2510 /* Successive slices of b are copied into bslice. */
2511 bslice
= _PyLong_New(asize
);
2517 PyLongObject
*product
;
2518 const Py_ssize_t nbtouse
= MIN(bsize
, asize
);
2520 /* Multiply the next slice of b by a. */
2521 memcpy(bslice
->ob_digit
, b
->ob_digit
+ nbdone
,
2522 nbtouse
* sizeof(digit
));
2523 Py_SIZE(bslice
) = nbtouse
;
2524 product
= k_mul(a
, bslice
);
2525 if (product
== NULL
)
2528 /* Add into result. */
2529 (void)v_iadd(ret
->ob_digit
+ nbdone
, Py_SIZE(ret
) - nbdone
,
2530 product
->ob_digit
, Py_SIZE(product
));
2538 return long_normalize(ret
);
2547 long_mul(PyLongObject
*v
, PyLongObject
*w
)
2549 PyLongObject
*a
, *b
, *z
;
2551 if (!convert_binop((PyObject
*)v
, (PyObject
*)w
, &a
, &b
)) {
2552 Py_INCREF(Py_NotImplemented
);
2553 return Py_NotImplemented
;
2557 /* Negate if exactly one of the inputs is negative. */
2558 if (((a
->ob_size
^ b
->ob_size
) < 0) && z
)
2559 z
->ob_size
= -(z
->ob_size
);
2562 return (PyObject
*)z
;
2565 /* The / and % operators are now defined in terms of divmod().
2566 The expression a mod b has the value a - b*floor(a/b).
2567 The long_divrem function gives the remainder after division of
2568 |a| by |b|, with the sign of a. This is also expressed
2569 as a - b*trunc(a/b), if trunc truncates towards zero.
2576 So, to get from rem to mod, we have to add b if a and b
2577 have different signs. We then subtract one from the 'div'
2578 part of the outcome to keep the invariant intact. */
2581 * *pdiv, *pmod = divmod(v, w)
2582 * NULL can be passed for pdiv or pmod, in which case that part of
2583 * the result is simply thrown away. The caller owns a reference to
2584 * each of these it requests (does not pass NULL for).
2587 l_divmod(PyLongObject
*v
, PyLongObject
*w
,
2588 PyLongObject
**pdiv
, PyLongObject
**pmod
)
2590 PyLongObject
*div
, *mod
;
2592 if (long_divrem(v
, w
, &div
, &mod
) < 0)
2594 if ((Py_SIZE(mod
) < 0 && Py_SIZE(w
) > 0) ||
2595 (Py_SIZE(mod
) > 0 && Py_SIZE(w
) < 0)) {
2598 temp
= (PyLongObject
*) long_add(mod
, w
);
2605 one
= (PyLongObject
*) PyLong_FromLong(1L);
2607 (temp
= (PyLongObject
*) long_sub(div
, one
)) == NULL
) {
2631 long_div(PyObject
*v
, PyObject
*w
)
2633 PyLongObject
*a
, *b
, *div
;
2635 CONVERT_BINOP(v
, w
, &a
, &b
);
2636 if (l_divmod(a
, b
, &div
, NULL
) < 0)
2640 return (PyObject
*)div
;
2644 long_classic_div(PyObject
*v
, PyObject
*w
)
2646 PyLongObject
*a
, *b
, *div
;
2648 CONVERT_BINOP(v
, w
, &a
, &b
);
2649 if (Py_DivisionWarningFlag
&&
2650 PyErr_Warn(PyExc_DeprecationWarning
, "classic long division") < 0)
2652 else if (l_divmod(a
, b
, &div
, NULL
) < 0)
2656 return (PyObject
*)div
;
2660 long_true_divide(PyObject
*v
, PyObject
*w
)
2662 PyLongObject
*a
, *b
;
2664 int failed
, aexp
= -1, bexp
= -1;
2666 CONVERT_BINOP(v
, w
, &a
, &b
);
2667 ad
= _PyLong_AsScaledDouble((PyObject
*)a
, &aexp
);
2668 bd
= _PyLong_AsScaledDouble((PyObject
*)b
, &bexp
);
2669 failed
= (ad
== -1.0 || bd
== -1.0) && PyErr_Occurred();
2674 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2675 but should really be set correctly after sucessful calls to
2676 _PyLong_AsScaledDouble() */
2677 assert(aexp
>= 0 && bexp
>= 0);
2680 PyErr_SetString(PyExc_ZeroDivisionError
,
2681 "long division or modulo by zero");
2685 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
2686 ad
/= bd
; /* overflow/underflow impossible here */
2688 if (aexp
> INT_MAX
/ PyLong_SHIFT
)
2690 else if (aexp
< -(INT_MAX
/ PyLong_SHIFT
))
2691 return PyFloat_FromDouble(0.0); /* underflow to 0 */
2693 ad
= ldexp(ad
, aexp
* PyLong_SHIFT
);
2694 if (Py_OVERFLOWED(ad
)) /* ignore underflow to 0.0 */
2696 return PyFloat_FromDouble(ad
);
2699 PyErr_SetString(PyExc_OverflowError
,
2700 "long/long too large for a float");
2706 long_mod(PyObject
*v
, PyObject
*w
)
2708 PyLongObject
*a
, *b
, *mod
;
2710 CONVERT_BINOP(v
, w
, &a
, &b
);
2712 if (l_divmod(a
, b
, NULL
, &mod
) < 0)
2716 return (PyObject
*)mod
;
2720 long_divmod(PyObject
*v
, PyObject
*w
)
2722 PyLongObject
*a
, *b
, *div
, *mod
;
2725 CONVERT_BINOP(v
, w
, &a
, &b
);
2727 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
2734 PyTuple_SetItem(z
, 0, (PyObject
*) div
);
2735 PyTuple_SetItem(z
, 1, (PyObject
*) mod
);
2748 long_pow(PyObject
*v
, PyObject
*w
, PyObject
*x
)
2750 PyLongObject
*a
, *b
, *c
; /* a,b,c = v,w,x */
2751 int negativeOutput
= 0; /* if x<0 return negative output */
2753 PyLongObject
*z
= NULL
; /* accumulated result */
2754 Py_ssize_t i
, j
, k
; /* counters */
2755 PyLongObject
*temp
= NULL
;
2757 /* 5-ary values. If the exponent is large enough, table is
2758 * precomputed so that table[i] == a**i % c for i in range(32).
2760 PyLongObject
*table
[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2761 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2763 /* a, b, c = v, w, x */
2764 CONVERT_BINOP(v
, w
, &a
, &b
);
2765 if (PyLong_Check(x
)) {
2766 c
= (PyLongObject
*)x
;
2769 else if (PyInt_Check(x
)) {
2770 c
= (PyLongObject
*)PyLong_FromLong(PyInt_AS_LONG(x
));
2774 else if (x
== Py_None
)
2779 Py_INCREF(Py_NotImplemented
);
2780 return Py_NotImplemented
;
2783 if (Py_SIZE(b
) < 0) { /* if exponent is negative */
2785 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
2786 "cannot be negative when 3rd argument specified");
2790 /* else return a float. This works because we know
2791 that this calls float_pow() which converts its
2792 arguments to double. */
2795 return PyFloat_Type
.tp_as_number
->nb_power(v
, w
, x
);
2801 raise ValueError() */
2802 if (Py_SIZE(c
) == 0) {
2803 PyErr_SetString(PyExc_ValueError
,
2804 "pow() 3rd argument cannot be 0");
2809 negativeOutput = True
2810 modulus = -modulus */
2811 if (Py_SIZE(c
) < 0) {
2813 temp
= (PyLongObject
*)_PyLong_Copy(c
);
2819 c
->ob_size
= - c
->ob_size
;
2824 if ((Py_SIZE(c
) == 1) && (c
->ob_digit
[0] == 1)) {
2825 z
= (PyLongObject
*)PyLong_FromLong(0L);
2830 base = base % modulus
2831 Having the base positive just makes things easier. */
2832 if (Py_SIZE(a
) < 0) {
2833 if (l_divmod(a
, c
, NULL
, &temp
) < 0)
2841 /* At this point a, b, and c are guaranteed non-negative UNLESS
2842 c is NULL, in which case a may be negative. */
2844 z
= (PyLongObject
*)PyLong_FromLong(1L);
2848 /* Perform a modular reduction, X = X % c, but leave X alone if c
2853 if (l_divmod(X, c, NULL, &temp) < 0) \
2860 /* Multiply two values, then reduce the result:
2861 result = X*Y % c. If c is NULL, skip the mod. */
2862 #define MULT(X, Y, result) \
2864 temp = (PyLongObject *)long_mul(X, Y); \
2867 Py_XDECREF(result); \
2873 if (Py_SIZE(b
) <= FIVEARY_CUTOFF
) {
2874 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2875 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2876 for (i
= Py_SIZE(b
) - 1; i
>= 0; --i
) {
2877 digit bi
= b
->ob_digit
[i
];
2879 for (j
= 1 << (PyLong_SHIFT
-1); j
!= 0; j
>>= 1) {
2887 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2888 Py_INCREF(z
); /* still holds 1L */
2890 for (i
= 1; i
< 32; ++i
)
2891 MULT(table
[i
-1], a
, table
[i
])
2893 for (i
= Py_SIZE(b
) - 1; i
>= 0; --i
) {
2894 const digit bi
= b
->ob_digit
[i
];
2896 for (j
= PyLong_SHIFT
- 5; j
>= 0; j
-= 5) {
2897 const int index
= (bi
>> j
) & 0x1f;
2898 for (k
= 0; k
< 5; ++k
)
2901 MULT(z
, table
[index
], z
)
2906 if (negativeOutput
&& (Py_SIZE(z
) != 0)) {
2907 temp
= (PyLongObject
*)long_sub(z
, c
);
2923 if (Py_SIZE(b
) > FIVEARY_CUTOFF
) {
2924 for (i
= 0; i
< 32; ++i
)
2925 Py_XDECREF(table
[i
]);
2931 return (PyObject
*)z
;
2935 long_invert(PyLongObject
*v
)
2937 /* Implement ~x as -(x+1) */
2940 w
= (PyLongObject
*)PyLong_FromLong(1L);
2943 x
= (PyLongObject
*) long_add(v
, w
);
2947 Py_SIZE(x
) = -(Py_SIZE(x
));
2948 return (PyObject
*)x
;
2952 long_neg(PyLongObject
*v
)
2955 if (v
->ob_size
== 0 && PyLong_CheckExact(v
)) {
2958 return (PyObject
*) v
;
2960 z
= (PyLongObject
*)_PyLong_Copy(v
);
2962 z
->ob_size
= -(v
->ob_size
);
2963 return (PyObject
*)z
;
2967 long_abs(PyLongObject
*v
)
2972 return long_long((PyObject
*)v
);
2976 long_nonzero(PyLongObject
*v
)
2978 return ABS(Py_SIZE(v
)) != 0;
2982 long_rshift(PyLongObject
*v
, PyLongObject
*w
)
2984 PyLongObject
*a
, *b
;
2985 PyLongObject
*z
= NULL
;
2987 Py_ssize_t newsize
, wordshift
, loshift
, hishift
, i
, j
;
2988 digit lomask
, himask
;
2990 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2992 if (Py_SIZE(a
) < 0) {
2993 /* Right shifting negative numbers is harder */
2994 PyLongObject
*a1
, *a2
;
2995 a1
= (PyLongObject
*) long_invert(a
);
2998 a2
= (PyLongObject
*) long_rshift(a1
, b
);
3002 z
= (PyLongObject
*) long_invert(a2
);
3007 shiftby
= PyLong_AsLong((PyObject
*)b
);
3008 if (shiftby
== -1L && PyErr_Occurred())
3011 PyErr_SetString(PyExc_ValueError
,
3012 "negative shift count");
3015 wordshift
= shiftby
/ PyLong_SHIFT
;
3016 newsize
= ABS(Py_SIZE(a
)) - wordshift
;
3021 return (PyObject
*)z
;
3023 loshift
= shiftby
% PyLong_SHIFT
;
3024 hishift
= PyLong_SHIFT
- loshift
;
3025 lomask
= ((digit
)1 << hishift
) - 1;
3026 himask
= PyLong_MASK
^ lomask
;
3027 z
= _PyLong_New(newsize
);
3031 Py_SIZE(z
) = -(Py_SIZE(z
));
3032 for (i
= 0, j
= wordshift
; i
< newsize
; i
++, j
++) {
3033 z
->ob_digit
[i
] = (a
->ob_digit
[j
] >> loshift
) & lomask
;
3036 (a
->ob_digit
[j
+1] << hishift
) & himask
;
3038 z
= long_normalize(z
);
3043 return (PyObject
*) z
;
3048 long_lshift(PyObject
*v
, PyObject
*w
)
3050 /* This version due to Tim Peters */
3051 PyLongObject
*a
, *b
;
3052 PyLongObject
*z
= NULL
;
3054 Py_ssize_t oldsize
, newsize
, wordshift
, remshift
, i
, j
;
3057 CONVERT_BINOP(v
, w
, &a
, &b
);
3059 shiftby
= PyLong_AsLong((PyObject
*)b
);
3060 if (shiftby
== -1L && PyErr_Occurred())
3063 PyErr_SetString(PyExc_ValueError
, "negative shift count");
3066 if ((long)(int)shiftby
!= shiftby
) {
3067 PyErr_SetString(PyExc_ValueError
,
3068 "outrageous left shift count");
3071 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3072 wordshift
= (int)shiftby
/ PyLong_SHIFT
;
3073 remshift
= (int)shiftby
- wordshift
* PyLong_SHIFT
;
3075 oldsize
= ABS(a
->ob_size
);
3076 newsize
= oldsize
+ wordshift
;
3079 z
= _PyLong_New(newsize
);
3083 z
->ob_size
= -(z
->ob_size
);
3084 for (i
= 0; i
< wordshift
; i
++)
3087 for (i
= wordshift
, j
= 0; j
< oldsize
; i
++, j
++) {
3088 accum
|= (twodigits
)a
->ob_digit
[j
] << remshift
;
3089 z
->ob_digit
[i
] = (digit
)(accum
& PyLong_MASK
);
3090 accum
>>= PyLong_SHIFT
;
3093 z
->ob_digit
[newsize
-1] = (digit
)accum
;
3096 z
= long_normalize(z
);
3100 return (PyObject
*) z
;
3104 /* Bitwise and/xor/or operations */
3107 long_bitwise(PyLongObject
*a
,
3108 int op
, /* '&', '|', '^' */
3111 digit maska
, maskb
; /* 0 or PyLong_MASK */
3113 Py_ssize_t size_a
, size_b
, size_z
;
3119 if (Py_SIZE(a
) < 0) {
3120 a
= (PyLongObject
*) long_invert(a
);
3123 maska
= PyLong_MASK
;
3129 if (Py_SIZE(b
) < 0) {
3130 b
= (PyLongObject
*) long_invert(b
);
3135 maskb
= PyLong_MASK
;
3145 if (maska
!= maskb
) {
3146 maska
^= PyLong_MASK
;
3151 if (maska
&& maskb
) {
3153 maska
^= PyLong_MASK
;
3154 maskb
^= PyLong_MASK
;
3159 if (maska
|| maskb
) {
3161 maska
^= PyLong_MASK
;
3162 maskb
^= PyLong_MASK
;
3168 /* JRH: The original logic here was to allocate the result value (z)
3169 as the longer of the two operands. However, there are some cases
3170 where the result is guaranteed to be shorter than that: AND of two
3171 positives, OR of two negatives: use the shorter number. AND with
3172 mixed signs: use the positive number. OR with mixed signs: use the
3173 negative number. After the transformations above, op will be '&'
3174 iff one of these cases applies, and mask will be non-0 for operands
3175 whose length should be ignored.
3178 size_a
= Py_SIZE(a
);
3179 size_b
= Py_SIZE(b
);
3183 : (maskb
? size_a
: MIN(size_a
, size_b
)))
3184 : MAX(size_a
, size_b
);
3185 z
= _PyLong_New(size_z
);
3192 for (i
= 0; i
< size_z
; ++i
) {
3193 diga
= (i
< size_a
? a
->ob_digit
[i
] : 0) ^ maska
;
3194 digb
= (i
< size_b
? b
->ob_digit
[i
] : 0) ^ maskb
;
3196 case '&': z
->ob_digit
[i
] = diga
& digb
; break;
3197 case '|': z
->ob_digit
[i
] = diga
| digb
; break;
3198 case '^': z
->ob_digit
[i
] = diga
^ digb
; break;
3204 z
= long_normalize(z
);
3206 return (PyObject
*) z
;
3213 long_and(PyObject
*v
, PyObject
*w
)
3215 PyLongObject
*a
, *b
;
3217 CONVERT_BINOP(v
, w
, &a
, &b
);
3218 c
= long_bitwise(a
, '&', b
);
3225 long_xor(PyObject
*v
, PyObject
*w
)
3227 PyLongObject
*a
, *b
;
3229 CONVERT_BINOP(v
, w
, &a
, &b
);
3230 c
= long_bitwise(a
, '^', b
);
3237 long_or(PyObject
*v
, PyObject
*w
)
3239 PyLongObject
*a
, *b
;
3241 CONVERT_BINOP(v
, w
, &a
, &b
);
3242 c
= long_bitwise(a
, '|', b
);
3249 long_coerce(PyObject
**pv
, PyObject
**pw
)
3251 if (PyInt_Check(*pw
)) {
3252 *pw
= PyLong_FromLong(PyInt_AS_LONG(*pw
));
3258 else if (PyLong_Check(*pw
)) {
3263 return 1; /* Can't do it */
3267 long_long(PyObject
*v
)
3269 if (PyLong_CheckExact(v
))
3272 v
= _PyLong_Copy((PyLongObject
*)v
);
3277 long_int(PyObject
*v
)
3280 x
= PyLong_AsLong(v
);
3281 if (PyErr_Occurred()) {
3282 if (PyErr_ExceptionMatches(PyExc_OverflowError
)) {
3284 if (PyLong_CheckExact(v
)) {
3289 return _PyLong_Copy((PyLongObject
*)v
);
3294 return PyInt_FromLong(x
);
3298 long_float(PyObject
*v
)
3301 result
= PyLong_AsDouble(v
);
3302 if (result
== -1.0 && PyErr_Occurred())
3304 return PyFloat_FromDouble(result
);
3308 long_oct(PyObject
*v
)
3310 return _PyLong_Format(v
, 8, 1, 0);
3314 long_hex(PyObject
*v
)
3316 return _PyLong_Format(v
, 16, 1, 0);
3320 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
3323 long_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3326 int base
= -909; /* unlikely! */
3327 static char *kwlist
[] = {"x", "base", 0};
3329 if (type
!= &PyLong_Type
)
3330 return long_subtype_new(type
, args
, kwds
); /* Wimp out */
3331 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:long", kwlist
,
3335 return PyLong_FromLong(0L);
3337 return PyNumber_Long(x
);
3338 else if (PyString_Check(x
)) {
3339 /* Since PyLong_FromString doesn't have a length parameter,
3340 * check here for possible NULs in the string. */
3341 char *string
= PyString_AS_STRING(x
);
3342 if (strlen(string
) != PyString_Size(x
)) {
3343 /* create a repr() of the input string,
3344 * just like PyLong_FromString does. */
3346 srepr
= PyObject_Repr(x
);
3349 PyErr_Format(PyExc_ValueError
,
3350 "invalid literal for long() with base %d: %s",
3351 base
, PyString_AS_STRING(srepr
));
3355 return PyLong_FromString(PyString_AS_STRING(x
), NULL
, base
);
3357 #ifdef Py_USING_UNICODE
3358 else if (PyUnicode_Check(x
))
3359 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x
),
3360 PyUnicode_GET_SIZE(x
),
3364 PyErr_SetString(PyExc_TypeError
,
3365 "long() can't convert non-string with explicit base");
3370 /* Wimpy, slow approach to tp_new calls for subtypes of long:
3371 first create a regular long from whatever arguments we got,
3372 then allocate a subtype instance and initialize it from
3373 the regular long. The regular long is then thrown away.
3376 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3378 PyLongObject
*tmp
, *newobj
;
3381 assert(PyType_IsSubtype(type
, &PyLong_Type
));
3382 tmp
= (PyLongObject
*)long_new(&PyLong_Type
, args
, kwds
);
3385 assert(PyLong_CheckExact(tmp
));
3389 newobj
= (PyLongObject
*)type
->tp_alloc(type
, n
);
3390 if (newobj
== NULL
) {
3394 assert(PyLong_Check(newobj
));
3395 Py_SIZE(newobj
) = Py_SIZE(tmp
);
3396 for (i
= 0; i
< n
; i
++)
3397 newobj
->ob_digit
[i
] = tmp
->ob_digit
[i
];
3399 return (PyObject
*)newobj
;
3403 long_getnewargs(PyLongObject
*v
)
3405 return Py_BuildValue("(N)", _PyLong_Copy(v
));
3409 long_getN(PyLongObject
*v
, void *context
) {
3410 return PyLong_FromLong((Py_intptr_t
)context
);
3414 long__format__(PyObject
*self
, PyObject
*args
)
3416 PyObject
*format_spec
;
3418 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
3420 if (PyBytes_Check(format_spec
))
3421 return _PyLong_FormatAdvanced(self
,
3422 PyBytes_AS_STRING(format_spec
),
3423 PyBytes_GET_SIZE(format_spec
));
3424 if (PyUnicode_Check(format_spec
)) {
3425 /* Convert format_spec to a str */
3427 PyObject
*str_spec
= PyObject_Str(format_spec
);
3429 if (str_spec
== NULL
)
3432 result
= _PyLong_FormatAdvanced(self
,
3433 PyBytes_AS_STRING(str_spec
),
3434 PyBytes_GET_SIZE(str_spec
));
3436 Py_DECREF(str_spec
);
3439 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
3444 long_sizeof(PyLongObject
*v
)
3448 res
= v
->ob_type
->tp_basicsize
;
3449 if (v
->ob_size
!= 0)
3450 res
+= abs(v
->ob_size
) * sizeof(digit
);
3451 return PyInt_FromSsize_t(res
);
3456 long_is_finite(PyObject
*v
)
3462 static PyMethodDef long_methods
[] = {
3463 {"conjugate", (PyCFunction
)long_long
, METH_NOARGS
,
3464 "Returns self, the complex conjugate of any long."},
3466 {"is_finite", (PyCFunction
)long_is_finite
, METH_NOARGS
,
3467 "Returns always True."},
3469 {"__trunc__", (PyCFunction
)long_long
, METH_NOARGS
,
3470 "Truncating an Integral returns itself."},
3471 {"__getnewargs__", (PyCFunction
)long_getnewargs
, METH_NOARGS
},
3472 {"__format__", (PyCFunction
)long__format__
, METH_VARARGS
},
3473 {"__sizeof__", (PyCFunction
)long_sizeof
, METH_NOARGS
,
3474 "Returns size in memory, in bytes"},
3475 {NULL
, NULL
} /* sentinel */
3478 static PyGetSetDef long_getset
[] = {
3480 (getter
)long_long
, (setter
)NULL
,
3481 "the real part of a complex number",
3484 (getter
)long_getN
, (setter
)NULL
,
3485 "the imaginary part of a complex number",
3488 (getter
)long_long
, (setter
)NULL
,
3489 "the numerator of a rational number in lowest terms",
3492 (getter
)long_getN
, (setter
)NULL
,
3493 "the denominator of a rational number in lowest terms",
3495 {NULL
} /* Sentinel */
3498 PyDoc_STRVAR(long_doc
,
3499 "long(x[, base]) -> integer\n\
3501 Convert a string or number to a long integer, if possible. A floating\n\
3502 point argument will be truncated towards zero (this does not include a\n\
3503 string representation of a floating point number!) When converting a\n\
3504 string, use the optional base. It is an error to supply a base when\n\
3505 converting a non-string.");
3507 static PyNumberMethods long_as_number
= {
3508 (binaryfunc
) long_add
, /*nb_add*/
3509 (binaryfunc
) long_sub
, /*nb_subtract*/
3510 (binaryfunc
) long_mul
, /*nb_multiply*/
3511 long_classic_div
, /*nb_divide*/
3512 long_mod
, /*nb_remainder*/
3513 long_divmod
, /*nb_divmod*/
3514 long_pow
, /*nb_power*/
3515 (unaryfunc
) long_neg
, /*nb_negative*/
3516 (unaryfunc
) long_long
, /*tp_positive*/
3517 (unaryfunc
) long_abs
, /*tp_absolute*/
3518 (inquiry
) long_nonzero
, /*tp_nonzero*/
3519 (unaryfunc
) long_invert
, /*nb_invert*/
3520 long_lshift
, /*nb_lshift*/
3521 (binaryfunc
) long_rshift
, /*nb_rshift*/
3522 long_and
, /*nb_and*/
3523 long_xor
, /*nb_xor*/
3525 long_coerce
, /*nb_coerce*/
3526 long_int
, /*nb_int*/
3527 long_long
, /*nb_long*/
3528 long_float
, /*nb_float*/
3529 long_oct
, /*nb_oct*/
3530 long_hex
, /*nb_hex*/
3531 0, /* nb_inplace_add */
3532 0, /* nb_inplace_subtract */
3533 0, /* nb_inplace_multiply */
3534 0, /* nb_inplace_divide */
3535 0, /* nb_inplace_remainder */
3536 0, /* nb_inplace_power */
3537 0, /* nb_inplace_lshift */
3538 0, /* nb_inplace_rshift */
3539 0, /* nb_inplace_and */
3540 0, /* nb_inplace_xor */
3541 0, /* nb_inplace_or */
3542 long_div
, /* nb_floor_divide */
3543 long_true_divide
, /* nb_true_divide */
3544 0, /* nb_inplace_floor_divide */
3545 0, /* nb_inplace_true_divide */
3546 long_long
, /* nb_index */
3549 PyTypeObject PyLong_Type
= {
3550 PyObject_HEAD_INIT(&PyType_Type
)
3552 "long", /* tp_name */
3553 sizeof(PyLongObject
) - sizeof(digit
), /* tp_basicsize */
3554 sizeof(digit
), /* tp_itemsize */
3555 long_dealloc
, /* tp_dealloc */
3559 (cmpfunc
)long_compare
, /* tp_compare */
3560 long_repr
, /* tp_repr */
3561 &long_as_number
, /* tp_as_number */
3562 0, /* tp_as_sequence */
3563 0, /* tp_as_mapping */
3564 (hashfunc
)long_hash
, /* tp_hash */
3566 long_str
, /* tp_str */
3567 PyObject_GenericGetAttr
, /* tp_getattro */
3568 0, /* tp_setattro */
3569 0, /* tp_as_buffer */
3570 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
3571 Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_LONG_SUBCLASS
, /* tp_flags */
3572 long_doc
, /* tp_doc */
3573 0, /* tp_traverse */
3575 0, /* tp_richcompare */
3576 0, /* tp_weaklistoffset */
3578 0, /* tp_iternext */
3579 long_methods
, /* tp_methods */
3581 long_getset
, /* tp_getset */
3584 0, /* tp_descr_get */
3585 0, /* tp_descr_set */
3586 0, /* tp_dictoffset */
3589 long_new
, /* tp_new */
3590 PyObject_Del
, /* tp_free */