2 /* Integer object implementation */
10 return LONG_MAX
; /* To initialize sys.maxint */
13 /* Standard Booleans */
15 PyIntObject _Py_ZeroStruct
= {
16 PyObject_HEAD_INIT(&PyInt_Type
)
20 PyIntObject _Py_TrueStruct
= {
21 PyObject_HEAD_INIT(&PyInt_Type
)
28 PyErr_SetString(PyExc_OverflowError
, msg
);
32 /* Integers are quite normal objects, to make object handling uniform.
33 (Using odd pointers to represent integers would save much space
34 but require extra checks for this special case throughout the code.)
35 Since, a typical Python program spends much of its time allocating
36 and deallocating integers, these operations should be very fast.
37 Therefore we use a dedicated allocation scheme with a much lower
38 overhead (in space and time) than straight malloc(): a simple
39 dedicated free list, filled when necessary with memory from malloc().
42 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
43 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
44 #define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
47 struct _intblock
*next
;
48 PyIntObject objects
[N_INTOBJECTS
];
51 typedef struct _intblock PyIntBlock
;
53 static PyIntBlock
*block_list
= NULL
;
54 static PyIntObject
*free_list
= NULL
;
60 /* XXX Int blocks escape the object heap. Use PyObject_MALLOC ??? */
61 p
= (PyIntObject
*) PyMem_MALLOC(sizeof(PyIntBlock
));
63 return (PyIntObject
*) PyErr_NoMemory();
64 ((PyIntBlock
*)p
)->next
= block_list
;
65 block_list
= (PyIntBlock
*)p
;
66 p
= &((PyIntBlock
*)p
)->objects
[0];
69 q
->ob_type
= (struct _typeobject
*)(q
-1);
71 return p
+ N_INTOBJECTS
- 1;
75 #define NSMALLPOSINTS 100
78 #define NSMALLNEGINTS 1
80 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
81 /* References to small integers are saved in this array so that they
83 The integers that are saved are those in the range
84 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
86 static PyIntObject
*small_ints
[NSMALLNEGINTS
+ NSMALLPOSINTS
];
89 int quick_int_allocs
, quick_neg_int_allocs
;
93 PyInt_FromLong(long ival
)
95 register PyIntObject
*v
;
96 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
97 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
&&
98 (v
= small_ints
[ival
+ NSMALLNEGINTS
]) != NULL
) {
104 quick_neg_int_allocs
++;
106 return (PyObject
*) v
;
109 if (free_list
== NULL
) {
110 if ((free_list
= fill_free_list()) == NULL
)
113 /* PyObject_New is inlined */
115 free_list
= (PyIntObject
*)v
->ob_type
;
116 PyObject_INIT(v
, &PyInt_Type
);
118 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
119 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
) {
120 /* save this one for a following allocation */
122 small_ints
[ival
+ NSMALLNEGINTS
] = v
;
125 return (PyObject
*) v
;
129 int_dealloc(PyIntObject
*v
)
131 v
->ob_type
= (struct _typeobject
*)free_list
;
136 PyInt_AsLong(register PyObject
*op
)
142 if (op
&& PyInt_Check(op
))
143 return PyInt_AS_LONG((PyIntObject
*) op
);
145 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
146 nb
->nb_int
== NULL
) {
147 PyErr_SetString(PyExc_TypeError
, "an integer is required");
151 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
154 if (!PyInt_Check(io
)) {
155 PyErr_SetString(PyExc_TypeError
,
156 "nb_int should return int object");
160 val
= PyInt_AS_LONG(io
);
167 PyInt_FromString(char *s
, char **pend
, int base
)
171 char buffer
[256]; /* For errors */
173 if ((base
!= 0 && base
< 2) || base
> 36) {
174 PyErr_SetString(PyExc_ValueError
, "int() base must be >= 2 and <= 36");
178 while (*s
&& isspace(Py_CHARMASK(*s
)))
181 if (base
== 0 && s
[0] == '0')
182 x
= (long) PyOS_strtoul(s
, &end
, base
);
184 x
= PyOS_strtol(s
, &end
, base
);
185 if (end
== s
|| !isalnum(Py_CHARMASK(end
[-1])))
187 while (*end
&& isspace(Py_CHARMASK(*end
)))
191 sprintf(buffer
, "invalid literal for int(): %.200s", s
);
192 PyErr_SetString(PyExc_ValueError
, buffer
);
195 else if (errno
!= 0) {
196 sprintf(buffer
, "int() literal too large: %.200s", s
);
197 PyErr_SetString(PyExc_ValueError
, buffer
);
202 return PyInt_FromLong(x
);
206 PyInt_FromUnicode(Py_UNICODE
*s
, int length
, int base
)
210 if (length
>= sizeof(buffer
)) {
211 PyErr_SetString(PyExc_ValueError
,
212 "int() literal too large to convert");
215 if (PyUnicode_EncodeDecimal(s
, length
, buffer
, NULL
))
217 return PyInt_FromString(buffer
, NULL
, base
);
222 /* Integers are seen as the "smallest" of all numeric types and thus
223 don't have any knowledge about conversion of other types to
226 #define CONVERT_TO_LONG(obj, lng) \
227 if (PyInt_Check(obj)) { \
228 lng = PyInt_AS_LONG(obj); \
231 Py_INCREF(Py_NotImplemented); \
232 return Py_NotImplemented; \
237 int_print(PyIntObject
*v
, FILE *fp
, int flags
)
238 /* flags -- not used but required by interface */
240 fprintf(fp
, "%ld", v
->ob_ival
);
245 int_repr(PyIntObject
*v
)
248 sprintf(buf
, "%ld", v
->ob_ival
);
249 return PyString_FromString(buf
);
253 int_compare(PyIntObject
*v
, PyIntObject
*w
)
255 register long i
= v
->ob_ival
;
256 register long j
= w
->ob_ival
;
257 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
261 int_hash(PyIntObject
*v
)
263 /* XXX If this is changed, you also need to change the way
264 Python's long, float and complex types are hashed. */
265 long x
= v
-> ob_ival
;
272 int_add(PyIntObject
*v
, PyIntObject
*w
)
274 register long a
, b
, x
;
275 CONVERT_TO_LONG(v
, a
);
276 CONVERT_TO_LONG(w
, b
);
278 if ((x
^a
) < 0 && (x
^b
) < 0)
279 return err_ovf("integer addition");
280 return PyInt_FromLong(x
);
284 int_sub(PyIntObject
*v
, PyIntObject
*w
)
286 register long a
, b
, x
;
287 CONVERT_TO_LONG(v
, a
);
288 CONVERT_TO_LONG(w
, b
);
290 if ((x
^a
) < 0 && (x
^~b
) < 0)
291 return err_ovf("integer subtraction");
292 return PyInt_FromLong(x
);
296 Integer overflow checking used to be done using a double, but on 64
297 bit machines (where both long and double are 64 bit) this fails
298 because the double doesn't have enough precision. John Tromp suggests
299 the following algorithm:
301 Suppose again we normalize a and b to be nonnegative.
302 Let ah and al (bh and bl) be the high and low 32 bits of a (b, resp.).
303 Now we test ah and bh against zero and get essentially 3 possible outcomes.
305 1) both ah and bh > 0 : then report overflow
307 2) both ah and bh = 0 : then compute a*b and report overflow if it comes out
310 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if it's >= 2^31
311 compute al*bl and report overflow if it's negative
312 add (ah*bl)<<32 to al*bl and report overflow if
315 In case of no overflow the result is then negated if necessary.
317 The majority of cases will be 2), in which case this method is the same as
318 what I suggested before. If multiplication is expensive enough, then the
319 other method is faster on case 3), but also more work to program, so I
320 guess the above is the preferred solution.
325 int_mul(PyObject
*v
, PyObject
*w
)
327 long a
, b
, ah
, bh
, x
, y
;
330 if (v
->ob_type
->tp_as_sequence
&&
331 v
->ob_type
->tp_as_sequence
->sq_repeat
) {
334 return (*v
->ob_type
->tp_as_sequence
->sq_repeat
)(v
, a
);
336 else if (w
->ob_type
->tp_as_sequence
&&
337 w
->ob_type
->tp_as_sequence
->sq_repeat
) {
340 return (*w
->ob_type
->tp_as_sequence
->sq_repeat
)(w
, a
);
343 CONVERT_TO_LONG(v
, a
);
344 CONVERT_TO_LONG(w
, b
);
345 ah
= a
>> (LONG_BIT
/2);
346 bh
= b
>> (LONG_BIT
/2);
348 /* Quick test for common case: two small positive ints */
350 if (ah
== 0 && bh
== 0) {
354 return PyInt_FromLong(x
);
357 /* Arrange that a >= b >= 0 */
362 /* Largest negative */
363 if (b
== 0 || b
== 1) {
371 ah
= a
>> (LONG_BIT
/2);
376 /* Largest negative */
377 if (a
== 0 || (a
== 1 && s
== 1)) {
385 bh
= b
>> (LONG_BIT
/2);
388 /* 1) both ah and bh > 0 : then report overflow */
390 if (ah
!= 0 && bh
!= 0)
393 /* 2) both ah and bh = 0 : then compute a*b and report
394 overflow if it comes out negative */
396 if (ah
== 0 && bh
== 0) {
400 return PyInt_FromLong(x
*s
);
409 /* bh not used beyond this point */
412 /* 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if
414 compute al*bl and report overflow if it's negative
415 add (ah*bl)<<32 to al*bl and report overflow if
417 (NB b == bl in this case, and we make a = al) */
420 if (y
>= (1L << (LONG_BIT
/2 - 1)))
422 a
&= (1L << (LONG_BIT
/2)) - 1;
426 x
+= y
<< (LONG_BIT
/2);
430 return PyInt_FromLong(x
* s
);
433 return err_ovf("integer multiplication");
437 i_divmod(register long x
, register long y
,
438 long *p_xdivy
, long *p_xmody
)
443 PyErr_SetString(PyExc_ZeroDivisionError
,
444 "integer division or modulo by zero");
447 /* (-sys.maxint-1)/-1 is the only overflow case. */
448 if (y
== -1 && x
< 0 && x
== -x
) {
449 err_ovf("integer division");
453 xmody
= x
- xdivy
* y
;
454 /* If the signs of x and y differ, and the remainder is non-0,
455 * C89 doesn't define whether xdivy is now the floor or the
456 * ceiling of the infinitely precise quotient. We want the floor,
457 * and we have it iff the remainder's sign matches y's.
459 if (xmody
&& ((y
^ xmody
) < 0) /* i.e. and signs differ */) {
462 assert(xmody
&& ((y
^ xmody
) >= 0));
470 int_div(PyIntObject
*x
, PyIntObject
*y
)
474 CONVERT_TO_LONG(x
, xi
);
475 CONVERT_TO_LONG(y
, yi
);
476 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
478 return PyInt_FromLong(d
);
482 int_mod(PyIntObject
*x
, PyIntObject
*y
)
486 CONVERT_TO_LONG(x
, xi
);
487 CONVERT_TO_LONG(y
, yi
);
488 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
490 return PyInt_FromLong(m
);
494 int_divmod(PyIntObject
*x
, PyIntObject
*y
)
498 CONVERT_TO_LONG(x
, xi
);
499 CONVERT_TO_LONG(y
, yi
);
500 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
502 return Py_BuildValue("(ll)", d
, m
);
506 int_pow(PyIntObject
*v
, PyIntObject
*w
, PyIntObject
*z
)
509 register long iv
, iw
, iz
=0, ix
, temp
, prev
;
510 CONVERT_TO_LONG(v
, iv
);
511 CONVERT_TO_LONG(w
, iw
);
514 PyErr_SetString(PyExc_ValueError
,
515 "cannot raise integer to a negative power");
517 PyErr_SetString(PyExc_ZeroDivisionError
,
518 "cannot raise 0 to a negative power");
521 if ((PyObject
*)z
!= Py_None
) {
522 CONVERT_TO_LONG(z
, iz
);
524 PyErr_SetString(PyExc_ValueError
,
525 "pow() arg 3 cannot be 0");
530 * XXX: The original exponentiation code stopped looping
531 * when temp hit zero; this code will continue onwards
532 * unnecessarily, but at least it won't cause any errors.
533 * Hopefully the speed improvement from the fast exponentiation
534 * will compensate for the slight inefficiency.
535 * XXX: Better handling of overflows is desperately needed.
540 prev
= ix
; /* Save value for overflow check */
544 break; /* Avoid ix / 0 */
545 if (ix
/ temp
!= prev
)
546 return err_ovf("integer exponentiation");
548 iw
>>= 1; /* Shift exponent down by 1 bit */
551 temp
*= temp
; /* Square the value of temp */
552 if (prev
!=0 && temp
/prev
!=prev
)
553 return err_ovf("integer exponentiation");
555 /* If we did a multiplication, perform a modulo */
562 if (i_divmod(ix
, iz
, &div
, &mod
) < 0)
566 return PyInt_FromLong(ix
);
568 register long iv
, iw
, ix
;
569 CONVERT_TO_LONG(v
, iv
);
570 CONVERT_TO_LONG(w
, iw
);
572 PyErr_SetString(PyExc_ValueError
,
573 "integer to the negative power");
576 if ((PyObject
*)z
!= Py_None
) {
577 PyErr_SetString(PyExc_TypeError
,
578 "pow(int, int, int) not yet supported");
586 break; /* 0 to some power -- avoid ix / 0 */
588 return err_ovf("integer exponentiation");
590 return PyInt_FromLong(ix
);
595 int_neg(PyIntObject
*v
)
601 return err_ovf("integer negation");
602 return PyInt_FromLong(x
);
606 int_pos(PyIntObject
*v
)
609 return (PyObject
*)v
;
613 int_abs(PyIntObject
*v
)
622 int_nonzero(PyIntObject
*v
)
624 return v
->ob_ival
!= 0;
628 int_invert(PyIntObject
*v
)
630 return PyInt_FromLong(~v
->ob_ival
);
634 int_lshift(PyIntObject
*v
, PyIntObject
*w
)
637 CONVERT_TO_LONG(v
, a
);
638 CONVERT_TO_LONG(w
, b
);
640 PyErr_SetString(PyExc_ValueError
, "negative shift count");
643 if (a
== 0 || b
== 0) {
645 return (PyObject
*) v
;
648 return PyInt_FromLong(0L);
650 a
= (unsigned long)a
<< b
;
651 return PyInt_FromLong(a
);
655 int_rshift(PyIntObject
*v
, PyIntObject
*w
)
658 CONVERT_TO_LONG(v
, a
);
659 CONVERT_TO_LONG(w
, b
);
661 PyErr_SetString(PyExc_ValueError
, "negative shift count");
664 if (a
== 0 || b
== 0) {
666 return (PyObject
*) v
;
675 a
= Py_ARITHMETIC_RIGHT_SHIFT(long, a
, b
);
677 return PyInt_FromLong(a
);
681 int_and(PyIntObject
*v
, PyIntObject
*w
)
684 CONVERT_TO_LONG(v
, a
);
685 CONVERT_TO_LONG(w
, b
);
686 return PyInt_FromLong(a
& b
);
690 int_xor(PyIntObject
*v
, PyIntObject
*w
)
693 CONVERT_TO_LONG(v
, a
);
694 CONVERT_TO_LONG(w
, b
);
695 return PyInt_FromLong(a
^ b
);
699 int_or(PyIntObject
*v
, PyIntObject
*w
)
702 CONVERT_TO_LONG(v
, a
);
703 CONVERT_TO_LONG(w
, b
);
704 return PyInt_FromLong(a
| b
);
708 int_int(PyIntObject
*v
)
711 return (PyObject
*)v
;
715 int_long(PyIntObject
*v
)
717 return PyLong_FromLong((v
-> ob_ival
));
721 int_float(PyIntObject
*v
)
723 return PyFloat_FromDouble((double)(v
-> ob_ival
));
727 int_oct(PyIntObject
*v
)
730 long x
= v
-> ob_ival
;
734 sprintf(buf
, "0%lo", x
);
735 return PyString_FromString(buf
);
739 int_hex(PyIntObject
*v
)
742 long x
= v
-> ob_ival
;
743 sprintf(buf
, "0x%lx", x
);
744 return PyString_FromString(buf
);
747 static PyNumberMethods int_as_number
= {
748 (binaryfunc
)int_add
, /*nb_add*/
749 (binaryfunc
)int_sub
, /*nb_subtract*/
750 (binaryfunc
)int_mul
, /*nb_multiply*/
751 (binaryfunc
)int_div
, /*nb_divide*/
752 (binaryfunc
)int_mod
, /*nb_remainder*/
753 (binaryfunc
)int_divmod
, /*nb_divmod*/
754 (ternaryfunc
)int_pow
, /*nb_power*/
755 (unaryfunc
)int_neg
, /*nb_negative*/
756 (unaryfunc
)int_pos
, /*nb_positive*/
757 (unaryfunc
)int_abs
, /*nb_absolute*/
758 (inquiry
)int_nonzero
, /*nb_nonzero*/
759 (unaryfunc
)int_invert
, /*nb_invert*/
760 (binaryfunc
)int_lshift
, /*nb_lshift*/
761 (binaryfunc
)int_rshift
, /*nb_rshift*/
762 (binaryfunc
)int_and
, /*nb_and*/
763 (binaryfunc
)int_xor
, /*nb_xor*/
764 (binaryfunc
)int_or
, /*nb_or*/
766 (unaryfunc
)int_int
, /*nb_int*/
767 (unaryfunc
)int_long
, /*nb_long*/
768 (unaryfunc
)int_float
, /*nb_float*/
769 (unaryfunc
)int_oct
, /*nb_oct*/
770 (unaryfunc
)int_hex
, /*nb_hex*/
771 0, /*nb_inplace_add*/
772 0, /*nb_inplace_subtract*/
773 0, /*nb_inplace_multiply*/
774 0, /*nb_inplace_divide*/
775 0, /*nb_inplace_remainder*/
776 0, /*nb_inplace_power*/
777 0, /*nb_inplace_lshift*/
778 0, /*nb_inplace_rshift*/
779 0, /*nb_inplace_and*/
780 0, /*nb_inplace_xor*/
784 PyTypeObject PyInt_Type
= {
785 PyObject_HEAD_INIT(&PyType_Type
)
790 (destructor
)int_dealloc
, /*tp_dealloc*/
791 (printfunc
)int_print
, /*tp_print*/
794 (cmpfunc
)int_compare
, /*tp_compare*/
795 (reprfunc
)int_repr
, /*tp_repr*/
796 &int_as_number
, /*tp_as_number*/
797 0, /*tp_as_sequence*/
799 (hashfunc
)int_hash
, /*tp_hash*/
805 Py_TPFLAGS_CHECKTYPES
/*tp_flags*/
812 PyIntBlock
*list
, *next
;
814 int bc
, bf
; /* block count, number of freed blocks */
815 int irem
, isum
; /* remaining unfreed ints per block, total */
817 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
820 i
= NSMALLNEGINTS
+ NSMALLPOSINTS
;
833 while (list
!= NULL
) {
836 for (i
= 0, p
= &list
->objects
[0];
839 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
844 list
->next
= block_list
;
846 for (i
= 0, p
= &list
->objects
[0];
849 if (!PyInt_Check(p
) || p
->ob_refcnt
== 0) {
850 p
->ob_type
= (struct _typeobject
*)
854 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
855 else if (-NSMALLNEGINTS
<= p
->ob_ival
&&
856 p
->ob_ival
< NSMALLPOSINTS
&&
857 small_ints
[p
->ob_ival
+
858 NSMALLNEGINTS
] == NULL
) {
860 small_ints
[p
->ob_ival
+
867 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
875 fprintf(stderr
, "# cleanup ints");
877 fprintf(stderr
, "\n");
881 ": %d unfreed int%s in %d out of %d block%s\n",
882 isum
, isum
== 1 ? "" : "s",
883 bc
- bf
, bc
, bc
== 1 ? "" : "s");
885 if (Py_VerboseFlag
> 1) {
887 while (list
!= NULL
) {
888 for (i
= 0, p
= &list
->objects
[0];
891 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
893 "# <int at %p, refcnt=%d, val=%ld>\n",
894 p
, p
->ob_refcnt
, p
->ob_ival
);