3 /* Long (arbitrary precision) integer object implementation */
5 /* XXX The functional organization of this file is terrible */
8 #include "longintrepr.h"
14 /* For long multiplication, use the O(N**2) school algorithm unless
15 * both operands contain more than KARATSUBA_CUTOFF digits (this
16 * being an internal Python long digit, in base PyLong_BASE).
18 #define KARATSUBA_CUTOFF 70
19 #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
21 /* For exponentiation, use the binary left-to-right algorithm
22 * unless the exponent contains more than FIVEARY_CUTOFF digits.
23 * In that case, do 5 bits at a time. The potential drawback is that
24 * a table of 2**5 intermediate results is computed.
26 #define FIVEARY_CUTOFF 8
28 #define ABS(x) ((x) < 0 ? -(x) : (x))
32 #define MAX(x, y) ((x) < (y) ? (y) : (x))
33 #define MIN(x, y) ((x) > (y) ? (y) : (x))
35 #define SIGCHECK(PyTryBlock) \
36 if (--_Py_Ticker < 0) { \
37 _Py_Ticker = _Py_CheckInterval; \
38 if (PyErr_CheckSignals()) PyTryBlock \
41 /* Normalize (remove leading zeros from) a long int object.
42 Doesn't attempt to free the storage--in most cases, due to the nature
43 of the algorithms used, this could save at most be one word anyway. */
46 long_normalize(register PyLongObject
*v
)
48 Py_ssize_t j
= ABS(Py_SIZE(v
));
51 while (i
> 0 && v
->ob_digit
[i
-1] == 0)
54 Py_SIZE(v
) = (Py_SIZE(v
) < 0) ? -(i
) : i
;
58 /* Allocate a new long int object with size digits.
59 Return NULL and set exception if we run out of memory. */
61 #define MAX_LONG_DIGITS \
62 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
65 _PyLong_New(Py_ssize_t size
)
67 if (size
> (Py_ssize_t
)MAX_LONG_DIGITS
) {
68 PyErr_SetString(PyExc_OverflowError
,
69 "too many digits in integer");
72 /* coverity[ampersand_in_size] */
73 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
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 digit bits
= (digit
)frac
;
201 v
->ob_digit
[i
] = 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 Py_ssize_t ndigits
; /* number of Python long digits */
442 PyLongObject
* v
; /* result */
443 Py_ssize_t 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
487 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
488 /* catch overflow before it happens */
489 if (numsignificantbytes
> (PY_SSIZE_T_MAX
- PyLong_SHIFT
) / 8) {
490 PyErr_SetString(PyExc_OverflowError
,
491 "byte array too long to convert to int");
494 ndigits
= (numsignificantbytes
* 8 + PyLong_SHIFT
- 1) / PyLong_SHIFT
;
495 v
= _PyLong_New(ndigits
);
499 /* Copy the bits over. The tricky parts are computing 2's-comp on
500 the fly for signed numbers, and dealing with the mismatch between
501 8-bit bytes and (probably) 15-bit Python digits.*/
504 twodigits carry
= 1; /* for 2's-comp calculation */
505 twodigits accum
= 0; /* sliding register */
506 unsigned int accumbits
= 0; /* number of bits in accum */
507 const unsigned char* p
= pstartbyte
;
509 for (i
= 0; i
< numsignificantbytes
; ++i
, p
+= incr
) {
510 twodigits thisbyte
= *p
;
511 /* Compute correction for 2's comp, if needed. */
513 thisbyte
= (0xff ^ thisbyte
) + carry
;
514 carry
= thisbyte
>> 8;
517 /* Because we're going LSB to MSB, thisbyte is
518 more significant than what's already in accum,
519 so needs to be prepended to accum. */
520 accum
|= (twodigits
)thisbyte
<< accumbits
;
522 if (accumbits
>= PyLong_SHIFT
) {
523 /* There's enough to fill a Python digit. */
524 assert(idigit
< ndigits
);
525 v
->ob_digit
[idigit
] = (digit
)(accum
&
528 accum
>>= PyLong_SHIFT
;
529 accumbits
-= PyLong_SHIFT
;
530 assert(accumbits
< PyLong_SHIFT
);
533 assert(accumbits
< PyLong_SHIFT
);
535 assert(idigit
< ndigits
);
536 v
->ob_digit
[idigit
] = (digit
)accum
;
541 Py_SIZE(v
) = is_signed
? -idigit
: idigit
;
542 return (PyObject
*)long_normalize(v
);
546 _PyLong_AsByteArray(PyLongObject
* v
,
547 unsigned char* bytes
, size_t n
,
548 int little_endian
, int is_signed
)
550 Py_ssize_t i
; /* index into v->ob_digit */
551 Py_ssize_t ndigits
; /* |v->ob_size| */
552 twodigits accum
; /* sliding register */
553 unsigned int accumbits
; /* # bits in accum */
554 int do_twos_comp
; /* store 2's-comp? is_signed and v < 0 */
555 digit carry
; /* for computing 2's-comp */
556 size_t j
; /* # bytes filled */
557 unsigned char* p
; /* pointer to next byte in bytes */
558 int pincr
; /* direction to move p */
560 assert(v
!= NULL
&& PyLong_Check(v
));
562 if (Py_SIZE(v
) < 0) {
563 ndigits
= -(Py_SIZE(v
));
565 PyErr_SetString(PyExc_OverflowError
,
566 "can't convert negative long to unsigned");
572 ndigits
= Py_SIZE(v
);
585 /* Copy over all the Python digits.
586 It's crucial that every Python digit except for the MSD contribute
587 exactly PyLong_SHIFT bits to the total, so first assert that the long is
589 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
593 carry
= do_twos_comp
? 1 : 0;
594 for (i
= 0; i
< ndigits
; ++i
) {
595 digit thisdigit
= v
->ob_digit
[i
];
597 thisdigit
= (thisdigit
^ PyLong_MASK
) + carry
;
598 carry
= thisdigit
>> PyLong_SHIFT
;
599 thisdigit
&= PyLong_MASK
;
601 /* Because we're going LSB to MSB, thisdigit is more
602 significant than what's already in accum, so needs to be
603 prepended to accum. */
604 accum
|= (twodigits
)thisdigit
<< accumbits
;
606 /* The most-significant digit may be (probably is) at least
608 if (i
== ndigits
- 1) {
609 /* Count # of sign bits -- they needn't be stored,
610 * although for signed conversion we need later to
611 * make sure at least one sign bit gets stored. */
612 digit s
= do_twos_comp
? thisdigit
^ PyLong_MASK
:
620 accumbits
+= PyLong_SHIFT
;
622 /* Store as many bytes as possible. */
623 while (accumbits
>= 8) {
627 *p
= (unsigned char)(accum
& 0xff);
634 /* Store the straggler (if any). */
635 assert(accumbits
< 8);
636 assert(carry
== 0); /* else do_twos_comp and *every* digit was 0 */
642 /* Fill leading bits of the byte with sign bits
643 (appropriately pretending that the long had an
644 infinite supply of sign bits). */
645 accum
|= (~(twodigits
)0) << accumbits
;
647 *p
= (unsigned char)(accum
& 0xff);
650 else if (j
== n
&& n
> 0 && is_signed
) {
651 /* The main loop filled the byte array exactly, so the code
652 just above didn't get to ensure there's a sign bit, and the
653 loop below wouldn't add one either. Make sure a sign bit
655 unsigned char msb
= *(p
- pincr
);
656 int sign_bit_set
= msb
>= 0x80;
657 assert(accumbits
== 0);
658 if (sign_bit_set
== do_twos_comp
)
664 /* Fill remaining bytes with copies of the sign bit. */
666 unsigned char signbyte
= do_twos_comp
? 0xffU
: 0U;
667 for ( ; j
< n
; ++j
, p
+= pincr
)
674 PyErr_SetString(PyExc_OverflowError
, "long too big to convert");
680 _PyLong_AsScaledDouble(PyObject
*vv
, int *exponent
)
682 /* NBITS_WANTED should be > the number of bits in a double's precision,
683 but small enough so that 2**NBITS_WANTED is within the normal double
684 range. nbitsneeded is set to 1 less than that because the most-significant
685 Python digit contains at least 1 significant bit, but we don't want to
686 bother counting them (catering to the worst case cheaply).
688 57 is one more than VAX-D double precision; I (Tim) don't know of a double
689 format with more precision than that; it's 1 larger so that we add in at
690 least one round bit to stand in for the ignored least-significant bits.
692 #define NBITS_WANTED 57
695 const double multiplier
= (double)(1L << PyLong_SHIFT
);
700 if (vv
== NULL
|| !PyLong_Check(vv
)) {
701 PyErr_BadInternalCall();
704 v
= (PyLongObject
*)vv
;
716 x
= (double)v
->ob_digit
[i
];
717 nbitsneeded
= NBITS_WANTED
- 1;
718 /* Invariant: i Python digits remain unaccounted for. */
719 while (i
> 0 && nbitsneeded
> 0) {
721 x
= x
* multiplier
+ (double)v
->ob_digit
[i
];
722 nbitsneeded
-= PyLong_SHIFT
;
724 /* There are i digits we didn't shift in. Pretending they're all
725 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
732 /* Get a C double from a long int object. */
735 PyLong_AsDouble(PyObject
*vv
)
740 if (vv
== NULL
|| !PyLong_Check(vv
)) {
741 PyErr_BadInternalCall();
744 x
= _PyLong_AsScaledDouble(vv
, &e
);
745 if (x
== -1.0 && PyErr_Occurred())
747 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
748 set correctly after a successful _PyLong_AsScaledDouble() call */
750 if (e
> INT_MAX
/ PyLong_SHIFT
)
753 x
= ldexp(x
, e
* PyLong_SHIFT
);
754 if (Py_OVERFLOWED(x
))
759 PyErr_SetString(PyExc_OverflowError
,
760 "long int too large to convert to float");
764 /* Create a new long (or int) object from a C pointer */
767 PyLong_FromVoidPtr(void *p
)
769 #if SIZEOF_VOID_P <= SIZEOF_LONG
771 return PyLong_FromUnsignedLong((unsigned long)p
);
772 return PyInt_FromLong((long)p
);
775 #ifndef HAVE_LONG_LONG
776 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
778 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
779 # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
781 /* optimize null pointers */
783 return PyInt_FromLong(0);
784 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG
)p
);
786 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
789 /* Get a C pointer from a long object (or an int object in some cases) */
792 PyLong_AsVoidPtr(PyObject
*vv
)
794 /* This function will allow int or long objects. If vv is neither,
795 then the PyLong_AsLong*() functions will raise the exception:
796 PyExc_SystemError, "bad argument to internal function"
798 #if SIZEOF_VOID_P <= SIZEOF_LONG
802 x
= PyInt_AS_LONG(vv
);
803 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
804 x
= PyLong_AsLong(vv
);
806 x
= PyLong_AsUnsignedLong(vv
);
809 #ifndef HAVE_LONG_LONG
810 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
812 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
813 # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
818 x
= PyInt_AS_LONG(vv
);
819 else if (PyLong_Check(vv
) && _PyLong_Sign(vv
) < 0)
820 x
= PyLong_AsLongLong(vv
);
822 x
= PyLong_AsUnsignedLongLong(vv
);
824 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
826 if (x
== -1 && PyErr_Occurred())
831 #ifdef HAVE_LONG_LONG
833 /* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
834 * rewritten to use the newer PyLong_{As,From}ByteArray API.
837 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
839 /* Create a new long int object from a C PY_LONG_LONG int. */
842 PyLong_FromLongLong(PY_LONG_LONG ival
)
845 unsigned PY_LONG_LONG abs_ival
;
846 unsigned PY_LONG_LONG t
; /* unsigned so >> doesn't propagate sign bit */
851 /* avoid signed overflow on negation; see comments
852 in PyLong_FromLong above. */
853 abs_ival
= (unsigned PY_LONG_LONG
)(-1-ival
) + 1;
857 abs_ival
= (unsigned PY_LONG_LONG
)ival
;
860 /* Count the number of Python digits.
861 We used to pick 5 ("big enough for anything"), but that's a
862 waste of time and space given that 5*15 = 75 bits are rarely
869 v
= _PyLong_New(ndigits
);
871 digit
*p
= v
->ob_digit
;
872 Py_SIZE(v
) = negative
? -ndigits
: ndigits
;
875 *p
++ = (digit
)(t
& PyLong_MASK
);
879 return (PyObject
*)v
;
882 /* Create a new long int object from a C unsigned PY_LONG_LONG int. */
885 PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival
)
888 unsigned PY_LONG_LONG t
;
891 /* Count the number of Python digits. */
892 t
= (unsigned PY_LONG_LONG
)ival
;
897 v
= _PyLong_New(ndigits
);
899 digit
*p
= v
->ob_digit
;
900 Py_SIZE(v
) = ndigits
;
902 *p
++ = (digit
)(ival
& PyLong_MASK
);
903 ival
>>= PyLong_SHIFT
;
906 return (PyObject
*)v
;
909 /* Create a new long int object from a C Py_ssize_t. */
912 PyLong_FromSsize_t(Py_ssize_t ival
)
914 Py_ssize_t bytes
= ival
;
916 return _PyLong_FromByteArray(
917 (unsigned char *)&bytes
,
918 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 1);
921 /* Create a new long int object from a C size_t. */
924 PyLong_FromSize_t(size_t ival
)
928 return _PyLong_FromByteArray(
929 (unsigned char *)&bytes
,
930 SIZEOF_SIZE_T
, IS_LITTLE_ENDIAN
, 0);
933 /* Get a C PY_LONG_LONG int from a long int object.
934 Return -1 and set an error if overflow occurs. */
937 PyLong_AsLongLong(PyObject
*vv
)
944 PyErr_BadInternalCall();
947 if (!PyLong_Check(vv
)) {
951 return (PY_LONG_LONG
)PyInt_AsLong(vv
);
952 if ((nb
= vv
->ob_type
->tp_as_number
) == NULL
||
953 nb
->nb_int
== NULL
) {
954 PyErr_SetString(PyExc_TypeError
, "an integer is required");
957 io
= (*nb
->nb_int
) (vv
);
960 if (PyInt_Check(io
)) {
961 bytes
= PyInt_AsLong(io
);
965 if (PyLong_Check(io
)) {
966 bytes
= PyLong_AsLongLong(io
);
971 PyErr_SetString(PyExc_TypeError
, "integer conversion failed");
975 res
= _PyLong_AsByteArray(
976 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
977 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
979 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
981 return (PY_LONG_LONG
)-1;
986 /* Get a C unsigned PY_LONG_LONG int from a long int object.
987 Return -1 and set an error if overflow occurs. */
989 unsigned PY_LONG_LONG
990 PyLong_AsUnsignedLongLong(PyObject
*vv
)
992 unsigned PY_LONG_LONG bytes
;
996 if (vv
== NULL
|| !PyLong_Check(vv
)) {
997 PyErr_BadInternalCall();
998 return (unsigned PY_LONG_LONG
)-1;
1001 res
= _PyLong_AsByteArray(
1002 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
1003 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
1005 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1007 return (unsigned PY_LONG_LONG
)res
;
1012 /* Get a C unsigned long int from a long int object, ignoring the high bits.
1013 Returns -1 and sets an error condition if an error occurs. */
1015 unsigned PY_LONG_LONG
1016 PyLong_AsUnsignedLongLongMask(PyObject
*vv
)
1018 register PyLongObject
*v
;
1019 unsigned PY_LONG_LONG x
;
1023 if (vv
== NULL
|| !PyLong_Check(vv
)) {
1024 PyErr_BadInternalCall();
1025 return (unsigned long) -1;
1027 v
= (PyLongObject
*)vv
;
1036 x
= (x
<< PyLong_SHIFT
) + v
->ob_digit
[i
];
1040 #undef IS_LITTLE_ENDIAN
1042 #endif /* HAVE_LONG_LONG */
1046 convert_binop(PyObject
*v
, PyObject
*w
, PyLongObject
**a
, PyLongObject
**b
) {
1047 if (PyLong_Check(v
)) {
1048 *a
= (PyLongObject
*) v
;
1051 else if (PyInt_Check(v
)) {
1052 *a
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(v
));
1057 if (PyLong_Check(w
)) {
1058 *b
= (PyLongObject
*) w
;
1061 else if (PyInt_Check(w
)) {
1062 *b
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(w
));
1071 #define CONVERT_BINOP(v, w, a, b) \
1072 if (!convert_binop(v, w, a, b)) { \
1073 Py_INCREF(Py_NotImplemented); \
1074 return Py_NotImplemented; \
1077 /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1078 2**k if d is nonzero, else 0. */
1080 static const unsigned char BitLengthTable
[32] = {
1081 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1082 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1086 bits_in_digit(digit d
)
1093 d_bits
+= (int)BitLengthTable
[d
];
1097 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1098 * is modified in place, by adding y to it. Carries are propagated as far as
1099 * x[m-1], and the remaining carry (0 or 1) is returned.
1102 v_iadd(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1108 for (i
= 0; i
< n
; ++i
) {
1109 carry
+= x
[i
] + y
[i
];
1110 x
[i
] = carry
& PyLong_MASK
;
1111 carry
>>= PyLong_SHIFT
;
1112 assert((carry
& 1) == carry
);
1114 for (; carry
&& i
< m
; ++i
) {
1116 x
[i
] = carry
& PyLong_MASK
;
1117 carry
>>= PyLong_SHIFT
;
1118 assert((carry
& 1) == carry
);
1123 /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1124 * is modified in place, by subtracting y from it. Borrows are propagated as
1125 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1128 v_isub(digit
*x
, Py_ssize_t m
, digit
*y
, Py_ssize_t n
)
1134 for (i
= 0; i
< n
; ++i
) {
1135 borrow
= x
[i
] - y
[i
] - borrow
;
1136 x
[i
] = borrow
& PyLong_MASK
;
1137 borrow
>>= PyLong_SHIFT
;
1138 borrow
&= 1; /* keep only 1 sign bit */
1140 for (; borrow
&& i
< m
; ++i
) {
1141 borrow
= x
[i
] - borrow
;
1142 x
[i
] = borrow
& PyLong_MASK
;
1143 borrow
>>= PyLong_SHIFT
;
1149 /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1150 * result in z[0:m], and return the d bits shifted out of the top.
1153 v_lshift(digit
*z
, digit
*a
, Py_ssize_t m
, int d
)
1158 assert(0 <= d
&& d
< PyLong_SHIFT
);
1159 for (i
=0; i
< m
; i
++) {
1160 twodigits acc
= (twodigits
)a
[i
] << d
| carry
;
1161 z
[i
] = (digit
)acc
& PyLong_MASK
;
1162 carry
= (digit
)(acc
>> PyLong_SHIFT
);
1167 /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1168 * result in z[0:m], and return the d bits shifted out of the bottom.
1171 v_rshift(digit
*z
, digit
*a
, Py_ssize_t m
, int d
)
1175 digit mask
= ((digit
)1 << d
) - 1U;
1177 assert(0 <= d
&& d
< PyLong_SHIFT
);
1178 for (i
=m
; i
-- > 0;) {
1179 twodigits acc
= (twodigits
)carry
<< PyLong_SHIFT
| a
[i
];
1180 carry
= (digit
)acc
& mask
;
1181 z
[i
] = (digit
)(acc
>> d
);
1186 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1187 in pout, and returning the remainder. pin and pout point at the LSD.
1188 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
1189 _PyLong_Format, but that should be done with great care since longs are
1193 inplace_divrem1(digit
*pout
, digit
*pin
, Py_ssize_t size
, digit n
)
1197 assert(n
> 0 && n
<= PyLong_MASK
);
1200 while (--size
>= 0) {
1202 rem
= (rem
<< PyLong_SHIFT
) + *--pin
;
1203 *--pout
= hi
= (digit
)(rem
/ n
);
1204 rem
-= (twodigits
)hi
* n
;
1209 /* Divide a long integer by a digit, returning both the quotient
1210 (as function result) and the remainder (through *prem).
1211 The sign of a is ignored; n should not be zero. */
1213 static PyLongObject
*
1214 divrem1(PyLongObject
*a
, digit n
, digit
*prem
)
1216 const Py_ssize_t size
= ABS(Py_SIZE(a
));
1219 assert(n
> 0 && n
<= PyLong_MASK
);
1220 z
= _PyLong_New(size
);
1223 *prem
= inplace_divrem1(z
->ob_digit
, a
->ob_digit
, size
, n
);
1224 return long_normalize(z
);
1227 /* Convert the long to a string object with given base,
1228 appending a base prefix of 0[box] if base is 2, 8 or 16.
1229 Add a trailing "L" if addL is non-zero.
1230 If newstyle is zero, then use the pre-2.6 behavior of octal having
1231 a leading "0", instead of the prefix "0o" */
1232 PyAPI_FUNC(PyObject
*)
1233 _PyLong_Format(PyObject
*aa
, int base
, int addL
, int newstyle
)
1235 register PyLongObject
*a
= (PyLongObject
*)aa
;
1236 PyStringObject
*str
;
1237 Py_ssize_t i
, j
, sz
;
1243 if (a
== NULL
|| !PyLong_Check(a
)) {
1244 PyErr_BadInternalCall();
1247 assert(base
>= 2 && base
<= 36);
1248 size_a
= ABS(Py_SIZE(a
));
1250 /* Compute a rough upper bound for the length of the string */
1257 i
= 5 + (addL
? 1 : 0);
1258 j
= size_a
*PyLong_SHIFT
+ bits
-1;
1260 if (j
/ PyLong_SHIFT
< size_a
|| sz
< i
) {
1261 PyErr_SetString(PyExc_OverflowError
,
1262 "long is too large to format");
1265 str
= (PyStringObject
*) PyString_FromStringAndSize((char *)0, sz
);
1268 p
= PyString_AS_STRING(str
) + sz
;
1275 if (a
->ob_size
== 0) {
1278 else if ((base
& (base
- 1)) == 0) {
1279 /* JRH: special case for power-of-2 bases */
1280 twodigits accum
= 0;
1281 int accumbits
= 0; /* # of bits in accum */
1282 int basebits
= 1; /* # of bits in base-1 */
1284 while ((i
>>= 1) > 1)
1287 for (i
= 0; i
< size_a
; ++i
) {
1288 accum
|= (twodigits
)a
->ob_digit
[i
] << accumbits
;
1289 accumbits
+= PyLong_SHIFT
;
1290 assert(accumbits
>= basebits
);
1292 char cdigit
= (char)(accum
& (base
- 1));
1293 cdigit
+= (cdigit
< 10) ? '0' : 'a'-10;
1294 assert(p
> PyString_AS_STRING(str
));
1296 accumbits
-= basebits
;
1298 } while (i
< size_a
-1 ? accumbits
>= basebits
:
1303 /* Not 0, and base not a power of 2. Divide repeatedly by
1304 base, but for speed use the highest power of base that
1306 Py_ssize_t size
= size_a
;
1307 digit
*pin
= a
->ob_digit
;
1308 PyLongObject
*scratch
;
1309 /* powbasw <- largest power of base that fits in a digit. */
1310 digit powbase
= base
; /* powbase == base ** power */
1313 twodigits newpow
= powbase
* (twodigits
)base
;
1314 if (newpow
>> PyLong_SHIFT
) /* doesn't fit in a digit */
1316 powbase
= (digit
)newpow
;
1320 /* Get a scratch area for repeated division. */
1321 scratch
= _PyLong_New(size
);
1322 if (scratch
== NULL
) {
1327 /* Repeatedly divide by powbase. */
1329 int ntostore
= power
;
1330 digit rem
= inplace_divrem1(scratch
->ob_digit
,
1331 pin
, size
, powbase
);
1332 pin
= scratch
->ob_digit
; /* no need to use a again */
1333 if (pin
[size
- 1] == 0)
1341 /* Break rem into digits. */
1342 assert(ntostore
> 0);
1344 digit nextrem
= (digit
)(rem
/ base
);
1345 char c
= (char)(rem
- nextrem
* base
);
1346 assert(p
> PyString_AS_STRING(str
));
1347 c
+= (c
< 10) ? '0' : 'a'-10;
1351 /* Termination is a bit delicate: must not
1352 store leading zeroes, so must get out if
1353 remaining quotient and rem are both 0. */
1354 } while (ntostore
&& (size
|| rem
));
1355 } while (size
!= 0);
1363 else if (base
== 8) {
1372 else if (base
== 16) {
1376 else if (base
!= 10) {
1378 *--p
= '0' + base
%10;
1380 *--p
= '0' + base
/10;
1384 if (p
!= PyString_AS_STRING(str
)) {
1385 char *q
= PyString_AS_STRING(str
);
1388 } while ((*q
++ = *p
++) != '\0');
1390 _PyString_Resize((PyObject
**)&str
,
1391 (Py_ssize_t
) (q
- PyString_AS_STRING(str
)));
1393 return (PyObject
*)str
;
1396 /* Table of digit values for 8-bit string -> integer conversion.
1397 * '0' maps to 0, ..., '9' maps to 9.
1398 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1399 * All other indices map to 37.
1400 * Note that when converting a base B string, a char c is a legitimate
1401 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1403 int _PyLong_DigitValue
[256] = {
1404 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1405 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1406 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1407 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1408 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1409 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1410 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1411 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1412 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1413 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1414 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1415 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1416 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1417 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1418 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1419 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1422 /* *str points to the first digit in a string of base `base` digits. base
1423 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1424 * non-digit (which may be *str!). A normalized long is returned.
1425 * The point to this routine is that it takes time linear in the number of
1426 * string characters.
1428 static PyLongObject
*
1429 long_from_binary_base(char **str
, int base
)
1440 assert(base
>= 2 && base
<= 32 && (base
& (base
- 1)) == 0);
1442 for (bits_per_char
= -1; n
; ++bits_per_char
)
1444 /* n <- total # of bits needed, while setting p to end-of-string */
1446 while (_PyLong_DigitValue
[Py_CHARMASK(*p
)] < base
)
1449 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1450 n
= (p
- start
) * bits_per_char
+ PyLong_SHIFT
- 1;
1451 if (n
/ bits_per_char
< p
- start
) {
1452 PyErr_SetString(PyExc_ValueError
,
1453 "long string too large to convert");
1456 n
= n
/ PyLong_SHIFT
;
1460 /* Read string from right, and fill in long from left; i.e.,
1461 * from least to most significant in both.
1465 pdigit
= z
->ob_digit
;
1466 while (--p
>= start
) {
1467 int k
= _PyLong_DigitValue
[Py_CHARMASK(*p
)];
1468 assert(k
>= 0 && k
< base
);
1469 accum
|= (twodigits
)k
<< bits_in_accum
;
1470 bits_in_accum
+= bits_per_char
;
1471 if (bits_in_accum
>= PyLong_SHIFT
) {
1472 *pdigit
++ = (digit
)(accum
& PyLong_MASK
);
1473 assert(pdigit
- z
->ob_digit
<= n
);
1474 accum
>>= PyLong_SHIFT
;
1475 bits_in_accum
-= PyLong_SHIFT
;
1476 assert(bits_in_accum
< PyLong_SHIFT
);
1479 if (bits_in_accum
) {
1480 assert(bits_in_accum
<= PyLong_SHIFT
);
1481 *pdigit
++ = (digit
)accum
;
1482 assert(pdigit
- z
->ob_digit
<= n
);
1484 while (pdigit
- z
->ob_digit
< n
)
1486 return long_normalize(z
);
1490 PyLong_FromString(char *str
, char **pend
, int base
)
1493 char *start
, *orig_str
= str
;
1495 PyObject
*strobj
, *strrepr
;
1498 if ((base
!= 0 && base
< 2) || base
> 36) {
1499 PyErr_SetString(PyExc_ValueError
,
1500 "long() arg 2 must be >= 2 and <= 36");
1503 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1507 else if (*str
== '-') {
1511 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1514 /* No base given. Deduce the base from the contents
1518 else if (str
[1] == 'x' || str
[1] == 'X')
1520 else if (str
[1] == 'o' || str
[1] == 'O')
1522 else if (str
[1] == 'b' || str
[1] == 'B')
1525 /* "old" (C-style) octal literal, still valid in
1526 2.x, although illegal in 3.x */
1529 /* Whether or not we were deducing the base, skip leading chars
1531 if (str
[0] == '0' &&
1532 ((base
== 16 && (str
[1] == 'x' || str
[1] == 'X')) ||
1533 (base
== 8 && (str
[1] == 'o' || str
[1] == 'O')) ||
1534 (base
== 2 && (str
[1] == 'b' || str
[1] == 'B'))))
1538 if ((base
& (base
- 1)) == 0)
1539 z
= long_from_binary_base(&str
, base
);
1542 Binary bases can be converted in time linear in the number of digits, because
1543 Python's representation base is binary. Other bases (including decimal!) use
1544 the simple quadratic-time algorithm below, complicated by some speed tricks.
1546 First some math: the largest integer that can be expressed in N base-B digits
1547 is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1548 case number of Python digits needed to hold it is the smallest integer n s.t.
1550 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1551 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1552 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
1554 The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
1555 this quickly. A Python long with that much space is reserved near the start,
1556 and the result is computed into it.
1558 The input string is actually treated as being in base base**i (i.e., i digits
1559 are processed at a time), where two more static arrays hold:
1561 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
1562 convmultmax_base[base] = base ** convwidth_base[base]
1564 The first of these is the largest i such that i consecutive input digits
1565 must fit in a single Python digit. The second is effectively the input
1566 base we're really using.
1568 Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1569 convmultmax_base[base], the result is "simply"
1571 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1573 where B = convmultmax_base[base].
1575 Error analysis: as above, the number of Python digits `n` needed is worst-
1578 n >= N * log(B)/log(PyLong_BASE)
1580 where `N` is the number of input digits in base `B`. This is computed via
1582 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
1584 below. Two numeric concerns are how much space this can waste, and whether
1585 the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
1586 which is the default (and it's unlikely anyone changes that).
1588 Waste isn't a problem: provided the first input digit isn't 0, the difference
1589 between the worst-case input with N digits and the smallest input with N
1590 digits is about a factor of B, but B is small compared to PyLong_BASE so at most
1591 one allocated Python digit can remain unused on that count. If
1592 N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
1593 and adding 1 returns a result 1 larger than necessary. However, that can't
1594 happen: whenever B is a power of 2, long_from_binary_base() is called
1595 instead, and it's impossible for B**i to be an integer power of 2**15 when
1596 B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
1597 an exact integer when B is not a power of 2, since B**i has a prime factor
1598 other than 2 in that case, but (2**15)**j's only prime factor is 2).
1600 The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
1601 is a little bit larger than an exact integer, but due to roundoff errors (in
1602 computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
1603 yields a numeric result a little less than that integer. Unfortunately, "how
1604 close can a transcendental function get to an integer over some range?"
1605 questions are generally theoretically intractable. Computer analysis via
1606 continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
1607 fractions, giving a sequence i/j of "the best" rational approximations. Then
1608 j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
1609 we can get very close to being in trouble, but very rarely. For example,
1610 76573 is a denominator in one of the continued-fraction approximations to
1611 log(10)/log(2**15), and indeed:
1613 >>> log(10)/log(2**15)*76573
1616 is very close to an integer. If we were working with IEEE single-precision,
1617 rounding errors could kill us. Finding worst cases in IEEE double-precision
1618 requires better-than-double-precision log() functions, and Tim didn't bother.
1619 Instead the code checks to see whether the allocated space is enough as each
1620 new Python digit is added, and copies the whole thing to a larger long if not.
1621 This should happen extremely rarely, and in fact I don't have a test case
1622 that triggers it(!). Instead the code was tested by artificially allocating
1623 just 1 digit at the start, so that the copying code was exercised for every
1624 digit beyond the first.
1626 register twodigits c
; /* current input character */
1630 twodigits convmultmax
, convmult
;
1634 static double log_base_PyLong_BASE
[37] = {0.0e0
,};
1635 static int convwidth_base
[37] = {0,};
1636 static twodigits convmultmax_base
[37] = {0,};
1638 if (log_base_PyLong_BASE
[base
] == 0.0) {
1639 twodigits convmax
= base
;
1642 log_base_PyLong_BASE
[base
] = log((double)base
) /
1643 log((double)PyLong_BASE
);
1645 twodigits next
= convmax
* base
;
1646 if (next
> PyLong_BASE
)
1651 convmultmax_base
[base
] = convmax
;
1653 convwidth_base
[base
] = i
;
1656 /* Find length of the string of numeric characters. */
1658 while (_PyLong_DigitValue
[Py_CHARMASK(*scan
)] < base
)
1661 /* Create a long object that can contain the largest possible
1662 * integer with this base and length. Note that there's no
1663 * need to initialize z->ob_digit -- no slot is read up before
1664 * being stored into.
1666 size_z
= (Py_ssize_t
)((scan
- str
) * log_base_PyLong_BASE
[base
]) + 1;
1667 /* Uncomment next line to test exceedingly rare copy code */
1670 z
= _PyLong_New(size_z
);
1675 /* `convwidth` consecutive input digits are treated as a single
1676 * digit in base `convmultmax`.
1678 convwidth
= convwidth_base
[base
];
1679 convmultmax
= convmultmax_base
[base
];
1682 while (str
< scan
) {
1683 /* grab up to convwidth digits from the input string */
1684 c
= (digit
)_PyLong_DigitValue
[Py_CHARMASK(*str
++)];
1685 for (i
= 1; i
< convwidth
&& str
!= scan
; ++i
, ++str
) {
1686 c
= (twodigits
)(c
* base
+
1687 _PyLong_DigitValue
[Py_CHARMASK(*str
)]);
1688 assert(c
< PyLong_BASE
);
1691 convmult
= convmultmax
;
1692 /* Calculate the shift only if we couldn't get
1695 if (i
!= convwidth
) {
1701 /* Multiply z by convmult, and add c. */
1703 pzstop
= pz
+ Py_SIZE(z
);
1704 for (; pz
< pzstop
; ++pz
) {
1705 c
+= (twodigits
)*pz
* convmult
;
1706 *pz
= (digit
)(c
& PyLong_MASK
);
1709 /* carry off the current end? */
1711 assert(c
< PyLong_BASE
);
1712 if (Py_SIZE(z
) < size_z
) {
1718 /* Extremely rare. Get more space. */
1719 assert(Py_SIZE(z
) == size_z
);
1720 tmp
= _PyLong_New(size_z
+ 1);
1725 memcpy(tmp
->ob_digit
,
1727 sizeof(digit
) * size_z
);
1730 z
->ob_digit
[size_z
] = (digit
)c
;
1741 Py_SIZE(z
) = -(Py_SIZE(z
));
1742 if (*str
== 'L' || *str
== 'l')
1744 while (*str
&& isspace(Py_CHARMASK(*str
)))
1750 return (PyObject
*) z
;
1754 slen
= strlen(orig_str
) < 200 ? strlen(orig_str
) : 200;
1755 strobj
= PyString_FromStringAndSize(orig_str
, slen
);
1758 strrepr
= PyObject_Repr(strobj
);
1760 if (strrepr
== NULL
)
1762 PyErr_Format(PyExc_ValueError
,
1763 "invalid literal for long() with base %d: %s",
1764 base
, PyString_AS_STRING(strrepr
));
1769 #ifdef Py_USING_UNICODE
1771 PyLong_FromUnicode(Py_UNICODE
*u
, Py_ssize_t length
, int base
)
1774 char *buffer
= (char *)PyMem_MALLOC(length
+1);
1779 if (PyUnicode_EncodeDecimal(u
, length
, buffer
, NULL
)) {
1783 result
= PyLong_FromString(buffer
, NULL
, base
);
1790 static PyLongObject
*x_divrem
1791 (PyLongObject
*, PyLongObject
*, PyLongObject
**);
1792 static PyObject
*long_long(PyObject
*v
);
1794 /* Long division with remainder, top-level routine */
1797 long_divrem(PyLongObject
*a
, PyLongObject
*b
,
1798 PyLongObject
**pdiv
, PyLongObject
**prem
)
1800 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
1804 PyErr_SetString(PyExc_ZeroDivisionError
,
1805 "long division or modulo by zero");
1808 if (size_a
< size_b
||
1809 (size_a
== size_b
&&
1810 a
->ob_digit
[size_a
-1] < b
->ob_digit
[size_b
-1])) {
1812 *pdiv
= _PyLong_New(0);
1816 *prem
= (PyLongObject
*) a
;
1821 z
= divrem1(a
, b
->ob_digit
[0], &rem
);
1824 *prem
= (PyLongObject
*) PyLong_FromLong((long)rem
);
1825 if (*prem
== NULL
) {
1831 z
= x_divrem(a
, b
, prem
);
1836 The quotient z has the sign of a*b;
1837 the remainder r has the sign of a,
1839 if ((a
->ob_size
< 0) != (b
->ob_size
< 0))
1840 z
->ob_size
= -(z
->ob_size
);
1841 if (a
->ob_size
< 0 && (*prem
)->ob_size
!= 0)
1842 (*prem
)->ob_size
= -((*prem
)->ob_size
);
1847 /* Unsigned long division with remainder -- the algorithm. The arguments v1
1848 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
1850 static PyLongObject
*
1851 x_divrem(PyLongObject
*v1
, PyLongObject
*w1
, PyLongObject
**prem
)
1853 PyLongObject
*v
, *w
, *a
;
1854 Py_ssize_t i
, k
, size_v
, size_w
;
1856 digit wm1
, wm2
, carry
, q
, r
, vtop
, *v0
, *vk
, *w0
, *ak
;
1861 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
1862 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
1863 handle the special case when the initial estimate q for a quotient
1864 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
1865 that won't overflow a digit. */
1867 /* allocate space; w will also be used to hold the final remainder */
1868 size_v
= ABS(Py_SIZE(v1
));
1869 size_w
= ABS(Py_SIZE(w1
));
1870 assert(size_v
>= size_w
&& size_w
>= 2); /* Assert checks by div() */
1871 v
= _PyLong_New(size_v
+1);
1876 w
= _PyLong_New(size_w
);
1883 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
1884 shift v1 left by the same amount. Results go into w and v. */
1885 d
= PyLong_SHIFT
- bits_in_digit(w1
->ob_digit
[size_w
-1]);
1886 carry
= v_lshift(w
->ob_digit
, w1
->ob_digit
, size_w
, d
);
1888 carry
= v_lshift(v
->ob_digit
, v1
->ob_digit
, size_v
, d
);
1889 if (carry
!= 0 || v
->ob_digit
[size_v
-1] >= w
->ob_digit
[size_w
-1]) {
1890 v
->ob_digit
[size_v
] = carry
;
1894 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
1895 at most (and usually exactly) k = size_v - size_w digits. */
1896 k
= size_v
- size_w
;
1909 for (vk
= v0
+k
, ak
= a
->ob_digit
+ k
; vk
-- > v0
;) {
1910 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
1911 single-digit quotient q, remainder in vk[0:size_w]. */
1921 /* estimate quotient digit q; may overestimate by 1 (rare) */
1923 assert(vtop
<= wm1
);
1924 vv
= ((twodigits
)vtop
<< PyLong_SHIFT
) | vk
[size_w
-1];
1925 q
= (digit
)(vv
/ wm1
);
1926 r
= (digit
)(vv
- (twodigits
)wm1
* q
); /* r = vv % wm1 */
1927 while ((twodigits
)wm2
* q
> (((twodigits
)r
<< PyLong_SHIFT
)
1931 if (r
>= PyLong_BASE
)
1934 assert(q
<= PyLong_BASE
);
1936 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
1938 for (i
= 0; i
< size_w
; ++i
) {
1939 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
1940 -PyLong_BASE * q <= z < PyLong_BASE */
1941 z
= (sdigit
)vk
[i
] + zhi
-
1942 (stwodigits
)q
* (stwodigits
)w0
[i
];
1943 vk
[i
] = (digit
)z
& PyLong_MASK
;
1944 zhi
= (sdigit
)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits
,
1948 /* add w back if q was too large (this branch taken rarely) */
1949 assert((sdigit
)vtop
+ zhi
== -1 || (sdigit
)vtop
+ zhi
== 0);
1950 if ((sdigit
)vtop
+ zhi
< 0) {
1952 for (i
= 0; i
< size_w
; ++i
) {
1953 carry
+= vk
[i
] + w0
[i
];
1954 vk
[i
] = carry
& PyLong_MASK
;
1955 carry
>>= PyLong_SHIFT
;
1960 /* store quotient digit */
1961 assert(q
< PyLong_BASE
);
1965 /* unshift remainder; we reuse w to store the result */
1966 carry
= v_rshift(w0
, v0
, size_w
, d
);
1970 *prem
= long_normalize(w
);
1971 return long_normalize(a
);
1977 long_dealloc(PyObject
*v
)
1979 Py_TYPE(v
)->tp_free(v
);
1983 long_repr(PyObject
*v
)
1985 return _PyLong_Format(v
, 10, 1, 0);
1989 long_str(PyObject
*v
)
1991 return _PyLong_Format(v
, 10, 0, 0);
1995 long_compare(PyLongObject
*a
, PyLongObject
*b
)
1999 if (Py_SIZE(a
) != Py_SIZE(b
)) {
2000 if (ABS(Py_SIZE(a
)) == 0 && ABS(Py_SIZE(b
)) == 0)
2003 sign
= Py_SIZE(a
) - Py_SIZE(b
);
2006 Py_ssize_t i
= ABS(Py_SIZE(a
));
2007 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
2012 sign
= (sdigit
)a
->ob_digit
[i
] - (sdigit
)b
->ob_digit
[i
];
2017 return sign
< 0 ? -1 : sign
> 0 ? 1 : 0;
2021 long_hash(PyLongObject
*v
)
2027 /* This is designed so that Python ints and longs with the
2028 same value hash to the same value, otherwise comparisons
2029 of mapping keys will turn out weird */
2037 /* The following loop produces a C unsigned long x such that x is
2038 congruent to the absolute value of v modulo ULONG_MAX. The
2039 resulting x is nonzero if and only if v is. */
2041 /* Force a native long #-bits (32 or 64) circular shift */
2042 x
= (x
>> (8*SIZEOF_LONG
-PyLong_SHIFT
)) | (x
<< PyLong_SHIFT
);
2043 x
+= v
->ob_digit
[i
];
2044 /* If the addition above overflowed we compensate by
2045 incrementing. This preserves the value modulo
2047 if (x
< v
->ob_digit
[i
])
2051 if (x
== (unsigned long)-1)
2052 x
= (unsigned long)-2;
2057 /* Add the absolute values of two long integers. */
2059 static PyLongObject
*
2060 x_add(PyLongObject
*a
, PyLongObject
*b
)
2062 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
2067 /* Ensure a is the larger of the two: */
2068 if (size_a
< size_b
) {
2069 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2070 { Py_ssize_t size_temp
= size_a
;
2072 size_b
= size_temp
; }
2074 z
= _PyLong_New(size_a
+1);
2077 for (i
= 0; i
< size_b
; ++i
) {
2078 carry
+= a
->ob_digit
[i
] + b
->ob_digit
[i
];
2079 z
->ob_digit
[i
] = carry
& PyLong_MASK
;
2080 carry
>>= PyLong_SHIFT
;
2082 for (; i
< size_a
; ++i
) {
2083 carry
+= a
->ob_digit
[i
];
2084 z
->ob_digit
[i
] = carry
& PyLong_MASK
;
2085 carry
>>= PyLong_SHIFT
;
2087 z
->ob_digit
[i
] = carry
;
2088 return long_normalize(z
);
2091 /* Subtract the absolute values of two integers. */
2093 static PyLongObject
*
2094 x_sub(PyLongObject
*a
, PyLongObject
*b
)
2096 Py_ssize_t size_a
= ABS(Py_SIZE(a
)), size_b
= ABS(Py_SIZE(b
));
2102 /* Ensure a is the larger of the two: */
2103 if (size_a
< size_b
) {
2105 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2106 { Py_ssize_t size_temp
= size_a
;
2108 size_b
= size_temp
; }
2110 else if (size_a
== size_b
) {
2111 /* Find highest digit where a and b differ: */
2113 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
2116 return _PyLong_New(0);
2117 if (a
->ob_digit
[i
] < b
->ob_digit
[i
]) {
2119 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
2121 size_a
= size_b
= i
+1;
2123 z
= _PyLong_New(size_a
);
2126 for (i
= 0; i
< size_b
; ++i
) {
2127 /* The following assumes unsigned arithmetic
2128 works module 2**N for some N>PyLong_SHIFT. */
2129 borrow
= a
->ob_digit
[i
] - b
->ob_digit
[i
] - borrow
;
2130 z
->ob_digit
[i
] = borrow
& PyLong_MASK
;
2131 borrow
>>= PyLong_SHIFT
;
2132 borrow
&= 1; /* Keep only one sign bit */
2134 for (; i
< size_a
; ++i
) {
2135 borrow
= a
->ob_digit
[i
] - borrow
;
2136 z
->ob_digit
[i
] = borrow
& PyLong_MASK
;
2137 borrow
>>= PyLong_SHIFT
;
2138 borrow
&= 1; /* Keep only one sign bit */
2140 assert(borrow
== 0);
2142 z
->ob_size
= -(z
->ob_size
);
2143 return long_normalize(z
);
2147 long_add(PyLongObject
*v
, PyLongObject
*w
)
2149 PyLongObject
*a
, *b
, *z
;
2151 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2153 if (a
->ob_size
< 0) {
2154 if (b
->ob_size
< 0) {
2156 if (z
!= NULL
&& z
->ob_size
!= 0)
2157 z
->ob_size
= -(z
->ob_size
);
2170 return (PyObject
*)z
;
2174 long_sub(PyLongObject
*v
, PyLongObject
*w
)
2176 PyLongObject
*a
, *b
, *z
;
2178 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
2180 if (a
->ob_size
< 0) {
2185 if (z
!= NULL
&& z
->ob_size
!= 0)
2186 z
->ob_size
= -(z
->ob_size
);
2196 return (PyObject
*)z
;
2199 /* Grade school multiplication, ignoring the signs.
2200 * Returns the absolute value of the product, or NULL if error.
2202 static PyLongObject
*
2203 x_mul(PyLongObject
*a
, PyLongObject
*b
)
2206 Py_ssize_t size_a
= ABS(Py_SIZE(a
));
2207 Py_ssize_t size_b
= ABS(Py_SIZE(b
));
2210 z
= _PyLong_New(size_a
+ size_b
);
2214 memset(z
->ob_digit
, 0, Py_SIZE(z
) * sizeof(digit
));
2216 /* Efficient squaring per HAC, Algorithm 14.16:
2217 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2218 * Gives slightly less than a 2x speedup when a == b,
2219 * via exploiting that each entry in the multiplication
2220 * pyramid appears twice (except for the size_a squares).
2222 for (i
= 0; i
< size_a
; ++i
) {
2224 twodigits f
= a
->ob_digit
[i
];
2225 digit
*pz
= z
->ob_digit
+ (i
<< 1);
2226 digit
*pa
= a
->ob_digit
+ i
+ 1;
2227 digit
*paend
= a
->ob_digit
+ size_a
;
2234 carry
= *pz
+ f
* f
;
2235 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2236 carry
>>= PyLong_SHIFT
;
2237 assert(carry
<= PyLong_MASK
);
2239 /* Now f is added in twice in each column of the
2240 * pyramid it appears. Same as adding f<<1 once.
2243 while (pa
< paend
) {
2244 carry
+= *pz
+ *pa
++ * f
;
2245 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2246 carry
>>= PyLong_SHIFT
;
2247 assert(carry
<= (PyLong_MASK
<< 1));
2251 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2252 carry
>>= PyLong_SHIFT
;
2255 *pz
+= (digit
)(carry
& PyLong_MASK
);
2256 assert((carry
>> PyLong_SHIFT
) == 0);
2259 else { /* a is not the same as b -- gradeschool long mult */
2260 for (i
= 0; i
< size_a
; ++i
) {
2261 twodigits carry
= 0;
2262 twodigits f
= a
->ob_digit
[i
];
2263 digit
*pz
= z
->ob_digit
+ i
;
2264 digit
*pb
= b
->ob_digit
;
2265 digit
*pbend
= b
->ob_digit
+ size_b
;
2272 while (pb
< pbend
) {
2273 carry
+= *pz
+ *pb
++ * f
;
2274 *pz
++ = (digit
)(carry
& PyLong_MASK
);
2275 carry
>>= PyLong_SHIFT
;
2276 assert(carry
<= PyLong_MASK
);
2279 *pz
+= (digit
)(carry
& PyLong_MASK
);
2280 assert((carry
>> PyLong_SHIFT
) == 0);
2283 return long_normalize(z
);
2286 /* A helper for Karatsuba multiplication (k_mul).
2287 Takes a long "n" and an integer "size" representing the place to
2288 split, and sets low and high such that abs(n) == (high << size) + low,
2289 viewing the shift as being by digits. The sign bit is ignored, and
2290 the return values are >= 0.
2291 Returns 0 on success, -1 on failure.
2294 kmul_split(PyLongObject
*n
, Py_ssize_t size
, PyLongObject
**high
, PyLongObject
**low
)
2296 PyLongObject
*hi
, *lo
;
2297 Py_ssize_t size_lo
, size_hi
;
2298 const Py_ssize_t size_n
= ABS(Py_SIZE(n
));
2300 size_lo
= MIN(size_n
, size
);
2301 size_hi
= size_n
- size_lo
;
2303 if ((hi
= _PyLong_New(size_hi
)) == NULL
)
2305 if ((lo
= _PyLong_New(size_lo
)) == NULL
) {
2310 memcpy(lo
->ob_digit
, n
->ob_digit
, size_lo
* sizeof(digit
));
2311 memcpy(hi
->ob_digit
, n
->ob_digit
+ size_lo
, size_hi
* sizeof(digit
));
2313 *high
= long_normalize(hi
);
2314 *low
= long_normalize(lo
);
2318 static PyLongObject
*k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
);
2320 /* Karatsuba multiplication. Ignores the input signs, and returns the
2321 * absolute value of the product (or NULL if error).
2322 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2324 static PyLongObject
*
2325 k_mul(PyLongObject
*a
, PyLongObject
*b
)
2327 Py_ssize_t asize
= ABS(Py_SIZE(a
));
2328 Py_ssize_t bsize
= ABS(Py_SIZE(b
));
2329 PyLongObject
*ah
= NULL
;
2330 PyLongObject
*al
= NULL
;
2331 PyLongObject
*bh
= NULL
;
2332 PyLongObject
*bl
= NULL
;
2333 PyLongObject
*ret
= NULL
;
2334 PyLongObject
*t1
, *t2
, *t3
;
2335 Py_ssize_t shift
; /* the number of digits we split off */
2338 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2339 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2340 * Then the original product is
2341 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2342 * By picking X to be a power of 2, "*X" is just shifting, and it's
2343 * been reduced to 3 multiplies on numbers half the size.
2346 /* We want to split based on the larger number; fiddle so that b
2349 if (asize
> bsize
) {
2359 /* Use gradeschool math when either number is too small. */
2360 i
= a
== b
? KARATSUBA_SQUARE_CUTOFF
: KARATSUBA_CUTOFF
;
2363 return _PyLong_New(0);
2368 /* If a is small compared to b, splitting on b gives a degenerate
2369 * case with ah==0, and Karatsuba may be (even much) less efficient
2370 * than "grade school" then. However, we can still win, by viewing
2371 * b as a string of "big digits", each of width a->ob_size. That
2372 * leads to a sequence of balanced calls to k_mul.
2374 if (2 * asize
<= bsize
)
2375 return k_lopsided_mul(a
, b
);
2377 /* Split a & b into hi & lo pieces. */
2379 if (kmul_split(a
, shift
, &ah
, &al
) < 0) goto fail
;
2380 assert(Py_SIZE(ah
) > 0); /* the split isn't degenerate */
2388 else if (kmul_split(b
, shift
, &bh
, &bl
) < 0) goto fail
;
2391 * 1. Allocate result space (asize + bsize digits: that's always
2393 * 2. Compute ah*bh, and copy into result at 2*shift.
2394 * 3. Compute al*bl, and copy into result at 0. Note that this
2395 * can't overlap with #2.
2396 * 4. Subtract al*bl from the result, starting at shift. This may
2397 * underflow (borrow out of the high digit), but we don't care:
2398 * we're effectively doing unsigned arithmetic mod
2399 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
2400 * borrows and carries out of the high digit can be ignored.
2401 * 5. Subtract ah*bh from the result, starting at shift.
2402 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2406 /* 1. Allocate result space. */
2407 ret
= _PyLong_New(asize
+ bsize
);
2408 if (ret
== NULL
) goto fail
;
2410 /* Fill with trash, to catch reference to uninitialized digits. */
2411 memset(ret
->ob_digit
, 0xDF, Py_SIZE(ret
) * sizeof(digit
));
2414 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2415 if ((t1
= k_mul(ah
, bh
)) == NULL
) goto fail
;
2416 assert(Py_SIZE(t1
) >= 0);
2417 assert(2*shift
+ Py_SIZE(t1
) <= Py_SIZE(ret
));
2418 memcpy(ret
->ob_digit
+ 2*shift
, t1
->ob_digit
,
2419 Py_SIZE(t1
) * sizeof(digit
));
2421 /* Zero-out the digits higher than the ah*bh copy. */
2422 i
= Py_SIZE(ret
) - 2*shift
- Py_SIZE(t1
);
2424 memset(ret
->ob_digit
+ 2*shift
+ Py_SIZE(t1
), 0,
2427 /* 3. t2 <- al*bl, and copy into the low digits. */
2428 if ((t2
= k_mul(al
, bl
)) == NULL
) {
2432 assert(Py_SIZE(t2
) >= 0);
2433 assert(Py_SIZE(t2
) <= 2*shift
); /* no overlap with high digits */
2434 memcpy(ret
->ob_digit
, t2
->ob_digit
, Py_SIZE(t2
) * sizeof(digit
));
2436 /* Zero out remaining digits. */
2437 i
= 2*shift
- Py_SIZE(t2
); /* number of uninitialized digits */
2439 memset(ret
->ob_digit
+ Py_SIZE(t2
), 0, i
* sizeof(digit
));
2441 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2442 * because it's fresher in cache.
2444 i
= Py_SIZE(ret
) - shift
; /* # digits after shift */
2445 (void)v_isub(ret
->ob_digit
+ shift
, i
, t2
->ob_digit
, Py_SIZE(t2
));
2448 (void)v_isub(ret
->ob_digit
+ shift
, i
, t1
->ob_digit
, Py_SIZE(t1
));
2451 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2452 if ((t1
= x_add(ah
, al
)) == NULL
) goto fail
;
2461 else if ((t2
= x_add(bh
, bl
)) == NULL
) {
2472 if (t3
== NULL
) goto fail
;
2473 assert(Py_SIZE(t3
) >= 0);
2475 /* Add t3. It's not obvious why we can't run out of room here.
2476 * See the (*) comment after this function.
2478 (void)v_iadd(ret
->ob_digit
+ shift
, i
, t3
->ob_digit
, Py_SIZE(t3
));
2481 return long_normalize(ret
);
2492 /* (*) Why adding t3 can't "run out of room" above.
2494 Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2497 1. For any integer i, i = c(i/2) + f(i/2). In particular,
2498 bsize = c(bsize/2) + f(bsize/2).
2499 2. shift = f(bsize/2)
2501 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2502 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
2504 We allocated asize + bsize result digits, and add t3 into them at an offset
2505 of shift. This leaves asize+bsize-shift allocated digit positions for t3
2506 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2507 asize + c(bsize/2) available digit positions.
2509 bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2510 at most c(bsize/2) digits + 1 bit.
2512 If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2513 digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2514 most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
2516 The product (ah+al)*(bh+bl) therefore has at most
2518 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
2520 and we have asize + c(bsize/2) available digit positions. We need to show
2521 this is always enough. An instance of c(bsize/2) cancels out in both, so
2522 the question reduces to whether asize digits is enough to hold
2523 (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2524 then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2525 asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
2526 digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
2527 asize == bsize, then we're asking whether bsize digits is enough to hold
2528 c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2529 is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2530 bsize >= KARATSUBA_CUTOFF >= 2.
2532 Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2533 clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2534 ah*bh and al*bl too.
2537 /* b has at least twice the digits of a, and a is big enough that Karatsuba
2538 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2539 * of slices, each with a->ob_size digits, and multiply the slices by a,
2540 * one at a time. This gives k_mul balanced inputs to work with, and is
2541 * also cache-friendly (we compute one double-width slice of the result
2542 * at a time, then move on, never bactracking except for the helpful
2543 * single-width slice overlap between successive partial sums).
2545 static PyLongObject
*
2546 k_lopsided_mul(PyLongObject
*a
, PyLongObject
*b
)
2548 const Py_ssize_t asize
= ABS(Py_SIZE(a
));
2549 Py_ssize_t bsize
= ABS(Py_SIZE(b
));
2550 Py_ssize_t nbdone
; /* # of b digits already multiplied */
2552 PyLongObject
*bslice
= NULL
;
2554 assert(asize
> KARATSUBA_CUTOFF
);
2555 assert(2 * asize
<= bsize
);
2557 /* Allocate result space, and zero it out. */
2558 ret
= _PyLong_New(asize
+ bsize
);
2561 memset(ret
->ob_digit
, 0, Py_SIZE(ret
) * sizeof(digit
));
2563 /* Successive slices of b are copied into bslice. */
2564 bslice
= _PyLong_New(asize
);
2570 PyLongObject
*product
;
2571 const Py_ssize_t nbtouse
= MIN(bsize
, asize
);
2573 /* Multiply the next slice of b by a. */
2574 memcpy(bslice
->ob_digit
, b
->ob_digit
+ nbdone
,
2575 nbtouse
* sizeof(digit
));
2576 Py_SIZE(bslice
) = nbtouse
;
2577 product
= k_mul(a
, bslice
);
2578 if (product
== NULL
)
2581 /* Add into result. */
2582 (void)v_iadd(ret
->ob_digit
+ nbdone
, Py_SIZE(ret
) - nbdone
,
2583 product
->ob_digit
, Py_SIZE(product
));
2591 return long_normalize(ret
);
2600 long_mul(PyLongObject
*v
, PyLongObject
*w
)
2602 PyLongObject
*a
, *b
, *z
;
2604 if (!convert_binop((PyObject
*)v
, (PyObject
*)w
, &a
, &b
)) {
2605 Py_INCREF(Py_NotImplemented
);
2606 return Py_NotImplemented
;
2610 /* Negate if exactly one of the inputs is negative. */
2611 if (((a
->ob_size
^ b
->ob_size
) < 0) && z
)
2612 z
->ob_size
= -(z
->ob_size
);
2615 return (PyObject
*)z
;
2618 /* The / and % operators are now defined in terms of divmod().
2619 The expression a mod b has the value a - b*floor(a/b).
2620 The long_divrem function gives the remainder after division of
2621 |a| by |b|, with the sign of a. This is also expressed
2622 as a - b*trunc(a/b), if trunc truncates towards zero.
2629 So, to get from rem to mod, we have to add b if a and b
2630 have different signs. We then subtract one from the 'div'
2631 part of the outcome to keep the invariant intact. */
2634 * *pdiv, *pmod = divmod(v, w)
2635 * NULL can be passed for pdiv or pmod, in which case that part of
2636 * the result is simply thrown away. The caller owns a reference to
2637 * each of these it requests (does not pass NULL for).
2640 l_divmod(PyLongObject
*v
, PyLongObject
*w
,
2641 PyLongObject
**pdiv
, PyLongObject
**pmod
)
2643 PyLongObject
*div
, *mod
;
2645 if (long_divrem(v
, w
, &div
, &mod
) < 0)
2647 if ((Py_SIZE(mod
) < 0 && Py_SIZE(w
) > 0) ||
2648 (Py_SIZE(mod
) > 0 && Py_SIZE(w
) < 0)) {
2651 temp
= (PyLongObject
*) long_add(mod
, w
);
2658 one
= (PyLongObject
*) PyLong_FromLong(1L);
2660 (temp
= (PyLongObject
*) long_sub(div
, one
)) == NULL
) {
2684 long_div(PyObject
*v
, PyObject
*w
)
2686 PyLongObject
*a
, *b
, *div
;
2688 CONVERT_BINOP(v
, w
, &a
, &b
);
2689 if (l_divmod(a
, b
, &div
, NULL
) < 0)
2693 return (PyObject
*)div
;
2697 long_classic_div(PyObject
*v
, PyObject
*w
)
2699 PyLongObject
*a
, *b
, *div
;
2701 CONVERT_BINOP(v
, w
, &a
, &b
);
2702 if (Py_DivisionWarningFlag
&&
2703 PyErr_Warn(PyExc_DeprecationWarning
, "classic long division") < 0)
2705 else if (l_divmod(a
, b
, &div
, NULL
) < 0)
2709 return (PyObject
*)div
;
2713 long_true_divide(PyObject
*v
, PyObject
*w
)
2715 PyLongObject
*a
, *b
;
2717 int failed
, aexp
= -1, bexp
= -1;
2719 CONVERT_BINOP(v
, w
, &a
, &b
);
2720 ad
= _PyLong_AsScaledDouble((PyObject
*)a
, &aexp
);
2721 bd
= _PyLong_AsScaledDouble((PyObject
*)b
, &bexp
);
2722 failed
= (ad
== -1.0 || bd
== -1.0) && PyErr_Occurred();
2727 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2728 but should really be set correctly after sucessful calls to
2729 _PyLong_AsScaledDouble() */
2730 assert(aexp
>= 0 && bexp
>= 0);
2733 PyErr_SetString(PyExc_ZeroDivisionError
,
2734 "long division or modulo by zero");
2738 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
2739 ad
/= bd
; /* overflow/underflow impossible here */
2741 if (aexp
> INT_MAX
/ PyLong_SHIFT
)
2743 else if (aexp
< -(INT_MAX
/ PyLong_SHIFT
))
2744 return PyFloat_FromDouble(0.0); /* underflow to 0 */
2746 ad
= ldexp(ad
, aexp
* PyLong_SHIFT
);
2747 if (Py_OVERFLOWED(ad
)) /* ignore underflow to 0.0 */
2749 return PyFloat_FromDouble(ad
);
2752 PyErr_SetString(PyExc_OverflowError
,
2753 "long/long too large for a float");
2759 long_mod(PyObject
*v
, PyObject
*w
)
2761 PyLongObject
*a
, *b
, *mod
;
2763 CONVERT_BINOP(v
, w
, &a
, &b
);
2765 if (l_divmod(a
, b
, NULL
, &mod
) < 0)
2769 return (PyObject
*)mod
;
2773 long_divmod(PyObject
*v
, PyObject
*w
)
2775 PyLongObject
*a
, *b
, *div
, *mod
;
2778 CONVERT_BINOP(v
, w
, &a
, &b
);
2780 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
2787 PyTuple_SetItem(z
, 0, (PyObject
*) div
);
2788 PyTuple_SetItem(z
, 1, (PyObject
*) mod
);
2801 long_pow(PyObject
*v
, PyObject
*w
, PyObject
*x
)
2803 PyLongObject
*a
, *b
, *c
; /* a,b,c = v,w,x */
2804 int negativeOutput
= 0; /* if x<0 return negative output */
2806 PyLongObject
*z
= NULL
; /* accumulated result */
2807 Py_ssize_t i
, j
, k
; /* counters */
2808 PyLongObject
*temp
= NULL
;
2810 /* 5-ary values. If the exponent is large enough, table is
2811 * precomputed so that table[i] == a**i % c for i in range(32).
2813 PyLongObject
*table
[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2814 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2816 /* a, b, c = v, w, x */
2817 CONVERT_BINOP(v
, w
, &a
, &b
);
2818 if (PyLong_Check(x
)) {
2819 c
= (PyLongObject
*)x
;
2822 else if (PyInt_Check(x
)) {
2823 c
= (PyLongObject
*)PyLong_FromLong(PyInt_AS_LONG(x
));
2827 else if (x
== Py_None
)
2832 Py_INCREF(Py_NotImplemented
);
2833 return Py_NotImplemented
;
2836 if (Py_SIZE(b
) < 0) { /* if exponent is negative */
2838 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
2839 "cannot be negative when 3rd argument specified");
2843 /* else return a float. This works because we know
2844 that this calls float_pow() which converts its
2845 arguments to double. */
2848 return PyFloat_Type
.tp_as_number
->nb_power(v
, w
, x
);
2854 raise ValueError() */
2855 if (Py_SIZE(c
) == 0) {
2856 PyErr_SetString(PyExc_ValueError
,
2857 "pow() 3rd argument cannot be 0");
2862 negativeOutput = True
2863 modulus = -modulus */
2864 if (Py_SIZE(c
) < 0) {
2866 temp
= (PyLongObject
*)_PyLong_Copy(c
);
2872 c
->ob_size
= - c
->ob_size
;
2877 if ((Py_SIZE(c
) == 1) && (c
->ob_digit
[0] == 1)) {
2878 z
= (PyLongObject
*)PyLong_FromLong(0L);
2883 base = base % modulus
2884 Having the base positive just makes things easier. */
2885 if (Py_SIZE(a
) < 0) {
2886 if (l_divmod(a
, c
, NULL
, &temp
) < 0)
2894 /* At this point a, b, and c are guaranteed non-negative UNLESS
2895 c is NULL, in which case a may be negative. */
2897 z
= (PyLongObject
*)PyLong_FromLong(1L);
2901 /* Perform a modular reduction, X = X % c, but leave X alone if c
2906 if (l_divmod(X, c, NULL, &temp) < 0) \
2913 /* Multiply two values, then reduce the result:
2914 result = X*Y % c. If c is NULL, skip the mod. */
2915 #define MULT(X, Y, result) \
2917 temp = (PyLongObject *)long_mul(X, Y); \
2920 Py_XDECREF(result); \
2926 if (Py_SIZE(b
) <= FIVEARY_CUTOFF
) {
2927 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2928 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
2929 for (i
= Py_SIZE(b
) - 1; i
>= 0; --i
) {
2930 digit bi
= b
->ob_digit
[i
];
2932 for (j
= (digit
)1 << (PyLong_SHIFT
-1); j
!= 0; j
>>= 1) {
2940 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2941 Py_INCREF(z
); /* still holds 1L */
2943 for (i
= 1; i
< 32; ++i
)
2944 MULT(table
[i
-1], a
, table
[i
])
2946 for (i
= Py_SIZE(b
) - 1; i
>= 0; --i
) {
2947 const digit bi
= b
->ob_digit
[i
];
2949 for (j
= PyLong_SHIFT
- 5; j
>= 0; j
-= 5) {
2950 const int index
= (bi
>> j
) & 0x1f;
2951 for (k
= 0; k
< 5; ++k
)
2954 MULT(z
, table
[index
], z
)
2959 if (negativeOutput
&& (Py_SIZE(z
) != 0)) {
2960 temp
= (PyLongObject
*)long_sub(z
, c
);
2976 if (Py_SIZE(b
) > FIVEARY_CUTOFF
) {
2977 for (i
= 0; i
< 32; ++i
)
2978 Py_XDECREF(table
[i
]);
2984 return (PyObject
*)z
;
2988 long_invert(PyLongObject
*v
)
2990 /* Implement ~x as -(x+1) */
2993 w
= (PyLongObject
*)PyLong_FromLong(1L);
2996 x
= (PyLongObject
*) long_add(v
, w
);
3000 Py_SIZE(x
) = -(Py_SIZE(x
));
3001 return (PyObject
*)x
;
3005 long_neg(PyLongObject
*v
)
3008 if (v
->ob_size
== 0 && PyLong_CheckExact(v
)) {
3011 return (PyObject
*) v
;
3013 z
= (PyLongObject
*)_PyLong_Copy(v
);
3015 z
->ob_size
= -(v
->ob_size
);
3016 return (PyObject
*)z
;
3020 long_abs(PyLongObject
*v
)
3025 return long_long((PyObject
*)v
);
3029 long_nonzero(PyLongObject
*v
)
3031 return ABS(Py_SIZE(v
)) != 0;
3035 long_rshift(PyLongObject
*v
, PyLongObject
*w
)
3037 PyLongObject
*a
, *b
;
3038 PyLongObject
*z
= NULL
;
3040 Py_ssize_t newsize
, wordshift
, loshift
, hishift
, i
, j
;
3041 digit lomask
, himask
;
3043 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
3045 if (Py_SIZE(a
) < 0) {
3046 /* Right shifting negative numbers is harder */
3047 PyLongObject
*a1
, *a2
;
3048 a1
= (PyLongObject
*) long_invert(a
);
3051 a2
= (PyLongObject
*) long_rshift(a1
, b
);
3055 z
= (PyLongObject
*) long_invert(a2
);
3060 shiftby
= PyLong_AsLong((PyObject
*)b
);
3061 if (shiftby
== -1L && PyErr_Occurred())
3064 PyErr_SetString(PyExc_ValueError
,
3065 "negative shift count");
3068 wordshift
= shiftby
/ PyLong_SHIFT
;
3069 newsize
= ABS(Py_SIZE(a
)) - wordshift
;
3074 return (PyObject
*)z
;
3076 loshift
= shiftby
% PyLong_SHIFT
;
3077 hishift
= PyLong_SHIFT
- loshift
;
3078 lomask
= ((digit
)1 << hishift
) - 1;
3079 himask
= PyLong_MASK
^ lomask
;
3080 z
= _PyLong_New(newsize
);
3084 Py_SIZE(z
) = -(Py_SIZE(z
));
3085 for (i
= 0, j
= wordshift
; i
< newsize
; i
++, j
++) {
3086 z
->ob_digit
[i
] = (a
->ob_digit
[j
] >> loshift
) & lomask
;
3089 (a
->ob_digit
[j
+1] << hishift
) & himask
;
3091 z
= long_normalize(z
);
3096 return (PyObject
*) z
;
3101 long_lshift(PyObject
*v
, PyObject
*w
)
3103 /* This version due to Tim Peters */
3104 PyLongObject
*a
, *b
;
3105 PyLongObject
*z
= NULL
;
3107 Py_ssize_t oldsize
, newsize
, wordshift
, remshift
, i
, j
;
3110 CONVERT_BINOP(v
, w
, &a
, &b
);
3112 shiftby
= PyLong_AsLong((PyObject
*)b
);
3113 if (shiftby
== -1L && PyErr_Occurred())
3116 PyErr_SetString(PyExc_ValueError
, "negative shift count");
3119 if ((long)(int)shiftby
!= shiftby
) {
3120 PyErr_SetString(PyExc_ValueError
,
3121 "outrageous left shift count");
3124 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3125 wordshift
= (int)shiftby
/ PyLong_SHIFT
;
3126 remshift
= (int)shiftby
- wordshift
* PyLong_SHIFT
;
3128 oldsize
= ABS(a
->ob_size
);
3129 newsize
= oldsize
+ wordshift
;
3132 z
= _PyLong_New(newsize
);
3136 z
->ob_size
= -(z
->ob_size
);
3137 for (i
= 0; i
< wordshift
; i
++)
3140 for (i
= wordshift
, j
= 0; j
< oldsize
; i
++, j
++) {
3141 accum
|= (twodigits
)a
->ob_digit
[j
] << remshift
;
3142 z
->ob_digit
[i
] = (digit
)(accum
& PyLong_MASK
);
3143 accum
>>= PyLong_SHIFT
;
3146 z
->ob_digit
[newsize
-1] = (digit
)accum
;
3149 z
= long_normalize(z
);
3153 return (PyObject
*) z
;
3157 /* Bitwise and/xor/or operations */
3160 long_bitwise(PyLongObject
*a
,
3161 int op
, /* '&', '|', '^' */
3164 digit maska
, maskb
; /* 0 or PyLong_MASK */
3166 Py_ssize_t size_a
, size_b
, size_z
, i
;
3171 if (Py_SIZE(a
) < 0) {
3172 a
= (PyLongObject
*) long_invert(a
);
3175 maska
= PyLong_MASK
;
3181 if (Py_SIZE(b
) < 0) {
3182 b
= (PyLongObject
*) long_invert(b
);
3187 maskb
= PyLong_MASK
;
3197 if (maska
!= maskb
) {
3198 maska
^= PyLong_MASK
;
3203 if (maska
&& maskb
) {
3205 maska
^= PyLong_MASK
;
3206 maskb
^= PyLong_MASK
;
3211 if (maska
|| maskb
) {
3213 maska
^= PyLong_MASK
;
3214 maskb
^= PyLong_MASK
;
3220 /* JRH: The original logic here was to allocate the result value (z)
3221 as the longer of the two operands. However, there are some cases
3222 where the result is guaranteed to be shorter than that: AND of two
3223 positives, OR of two negatives: use the shorter number. AND with
3224 mixed signs: use the positive number. OR with mixed signs: use the
3225 negative number. After the transformations above, op will be '&'
3226 iff one of these cases applies, and mask will be non-0 for operands
3227 whose length should be ignored.
3230 size_a
= Py_SIZE(a
);
3231 size_b
= Py_SIZE(b
);
3235 : (maskb
? size_a
: MIN(size_a
, size_b
)))
3236 : MAX(size_a
, size_b
);
3237 z
= _PyLong_New(size_z
);
3244 for (i
= 0; i
< size_z
; ++i
) {
3245 diga
= (i
< size_a
? a
->ob_digit
[i
] : 0) ^ maska
;
3246 digb
= (i
< size_b
? b
->ob_digit
[i
] : 0) ^ maskb
;
3248 case '&': z
->ob_digit
[i
] = diga
& digb
; break;
3249 case '|': z
->ob_digit
[i
] = diga
| digb
; break;
3250 case '^': z
->ob_digit
[i
] = diga
^ digb
; break;
3256 z
= long_normalize(z
);
3258 return (PyObject
*) z
;
3265 long_and(PyObject
*v
, PyObject
*w
)
3267 PyLongObject
*a
, *b
;
3269 CONVERT_BINOP(v
, w
, &a
, &b
);
3270 c
= long_bitwise(a
, '&', b
);
3277 long_xor(PyObject
*v
, PyObject
*w
)
3279 PyLongObject
*a
, *b
;
3281 CONVERT_BINOP(v
, w
, &a
, &b
);
3282 c
= long_bitwise(a
, '^', b
);
3289 long_or(PyObject
*v
, PyObject
*w
)
3291 PyLongObject
*a
, *b
;
3293 CONVERT_BINOP(v
, w
, &a
, &b
);
3294 c
= long_bitwise(a
, '|', b
);
3301 long_coerce(PyObject
**pv
, PyObject
**pw
)
3303 if (PyInt_Check(*pw
)) {
3304 *pw
= PyLong_FromLong(PyInt_AS_LONG(*pw
));
3310 else if (PyLong_Check(*pw
)) {
3315 return 1; /* Can't do it */
3319 long_long(PyObject
*v
)
3321 if (PyLong_CheckExact(v
))
3324 v
= _PyLong_Copy((PyLongObject
*)v
);
3329 long_int(PyObject
*v
)
3332 x
= PyLong_AsLong(v
);
3333 if (PyErr_Occurred()) {
3334 if (PyErr_ExceptionMatches(PyExc_OverflowError
)) {
3336 if (PyLong_CheckExact(v
)) {
3341 return _PyLong_Copy((PyLongObject
*)v
);
3346 return PyInt_FromLong(x
);
3350 long_float(PyObject
*v
)
3353 result
= PyLong_AsDouble(v
);
3354 if (result
== -1.0 && PyErr_Occurred())
3356 return PyFloat_FromDouble(result
);
3360 long_oct(PyObject
*v
)
3362 return _PyLong_Format(v
, 8, 1, 0);
3366 long_hex(PyObject
*v
)
3368 return _PyLong_Format(v
, 16, 1, 0);
3372 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
3375 long_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3378 int base
= -909; /* unlikely! */
3379 static char *kwlist
[] = {"x", "base", 0};
3381 if (type
!= &PyLong_Type
)
3382 return long_subtype_new(type
, args
, kwds
); /* Wimp out */
3383 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:long", kwlist
,
3387 return PyLong_FromLong(0L);
3389 return PyNumber_Long(x
);
3390 else if (PyString_Check(x
)) {
3391 /* Since PyLong_FromString doesn't have a length parameter,
3392 * check here for possible NULs in the string. */
3393 char *string
= PyString_AS_STRING(x
);
3394 if (strlen(string
) != (size_t)PyString_Size(x
)) {
3395 /* create a repr() of the input string,
3396 * just like PyLong_FromString does. */
3398 srepr
= PyObject_Repr(x
);
3401 PyErr_Format(PyExc_ValueError
,
3402 "invalid literal for long() with base %d: %s",
3403 base
, PyString_AS_STRING(srepr
));
3407 return PyLong_FromString(PyString_AS_STRING(x
), NULL
, base
);
3409 #ifdef Py_USING_UNICODE
3410 else if (PyUnicode_Check(x
))
3411 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x
),
3412 PyUnicode_GET_SIZE(x
),
3416 PyErr_SetString(PyExc_TypeError
,
3417 "long() can't convert non-string with explicit base");
3422 /* Wimpy, slow approach to tp_new calls for subtypes of long:
3423 first create a regular long from whatever arguments we got,
3424 then allocate a subtype instance and initialize it from
3425 the regular long. The regular long is then thrown away.
3428 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3430 PyLongObject
*tmp
, *newobj
;
3433 assert(PyType_IsSubtype(type
, &PyLong_Type
));
3434 tmp
= (PyLongObject
*)long_new(&PyLong_Type
, args
, kwds
);
3437 assert(PyLong_CheckExact(tmp
));
3441 newobj
= (PyLongObject
*)type
->tp_alloc(type
, n
);
3442 if (newobj
== NULL
) {
3446 assert(PyLong_Check(newobj
));
3447 Py_SIZE(newobj
) = Py_SIZE(tmp
);
3448 for (i
= 0; i
< n
; i
++)
3449 newobj
->ob_digit
[i
] = tmp
->ob_digit
[i
];
3451 return (PyObject
*)newobj
;
3455 long_getnewargs(PyLongObject
*v
)
3457 return Py_BuildValue("(N)", _PyLong_Copy(v
));
3461 long_getN(PyLongObject
*v
, void *context
) {
3462 return PyLong_FromLong((Py_intptr_t
)context
);
3466 long__format__(PyObject
*self
, PyObject
*args
)
3468 PyObject
*format_spec
;
3470 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
3472 if (PyBytes_Check(format_spec
))
3473 return _PyLong_FormatAdvanced(self
,
3474 PyBytes_AS_STRING(format_spec
),
3475 PyBytes_GET_SIZE(format_spec
));
3476 if (PyUnicode_Check(format_spec
)) {
3477 /* Convert format_spec to a str */
3479 PyObject
*str_spec
= PyObject_Str(format_spec
);
3481 if (str_spec
== NULL
)
3484 result
= _PyLong_FormatAdvanced(self
,
3485 PyBytes_AS_STRING(str_spec
),
3486 PyBytes_GET_SIZE(str_spec
));
3488 Py_DECREF(str_spec
);
3491 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
3496 long_sizeof(PyLongObject
*v
)
3500 res
= v
->ob_type
->tp_basicsize
+ ABS(Py_SIZE(v
))*sizeof(digit
);
3501 return PyInt_FromSsize_t(res
);
3505 long_bit_length(PyLongObject
*v
)
3507 PyLongObject
*result
, *x
, *y
;
3508 Py_ssize_t ndigits
, msd_bits
= 0;
3512 assert(PyLong_Check(v
));
3514 ndigits
= ABS(Py_SIZE(v
));
3516 return PyInt_FromLong(0);
3518 msd
= v
->ob_digit
[ndigits
-1];
3523 msd_bits
+= (long)(BitLengthTable
[msd
]);
3525 if (ndigits
<= PY_SSIZE_T_MAX
/PyLong_SHIFT
)
3526 return PyInt_FromSsize_t((ndigits
-1)*PyLong_SHIFT
+ msd_bits
);
3528 /* expression above may overflow; use Python integers instead */
3529 result
= (PyLongObject
*)PyLong_FromSsize_t(ndigits
- 1);
3532 x
= (PyLongObject
*)PyLong_FromLong(PyLong_SHIFT
);
3535 y
= (PyLongObject
*)long_mul(result
, x
);
3542 x
= (PyLongObject
*)PyLong_FromLong(msd_bits
);
3545 y
= (PyLongObject
*)long_add(result
, x
);
3552 return (PyObject
*)result
;
3559 PyDoc_STRVAR(long_bit_length_doc
,
3560 "long.bit_length() -> int or long\n\
3562 Number of bits necessary to represent self in binary.\n\
3565 >>> (37L).bit_length()\n\
3570 long_is_finite(PyObject
*v
)
3576 static PyMethodDef long_methods
[] = {
3577 {"conjugate", (PyCFunction
)long_long
, METH_NOARGS
,
3578 "Returns self, the complex conjugate of any long."},
3579 {"bit_length", (PyCFunction
)long_bit_length
, METH_NOARGS
,
3580 long_bit_length_doc
},
3582 {"is_finite", (PyCFunction
)long_is_finite
, METH_NOARGS
,
3583 "Returns always True."},
3585 {"__trunc__", (PyCFunction
)long_long
, METH_NOARGS
,
3586 "Truncating an Integral returns itself."},
3587 {"__getnewargs__", (PyCFunction
)long_getnewargs
, METH_NOARGS
},
3588 {"__format__", (PyCFunction
)long__format__
, METH_VARARGS
},
3589 {"__sizeof__", (PyCFunction
)long_sizeof
, METH_NOARGS
,
3590 "Returns size in memory, in bytes"},
3591 {NULL
, NULL
} /* sentinel */
3594 static PyGetSetDef long_getset
[] = {
3596 (getter
)long_long
, (setter
)NULL
,
3597 "the real part of a complex number",
3600 (getter
)long_getN
, (setter
)NULL
,
3601 "the imaginary part of a complex number",
3604 (getter
)long_long
, (setter
)NULL
,
3605 "the numerator of a rational number in lowest terms",
3608 (getter
)long_getN
, (setter
)NULL
,
3609 "the denominator of a rational number in lowest terms",
3611 {NULL
} /* Sentinel */
3614 PyDoc_STRVAR(long_doc
,
3615 "long(x[, base]) -> integer\n\
3617 Convert a string or number to a long integer, if possible. A floating\n\
3618 point argument will be truncated towards zero (this does not include a\n\
3619 string representation of a floating point number!) When converting a\n\
3620 string, use the optional base. It is an error to supply a base when\n\
3621 converting a non-string.");
3623 static PyNumberMethods long_as_number
= {
3624 (binaryfunc
) long_add
, /*nb_add*/
3625 (binaryfunc
) long_sub
, /*nb_subtract*/
3626 (binaryfunc
) long_mul
, /*nb_multiply*/
3627 long_classic_div
, /*nb_divide*/
3628 long_mod
, /*nb_remainder*/
3629 long_divmod
, /*nb_divmod*/
3630 long_pow
, /*nb_power*/
3631 (unaryfunc
) long_neg
, /*nb_negative*/
3632 (unaryfunc
) long_long
, /*tp_positive*/
3633 (unaryfunc
) long_abs
, /*tp_absolute*/
3634 (inquiry
) long_nonzero
, /*tp_nonzero*/
3635 (unaryfunc
) long_invert
, /*nb_invert*/
3636 long_lshift
, /*nb_lshift*/
3637 (binaryfunc
) long_rshift
, /*nb_rshift*/
3638 long_and
, /*nb_and*/
3639 long_xor
, /*nb_xor*/
3641 long_coerce
, /*nb_coerce*/
3642 long_int
, /*nb_int*/
3643 long_long
, /*nb_long*/
3644 long_float
, /*nb_float*/
3645 long_oct
, /*nb_oct*/
3646 long_hex
, /*nb_hex*/
3647 0, /* nb_inplace_add */
3648 0, /* nb_inplace_subtract */
3649 0, /* nb_inplace_multiply */
3650 0, /* nb_inplace_divide */
3651 0, /* nb_inplace_remainder */
3652 0, /* nb_inplace_power */
3653 0, /* nb_inplace_lshift */
3654 0, /* nb_inplace_rshift */
3655 0, /* nb_inplace_and */
3656 0, /* nb_inplace_xor */
3657 0, /* nb_inplace_or */
3658 long_div
, /* nb_floor_divide */
3659 long_true_divide
, /* nb_true_divide */
3660 0, /* nb_inplace_floor_divide */
3661 0, /* nb_inplace_true_divide */
3662 long_long
, /* nb_index */
3665 PyTypeObject PyLong_Type
= {
3666 PyObject_HEAD_INIT(&PyType_Type
)
3668 "long", /* tp_name */
3669 offsetof(PyLongObject
, ob_digit
), /* tp_basicsize */
3670 sizeof(digit
), /* tp_itemsize */
3671 long_dealloc
, /* tp_dealloc */
3675 (cmpfunc
)long_compare
, /* tp_compare */
3676 long_repr
, /* tp_repr */
3677 &long_as_number
, /* tp_as_number */
3678 0, /* tp_as_sequence */
3679 0, /* tp_as_mapping */
3680 (hashfunc
)long_hash
, /* tp_hash */
3682 long_str
, /* tp_str */
3683 PyObject_GenericGetAttr
, /* tp_getattro */
3684 0, /* tp_setattro */
3685 0, /* tp_as_buffer */
3686 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
3687 Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_LONG_SUBCLASS
, /* tp_flags */
3688 long_doc
, /* tp_doc */
3689 0, /* tp_traverse */
3691 0, /* tp_richcompare */
3692 0, /* tp_weaklistoffset */
3694 0, /* tp_iternext */
3695 long_methods
, /* tp_methods */
3697 long_getset
, /* tp_getset */
3700 0, /* tp_descr_get */
3701 0, /* tp_descr_set */
3702 0, /* tp_dictoffset */
3705 long_new
, /* tp_new */
3706 PyObject_Del
, /* tp_free */
3709 static PyTypeObject Long_InfoType
;
3711 PyDoc_STRVAR(long_info__doc__
,
3714 A struct sequence that holds information about Python's\n\
3715 internal representation of integers. The attributes are read only.");
3717 static PyStructSequence_Field long_info_fields
[] = {
3718 {"bits_per_digit", "size of a digit in bits"},
3719 {"sizeof_digit", "size in bytes of the C type used to "
3720 "represent a digit"},
3724 static PyStructSequence_Desc long_info_desc
= {
3725 "sys.long_info", /* name */
3726 long_info__doc__
, /* doc */
3727 long_info_fields
, /* fields */
3728 2 /* number of fields */
3732 PyLong_GetInfo(void)
3734 PyObject
* long_info
;
3736 long_info
= PyStructSequence_New(&Long_InfoType
);
3737 if (long_info
== NULL
)
3739 PyStructSequence_SET_ITEM(long_info
, field
++, PyLong_FromLong(PyLong_SHIFT
));
3740 PyStructSequence_SET_ITEM(long_info
, field
++, PyLong_FromLong(sizeof(digit
)));
3741 if (PyErr_Occurred()) {
3742 Py_CLEAR(long_info
);
3751 /* initialize long_info */
3752 if (Long_InfoType
.tp_name
== 0)
3753 PyStructSequence_InitType(&Long_InfoType
, &long_info_desc
);