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(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 xi
, register long yi
,
438 long *p_xdivy
, long *p_xmody
)
443 PyErr_SetString(PyExc_ZeroDivisionError
,
444 "integer division or modulo by zero");
449 if (yi
== -1 && -xi
< 0) {
450 /* most negative / -1 */
451 err_ovf("integer division");
457 xdivy
= - (xi
/ -yi
);
461 xdivy
= - (-xi
/ yi
);
465 xmody
= xi
- xdivy
*yi
;
466 if ((xmody
< 0 && yi
> 0) || (xmody
> 0 && yi
< 0)) {
476 int_div(PyIntObject
*x
, PyIntObject
*y
)
480 CONVERT_TO_LONG(x
, xi
);
481 CONVERT_TO_LONG(y
, yi
);
482 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
484 return PyInt_FromLong(d
);
488 int_mod(PyIntObject
*x
, PyIntObject
*y
)
492 CONVERT_TO_LONG(x
, xi
);
493 CONVERT_TO_LONG(y
, yi
);
494 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
496 return PyInt_FromLong(m
);
500 int_divmod(PyIntObject
*x
, PyIntObject
*y
)
504 CONVERT_TO_LONG(x
, xi
);
505 CONVERT_TO_LONG(y
, yi
);
506 if (i_divmod(xi
, yi
, &d
, &m
) < 0)
508 return Py_BuildValue("(ll)", d
, m
);
512 int_pow(PyIntObject
*v
, PyIntObject
*w
, PyIntObject
*z
)
515 register long iv
, iw
, iz
=0, ix
, temp
, prev
;
516 CONVERT_TO_LONG(v
, iv
);
517 CONVERT_TO_LONG(w
, iw
);
520 PyErr_SetString(PyExc_ValueError
,
521 "cannot raise integer to a negative power");
523 PyErr_SetString(PyExc_ZeroDivisionError
,
524 "cannot raise 0 to a negative power");
527 if ((PyObject
*)z
!= Py_None
) {
528 CONVERT_TO_LONG(z
, iz
);
530 PyErr_SetString(PyExc_ValueError
,
531 "pow() arg 3 cannot be 0");
536 * XXX: The original exponentiation code stopped looping
537 * when temp hit zero; this code will continue onwards
538 * unnecessarily, but at least it won't cause any errors.
539 * Hopefully the speed improvement from the fast exponentiation
540 * will compensate for the slight inefficiency.
541 * XXX: Better handling of overflows is desperately needed.
546 prev
= ix
; /* Save value for overflow check */
550 break; /* Avoid ix / 0 */
551 if (ix
/ temp
!= prev
)
552 return err_ovf("integer exponentiation");
554 iw
>>= 1; /* Shift exponent down by 1 bit */
557 temp
*= temp
; /* Square the value of temp */
558 if (prev
!=0 && temp
/prev
!=prev
)
559 return err_ovf("integer exponentiation");
561 /* If we did a multiplication, perform a modulo */
568 if (i_divmod(ix
, iz
, &div
, &mod
) < 0)
572 return PyInt_FromLong(ix
);
574 register long iv
, iw
, ix
;
575 CONVERT_TO_LONG(v
, iv
);
576 CONVERT_TO_LONG(w
, iw
);
578 PyErr_SetString(PyExc_ValueError
,
579 "integer to the negative power");
582 if ((PyObject
*)z
!= Py_None
) {
583 PyErr_SetString(PyExc_TypeError
,
584 "pow(int, int, int) not yet supported");
592 break; /* 0 to some power -- avoid ix / 0 */
594 return err_ovf("integer exponentiation");
596 return PyInt_FromLong(ix
);
601 int_neg(PyIntObject
*v
)
607 return err_ovf("integer negation");
608 return PyInt_FromLong(x
);
612 int_pos(PyIntObject
*v
)
615 return (PyObject
*)v
;
619 int_abs(PyIntObject
*v
)
628 int_nonzero(PyIntObject
*v
)
630 return v
->ob_ival
!= 0;
634 int_invert(PyIntObject
*v
)
636 return PyInt_FromLong(~v
->ob_ival
);
640 int_lshift(PyIntObject
*v
, PyIntObject
*w
)
643 CONVERT_TO_LONG(v
, a
);
644 CONVERT_TO_LONG(w
, b
);
646 PyErr_SetString(PyExc_ValueError
, "negative shift count");
649 if (a
== 0 || b
== 0) {
651 return (PyObject
*) v
;
654 return PyInt_FromLong(0L);
656 a
= (unsigned long)a
<< b
;
657 return PyInt_FromLong(a
);
661 int_rshift(PyIntObject
*v
, PyIntObject
*w
)
664 CONVERT_TO_LONG(v
, a
);
665 CONVERT_TO_LONG(w
, b
);
667 PyErr_SetString(PyExc_ValueError
, "negative shift count");
670 if (a
== 0 || b
== 0) {
672 return (PyObject
*) v
;
681 a
= Py_ARITHMETIC_RIGHT_SHIFT(long, a
, b
);
683 return PyInt_FromLong(a
);
687 int_and(PyIntObject
*v
, PyIntObject
*w
)
690 CONVERT_TO_LONG(v
, a
);
691 CONVERT_TO_LONG(w
, b
);
692 return PyInt_FromLong(a
& b
);
696 int_xor(PyIntObject
*v
, PyIntObject
*w
)
699 CONVERT_TO_LONG(v
, a
);
700 CONVERT_TO_LONG(w
, b
);
701 return PyInt_FromLong(a
^ b
);
705 int_or(PyIntObject
*v
, PyIntObject
*w
)
708 CONVERT_TO_LONG(v
, a
);
709 CONVERT_TO_LONG(w
, b
);
710 return PyInt_FromLong(a
| b
);
714 int_int(PyIntObject
*v
)
717 return (PyObject
*)v
;
721 int_long(PyIntObject
*v
)
723 return PyLong_FromLong((v
-> ob_ival
));
727 int_float(PyIntObject
*v
)
729 return PyFloat_FromDouble((double)(v
-> ob_ival
));
733 int_oct(PyIntObject
*v
)
736 long x
= v
-> ob_ival
;
740 sprintf(buf
, "0%lo", x
);
741 return PyString_FromString(buf
);
745 int_hex(PyIntObject
*v
)
748 long x
= v
-> ob_ival
;
749 sprintf(buf
, "0x%lx", x
);
750 return PyString_FromString(buf
);
753 static PyNumberMethods int_as_number
= {
754 (binaryfunc
)int_add
, /*nb_add*/
755 (binaryfunc
)int_sub
, /*nb_subtract*/
756 (binaryfunc
)int_mul
, /*nb_multiply*/
757 (binaryfunc
)int_div
, /*nb_divide*/
758 (binaryfunc
)int_mod
, /*nb_remainder*/
759 (binaryfunc
)int_divmod
, /*nb_divmod*/
760 (ternaryfunc
)int_pow
, /*nb_power*/
761 (unaryfunc
)int_neg
, /*nb_negative*/
762 (unaryfunc
)int_pos
, /*nb_positive*/
763 (unaryfunc
)int_abs
, /*nb_absolute*/
764 (inquiry
)int_nonzero
, /*nb_nonzero*/
765 (unaryfunc
)int_invert
, /*nb_invert*/
766 (binaryfunc
)int_lshift
, /*nb_lshift*/
767 (binaryfunc
)int_rshift
, /*nb_rshift*/
768 (binaryfunc
)int_and
, /*nb_and*/
769 (binaryfunc
)int_xor
, /*nb_xor*/
770 (binaryfunc
)int_or
, /*nb_or*/
772 (unaryfunc
)int_int
, /*nb_int*/
773 (unaryfunc
)int_long
, /*nb_long*/
774 (unaryfunc
)int_float
, /*nb_float*/
775 (unaryfunc
)int_oct
, /*nb_oct*/
776 (unaryfunc
)int_hex
, /*nb_hex*/
777 0, /*nb_inplace_add*/
778 0, /*nb_inplace_subtract*/
779 0, /*nb_inplace_multiply*/
780 0, /*nb_inplace_divide*/
781 0, /*nb_inplace_remainder*/
782 0, /*nb_inplace_power*/
783 0, /*nb_inplace_lshift*/
784 0, /*nb_inplace_rshift*/
785 0, /*nb_inplace_and*/
786 0, /*nb_inplace_xor*/
790 PyTypeObject PyInt_Type
= {
791 PyObject_HEAD_INIT(&PyType_Type
)
796 (destructor
)int_dealloc
, /*tp_dealloc*/
797 (printfunc
)int_print
, /*tp_print*/
800 (cmpfunc
)int_compare
, /*tp_compare*/
801 (reprfunc
)int_repr
, /*tp_repr*/
802 &int_as_number
, /*tp_as_number*/
803 0, /*tp_as_sequence*/
805 (hashfunc
)int_hash
, /*tp_hash*/
811 Py_TPFLAGS_CHECKTYPES
/*tp_flags*/
818 PyIntBlock
*list
, *next
;
820 int bc
, bf
; /* block count, number of freed blocks */
821 int irem
, isum
; /* remaining unfreed ints per block, total */
823 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
826 i
= NSMALLNEGINTS
+ NSMALLPOSINTS
;
839 while (list
!= NULL
) {
842 for (i
= 0, p
= &list
->objects
[0];
845 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
850 list
->next
= block_list
;
852 for (i
= 0, p
= &list
->objects
[0];
855 if (!PyInt_Check(p
) || p
->ob_refcnt
== 0) {
856 p
->ob_type
= (struct _typeobject
*)
860 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
861 else if (-NSMALLNEGINTS
<= p
->ob_ival
&&
862 p
->ob_ival
< NSMALLPOSINTS
&&
863 small_ints
[p
->ob_ival
+
864 NSMALLNEGINTS
] == NULL
) {
866 small_ints
[p
->ob_ival
+
873 PyMem_FREE(list
); /* XXX PyObject_FREE ??? */
881 fprintf(stderr
, "# cleanup ints");
883 fprintf(stderr
, "\n");
887 ": %d unfreed int%s in %d out of %d block%s\n",
888 isum
, isum
== 1 ? "" : "s",
889 bc
- bf
, bc
, bc
== 1 ? "" : "s");
891 if (Py_VerboseFlag
> 1) {
893 while (list
!= NULL
) {
894 for (i
= 0, p
= &list
->objects
[0];
897 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
899 "# <int at %p, refcnt=%d, val=%ld>\n",
900 p
, p
->ob_refcnt
, p
->ob_ival
);