1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Integer object implementation */
42 #define LONG_MAX 0X7FFFFFFFL
46 #define LONG_MIN (-LONG_MAX-1)
54 #define LONG_BIT (CHAR_BIT * sizeof(long))
60 return LONG_MAX
; /* To initialize sys.maxint */
63 /* Standard Booleans */
65 PyIntObject _Py_ZeroStruct
= {
66 PyObject_HEAD_INIT(&PyInt_Type
)
70 PyIntObject _Py_TrueStruct
= {
71 PyObject_HEAD_INIT(&PyInt_Type
)
79 PyErr_SetString(PyExc_OverflowError
, msg
);
83 /* Integers are quite normal objects, to make object handling uniform.
84 (Using odd pointers to represent integers would save much space
85 but require extra checks for this special case throughout the code.)
86 Since, a typical Python program spends much of its time allocating
87 and deallocating integers, these operations should be very fast.
88 Therefore we use a dedicated allocation scheme with a much lower
89 overhead (in space and time) than straight malloc(): a simple
90 dedicated free list, filled when necessary with memory from malloc().
93 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
94 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
95 #define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
97 #define PyMem_MALLOC malloc
98 #define PyMem_FREE free
101 struct _intblock
*next
;
102 PyIntObject objects
[N_INTOBJECTS
];
105 typedef struct _intblock PyIntBlock
;
107 static PyIntBlock
*block_list
= NULL
;
108 static PyIntObject
*free_list
= NULL
;
114 p
= (PyIntObject
*)PyMem_MALLOC(sizeof(PyIntBlock
));
116 return (PyIntObject
*)PyErr_NoMemory();
117 ((PyIntBlock
*)p
)->next
= block_list
;
118 block_list
= (PyIntBlock
*)p
;
119 p
= &((PyIntBlock
*)p
)->objects
[0];
120 q
= p
+ N_INTOBJECTS
;
122 q
->ob_type
= (struct _typeobject
*)(q
-1);
124 return p
+ N_INTOBJECTS
- 1;
127 #ifndef NSMALLPOSINTS
128 #define NSMALLPOSINTS 100
130 #ifndef NSMALLNEGINTS
131 #define NSMALLNEGINTS 1
133 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
134 /* References to small integers are saved in this array so that they
136 The integers that are saved are those in the range
137 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
139 static PyIntObject
*small_ints
[NSMALLNEGINTS
+ NSMALLPOSINTS
];
142 int quick_int_allocs
, quick_neg_int_allocs
;
149 register PyIntObject
*v
;
150 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
151 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
&&
152 (v
= small_ints
[ival
+ NSMALLNEGINTS
]) != NULL
) {
158 quick_neg_int_allocs
++;
160 return (PyObject
*) v
;
163 if (free_list
== NULL
) {
164 if ((free_list
= fill_free_list()) == NULL
)
168 free_list
= (PyIntObject
*)v
->ob_type
;
169 v
->ob_type
= &PyInt_Type
;
171 _Py_NewReference((PyObject
*)v
);
172 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
173 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
) {
174 /* save this one for a following allocation */
176 small_ints
[ival
+ NSMALLNEGINTS
] = v
;
179 return (PyObject
*) v
;
186 v
->ob_type
= (struct _typeobject
*)free_list
;
192 register PyObject
*op
;
198 if (op
&& PyInt_Check(op
))
199 return PyInt_AS_LONG((PyIntObject
*) op
);
201 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
202 nb
->nb_int
== NULL
) {
207 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
210 if (!PyInt_Check(io
)) {
211 PyErr_SetString(PyExc_TypeError
,
212 "nb_int should return int object");
216 val
= PyInt_AS_LONG(io
);
223 PyInt_FromString(s
, pend
, base
)
230 char buffer
[256]; /* For errors */
232 if ((base
!= 0 && base
< 2) || base
> 36) {
233 PyErr_SetString(PyExc_ValueError
, "invalid base for int()");
237 while (*s
&& isspace(Py_CHARMASK(*s
)))
240 if (base
== 0 && s
[0] == '0')
241 x
= (long) PyOS_strtoul(s
, &end
, base
);
243 x
= PyOS_strtol(s
, &end
, base
);
244 if (end
== s
|| !isalnum(end
[-1]))
246 while (*end
&& isspace(Py_CHARMASK(*end
)))
250 sprintf(buffer
, "invalid literal for int(): %.200s", s
);
251 PyErr_SetString(PyExc_ValueError
, buffer
);
254 else if (errno
!= 0) {
255 sprintf(buffer
, "int() literal too large: %.200s", s
);
256 PyErr_SetString(PyExc_ValueError
, buffer
);
261 return PyInt_FromLong(x
);
268 int_print(v
, fp
, flags
)
271 int flags
; /* Not used but required by interface */
273 fprintf(fp
, "%ld", v
->ob_ival
);
282 sprintf(buf
, "%ld", v
->ob_ival
);
283 return PyString_FromString(buf
);
290 register long i
= v
->ob_ival
;
291 register long j
= w
->ob_ival
;
292 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
299 /* XXX If this is changed, you also need to change the way
300 Python's long, float and complex types are hashed. */
301 long x
= v
-> ob_ival
;
312 register long a
, b
, x
;
316 if ((x
^a
) < 0 && (x
^b
) < 0)
317 return err_ovf("integer addition");
318 return PyInt_FromLong(x
);
326 register long a
, b
, x
;
330 if ((x
^a
) < 0 && (x
^~b
) < 0)
331 return err_ovf("integer subtraction");
332 return PyInt_FromLong(x
);
336 Integer overflow checking used to be done using a double, but on 64
337 bit machines (where both long and double are 64 bit) this fails
338 because the double doesn't have enouvg precision. John Tromp suggests
339 the following algorithm:
341 Suppose again we normalize a and b to be nonnegative.
342 Let ah and al (bh and bl) be the high and low 32 bits of a (b, resp.).
343 Now we test ah and bh against zero and get essentially 3 possible outcomes.
345 1) both ah and bh > 0 : then report overflow
347 2) both ah and bh = 0 : then compute a*b and report overflow if it comes out
350 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if it's >= 2^31
351 compute al*bl and report overflow if it's negative
352 add (ah*bl)<<32 to al*bl and report overflow if
355 In case of no overflow the result is then negated if necessary.
357 The majority of cases will be 2), in which case this method is the same as
358 what I suggested before. If multiplication is expensive enough, then the
359 other method is faster on case 3), but also more work to program, so I
360 guess the above is the preferred solution.
369 long a
, b
, ah
, bh
, x
, y
;
374 ah
= a
>> (LONG_BIT
/2);
375 bh
= b
>> (LONG_BIT
/2);
377 /* Quick test for common case: two small positive ints */
379 if (ah
== 0 && bh
== 0) {
383 return PyInt_FromLong(x
);
386 /* Arrange that a >= b >= 0 */
391 /* Largest negative */
392 if (b
== 0 || b
== 1) {
400 ah
= a
>> (LONG_BIT
/2);
405 /* Largest negative */
406 if (a
== 0 || (a
== 1 && s
== 1)) {
414 bh
= b
>> (LONG_BIT
/2);
417 /* 1) both ah and bh > 0 : then report overflow */
419 if (ah
!= 0 && bh
!= 0)
422 /* 2) both ah and bh = 0 : then compute a*b and report
423 overflow if it comes out negative */
425 if (ah
== 0 && bh
== 0) {
429 return PyInt_FromLong(x
*s
);
438 /* bh not used beyond this point */
441 /* 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if
443 compute al*bl and report overflow if it's negative
444 add (ah*bl)<<32 to al*bl and report overflow if
446 (NB b == bl in this case, and we make a = al) */
449 if (y
>= (1L << (LONG_BIT
/2 - 1)))
451 a
&= (1L << (LONG_BIT
/2)) - 1;
455 x
+= y
<< (LONG_BIT
/2);
459 return PyInt_FromLong(x
* s
);
462 return err_ovf("integer multiplication");
466 i_divmod(x
, y
, p_xdivy
, p_xmody
)
467 register PyIntObject
*x
, *y
;
468 long *p_xdivy
, *p_xmody
;
470 long xi
= x
->ob_ival
;
471 long yi
= y
->ob_ival
;
475 PyErr_SetString(PyExc_ZeroDivisionError
,
476 "integer division or modulo");
481 if (yi
== -1 && -xi
< 0) {
482 /* most negative / -1 */
483 err_ovf("integer division");
489 xdivy
= - (xi
/ -yi
);
493 xdivy
= - (-xi
/ yi
);
497 xmody
= xi
- xdivy
*yi
;
498 if ((xmody
< 0 && yi
> 0) || (xmody
> 0 && yi
< 0)) {
513 if (i_divmod(x
, y
, &d
, &m
) < 0)
515 return PyInt_FromLong(d
);
524 if (i_divmod(x
, y
, &d
, &m
) < 0)
526 return PyInt_FromLong(m
);
535 if (i_divmod(x
, y
, &d
, &m
) < 0)
537 return Py_BuildValue("(ll)", d
, m
);
547 register long iv
, iw
, iz
=0, ix
, temp
, prev
;
551 PyErr_SetString(PyExc_ValueError
,
552 "integer to the negative power");
555 if ((PyObject
*)z
!= Py_None
) {
558 PyErr_SetString(PyExc_ValueError
,
559 "pow(x, y, z) with z==0");
564 * XXX: The original exponentiation code stopped looping
565 * when temp hit zero; this code will continue onwards
566 * unnecessarily, but at least it won't cause any errors.
567 * Hopefully the speed improvement from the fast exponentiation
568 * will compensate for the slight inefficiency.
569 * XXX: Better handling of overflows is desperately needed.
574 prev
= ix
; /* Save value for overflow check */
578 break; /* Avoid ix / 0 */
579 if (ix
/ temp
!= prev
)
580 return err_ovf("integer exponentiation");
582 iw
>>= 1; /* Shift exponent down by 1 bit */
585 temp
*= temp
; /* Square the value of temp */
586 if (prev
!=0 && temp
/prev
!=prev
)
587 return err_ovf("integer exponentiation");
589 /* If we did a multiplication, perform a modulo */
597 t1
=PyInt_FromLong(ix
);
598 t2
=PyInt_FromLong(iz
);
599 if (t1
==NULL
|| t2
==NULL
||
600 i_divmod((PyIntObject
*)t1
,
601 (PyIntObject
*)t2
, &div
, &mod
)<0)
611 return PyInt_FromLong(ix
);
613 register long iv
, iw
, ix
;
617 PyErr_SetString(PyExc_ValueError
,
618 "integer to the negative power");
621 if ((PyObject
*)z
!= Py_None
) {
622 PyErr_SetString(PyExc_TypeError
,
623 "pow(int, int, int) not yet supported");
631 break; /* 0 to some power -- avoid ix / 0 */
633 return err_ovf("integer exponentiation");
635 return PyInt_FromLong(ix
);
647 return err_ovf("integer negation");
648 return PyInt_FromLong(x
);
656 return (PyObject
*)v
;
673 return v
->ob_ival
!= 0;
680 return PyInt_FromLong(~v
->ob_ival
);
692 PyErr_SetString(PyExc_ValueError
, "negative shift count");
695 if (a
== 0 || b
== 0) {
697 return (PyObject
*) v
;
700 return PyInt_FromLong(0L);
702 a
= (unsigned long)a
<< b
;
703 return PyInt_FromLong(a
);
715 PyErr_SetString(PyExc_ValueError
, "negative shift count");
718 if (a
== 0 || b
== 0) {
720 return (PyObject
*) v
;
730 a
= ~( ~(unsigned long)a
>> b
);
732 a
= (unsigned long)a
>> b
;
734 return PyInt_FromLong(a
);
745 return PyInt_FromLong(a
& b
);
756 return PyInt_FromLong(a
^ b
);
767 return PyInt_FromLong(a
| b
);
775 return (PyObject
*)v
;
782 return PyLong_FromLong((v
-> ob_ival
));
789 return PyFloat_FromDouble((double)(v
-> ob_ival
));
797 long x
= v
-> ob_ival
;
801 sprintf(buf
, "0%lo", x
);
802 return PyString_FromString(buf
);
810 long x
= v
-> ob_ival
;
811 sprintf(buf
, "0x%lx", x
);
812 return PyString_FromString(buf
);
815 static PyNumberMethods int_as_number
= {
816 (binaryfunc
)int_add
, /*nb_add*/
817 (binaryfunc
)int_sub
, /*nb_subtract*/
818 (binaryfunc
)int_mul
, /*nb_multiply*/
819 (binaryfunc
)int_div
, /*nb_divide*/
820 (binaryfunc
)int_mod
, /*nb_remainder*/
821 (binaryfunc
)int_divmod
, /*nb_divmod*/
822 (ternaryfunc
)int_pow
, /*nb_power*/
823 (unaryfunc
)int_neg
, /*nb_negative*/
824 (unaryfunc
)int_pos
, /*nb_positive*/
825 (unaryfunc
)int_abs
, /*nb_absolute*/
826 (inquiry
)int_nonzero
, /*nb_nonzero*/
827 (unaryfunc
)int_invert
, /*nb_invert*/
828 (binaryfunc
)int_lshift
, /*nb_lshift*/
829 (binaryfunc
)int_rshift
, /*nb_rshift*/
830 (binaryfunc
)int_and
, /*nb_and*/
831 (binaryfunc
)int_xor
, /*nb_xor*/
832 (binaryfunc
)int_or
, /*nb_or*/
834 (unaryfunc
)int_int
, /*nb_int*/
835 (unaryfunc
)int_long
, /*nb_long*/
836 (unaryfunc
)int_float
, /*nb_float*/
837 (unaryfunc
)int_oct
, /*nb_oct*/
838 (unaryfunc
)int_hex
, /*nb_hex*/
841 PyTypeObject PyInt_Type
= {
842 PyObject_HEAD_INIT(&PyType_Type
)
847 (destructor
)int_dealloc
, /*tp_dealloc*/
848 (printfunc
)int_print
, /*tp_print*/
851 (cmpfunc
)int_compare
, /*tp_compare*/
852 (reprfunc
)int_repr
, /*tp_repr*/
853 &int_as_number
, /*tp_as_number*/
854 0, /*tp_as_sequence*/
856 (hashfunc
)int_hash
, /*tp_hash*/
863 PyIntBlock
*list
, *next
;
865 int bc
, bf
; /* block count, number of freed blocks */
866 int irem
, isum
; /* remaining unfreed ints per block, total */
868 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
871 i
= NSMALLNEGINTS
+ NSMALLPOSINTS
;
884 while (list
!= NULL
) {
887 for (i
= 0, p
= &list
->objects
[0];
890 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
895 list
->next
= block_list
;
897 for (i
= 0, p
= &list
->objects
[0];
900 if (!PyInt_Check(p
) || p
->ob_refcnt
== 0) {
901 p
->ob_type
= (struct _typeobject
*)
905 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
906 else if (-NSMALLNEGINTS
<= p
->ob_ival
&&
907 p
->ob_ival
< NSMALLPOSINTS
&&
908 small_ints
[p
->ob_ival
+
909 NSMALLNEGINTS
] == NULL
) {
911 small_ints
[p
->ob_ival
+
926 fprintf(stderr
, "# cleanup ints");
928 fprintf(stderr
, "\n");
932 ": %d unfreed int%s in %d out of %d block%s\n",
933 isum
, isum
== 1 ? "" : "s",
934 bc
- bf
, bc
, bc
== 1 ? "" : "s");
936 if (Py_VerboseFlag
> 1) {
938 while (list
!= NULL
) {
939 for (i
= 0, p
= &list
->objects
[0];
942 if (PyInt_Check(p
) && p
->ob_refcnt
!= 0)
944 "# <int at %lx, refcnt=%d, val=%ld>\n",
945 p
, p
->ob_refcnt
, p
->ob_ival
);