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 not be used in advertising or publicity pertaining to
13 distribution of the software without specific, written prior permission.
15 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
16 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17 FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
18 FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 ******************************************************************/
25 /* Integer object implementation */
27 #include "allobjects.h"
28 #include "modsupport.h"
35 #define LONG_MAX 0X7FFFFFFFL
39 #define LONG_MIN (-LONG_MAX-1)
47 #define LONG_BIT (CHAR_BIT * sizeof(long))
53 return LONG_MAX
; /* To initialize sys.maxint */
56 /* Standard Booleans */
58 intobject FalseObject
= {
59 OB_HEAD_INIT(&Inttype
)
63 intobject TrueObject
= {
64 OB_HEAD_INIT(&Inttype
)
72 err_setstr(OverflowError
, msg
);
76 /* Integers are quite normal objects, to make object handling uniform.
77 (Using odd pointers to represent integers would save much space
78 but require extra checks for this special case throughout the code.)
79 Since, a typical Python program spends much of its time allocating
80 and deallocating integers, these operations should be very fast.
81 Therefore we use a dedicated allocation scheme with a much lower
82 overhead (in space and time) than straight malloc(): a simple
83 dedicated free list, filled when necessary with memory from malloc().
86 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
87 #define N_INTOBJECTS (BLOCK_SIZE / sizeof(intobject))
93 p
= NEW(intobject
, N_INTOBJECTS
);
95 return (intobject
*)err_nomem();
98 *(intobject
**)q
= q
-1;
99 *(intobject
**)q
= NULL
;
100 return p
+ N_INTOBJECTS
- 1;
103 static intobject
*free_list
= NULL
;
104 #ifndef NSMALLPOSINTS
105 #define NSMALLPOSINTS 100
107 #ifndef NSMALLNEGINTS
108 #define NSMALLNEGINTS 1
110 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
111 /* References to small integers are saved in this array so that they
113 The integers that are saved are those in the range
114 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
116 static intobject
*small_ints
[NSMALLNEGINTS
+ NSMALLPOSINTS
];
119 int quick_int_allocs
, quick_neg_int_allocs
;
126 register intobject
*v
;
127 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
128 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
&&
129 (v
= small_ints
[ival
+ NSMALLNEGINTS
]) != NULL
) {
135 quick_neg_int_allocs
++;
140 if (free_list
== NULL
) {
141 if ((free_list
= fill_free_list()) == NULL
)
145 free_list
= *(intobject
**)free_list
;
146 v
->ob_type
= &Inttype
;
149 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
150 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
) {
151 /* save this one for a following allocation */
153 small_ints
[ival
+ NSMALLNEGINTS
] = v
;
163 *(intobject
**)v
= free_list
;
175 if (op
&& is_intobject(op
))
176 return GETINTVALUE((intobject
*) op
);
178 if (op
== NULL
|| (nb
= op
->ob_type
->tp_as_number
) == NULL
||
179 nb
->nb_int
== NULL
) {
184 io
= (intobject
*) (*nb
->nb_int
) (op
);
187 if (!is_intobject(io
)) {
188 err_setstr(TypeError
, "nb_int should return int object");
192 val
= GETINTVALUE(io
);
202 int_print(v
, fp
, flags
)
205 int flags
; /* Not used but required by interface */
207 fprintf(fp
, "%ld", v
->ob_ival
);
216 sprintf(buf
, "%ld", v
->ob_ival
);
217 return newstringobject(buf
);
224 register long i
= v
->ob_ival
;
225 register long j
= w
->ob_ival
;
226 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
233 long x
= v
-> ob_ival
;
244 register long a
, b
, x
;
248 if ((x
^a
) < 0 && (x
^b
) < 0)
249 return err_ovf("integer addition");
250 return newintobject(x
);
258 register long a
, b
, x
;
262 if ((x
^a
) < 0 && (x
^~b
) < 0)
263 return err_ovf("integer subtraction");
264 return newintobject(x
);
268 Integer overflow checking used to be done using a double, but on 64
269 bit machines (where both long and double are 64 bit) this fails
270 because the double doesn't have enouvg precision. John Tromp suggests
271 the following algorithm:
273 Suppose again we normalize a and b to be nonnegative.
274 Let ah and al (bh and bl) be the high and low 32 bits of a (b, resp.).
275 Now we test ah and bh against zero and get essentially 3 possible outcomes.
277 1) both ah and bh > 0 : then report overflow
279 2) both ah and bh = 0 : then compute a*b and report overflow if it comes out
282 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if it's >= 2^31
283 compute al*bl and report overflow if it's negative
284 add (ah*bl)<<32 to al*bl and report overflow if
287 In case of no overflow the result is then negated if necessary.
289 The majority of cases will be 2), in which case this method is the same as
290 what I suggested before. If multiplication is expensive enough, then the
291 other method is faster on case 3), but also more work to program, so I
292 guess the above is the preferred solution.
301 long a
, b
, ah
, bh
, x
, y
;
306 ah
= a
>> (LONG_BIT
/2);
307 bh
= b
>> (LONG_BIT
/2);
309 /* Quick test for common case: two small positive ints */
311 if (ah
== 0 && bh
== 0) {
315 return newintobject(x
);
318 /* Arrange that a >= b >= 0 */
323 /* Largest negative */
324 if (b
== 0 || b
== 1) {
332 ah
= a
>> (LONG_BIT
/2);
337 /* Largest negative */
338 if (a
== 0 || a
== 1 && s
== 1) {
346 bh
= b
>> (LONG_BIT
/2);
349 /* 1) both ah and bh > 0 : then report overflow */
351 if (ah
!= 0 && bh
!= 0)
354 /* 2) both ah and bh = 0 : then compute a*b and report
355 overflow if it comes out negative */
357 if (ah
== 0 && bh
== 0) {
361 return newintobject(x
*s
);
370 /* bh not used beyond this point */
373 /* 3) ah > 0 and bh = 0 : compute ah*bl and report overflow if
375 compute al*bl and report overflow if it's negative
376 add (ah*bl)<<32 to al*bl and report overflow if
378 (NB b == bl in this case, and we make a = al) */
381 if (y
>= (1L << (LONG_BIT
/2)))
383 a
&= (1L << (LONG_BIT
/2)) - 1;
387 x
+= y
<< LONG_BIT
/2;
391 return newintobject(x
* s
);
394 return err_ovf("integer multiplication");
398 i_divmod(x
, y
, p_xdivy
, p_xmody
)
399 register intobject
*x
, *y
;
400 long *p_xdivy
, *p_xmody
;
402 long xi
= x
->ob_ival
;
403 long yi
= y
->ob_ival
;
407 err_setstr(ZeroDivisionError
, "integer division or modulo");
414 xdivy
= - (xi
/ -yi
);
418 xdivy
= - (-xi
/ yi
);
422 xmody
= xi
- xdivy
*yi
;
423 if (xmody
< 0 && yi
> 0 || xmody
> 0 && yi
< 0) {
438 if (i_divmod(x
, y
, &d
, &m
) < 0)
440 return newintobject(d
);
449 if (i_divmod(x
, y
, &d
, &m
) < 0)
451 return newintobject(m
);
460 if (i_divmod(x
, y
, &d
, &m
) < 0)
462 return mkvalue("(ll)", d
, m
);
472 register long iv
, iw
, iz
, ix
, temp
, prev
;
477 err_setstr(ValueError
, "integer to the negative power");
480 if ((object
*)z
!= None
) {
485 * XXX: The original exponentiation code stopped looping
486 * when temp hit zero; this code will continue onwards
487 * unnecessarily, but at least it won't cause any errors.
488 * Hopefully the speed improvement from the fast exponentiation
489 * will compensate for the slight inefficiency.
490 * XXX: Better handling of overflows is desperately needed.
495 prev
= ix
; /* Save value for overflow check */
499 break; /* Avoid ix / 0 */
500 if (ix
/ temp
!= prev
)
501 return err_ovf("integer pow()");
503 iw
>>= 1; /* Shift exponent down by 1 bit */
506 temp
*= temp
; /* Square the value of temp */
507 if (prev
!=0 && temp
/prev
!=prev
)
508 return err_ovf("integer pow()");
510 /* If we did a multiplication, perform a modulo */
520 if (t1
==NULL
|| t2
==NULL
||
521 i_divmod((intobject
*)t1
, (intobject
*)t2
, &div
, &mod
)<0) {
530 return newintobject(ix
);
532 register long iv
, iw
, ix
;
536 err_setstr(ValueError
, "integer to the negative power");
539 if ((object
*)z
!= None
) {
540 err_setstr(TypeError
, "pow(int, int, int) not yet supported");
548 break; /* 0 to some power -- avoid ix / 0 */
550 return err_ovf("integer pow()");
552 return newintobject(ix
);
564 return err_ovf("integer negation");
565 return newintobject(x
);
590 return v
->ob_ival
!= 0;
597 return newintobject(~v
->ob_ival
);
609 err_setstr(ValueError
, "negative shift count");
612 if (a
== 0 || b
== 0) {
617 return newintobject(0L);
619 a
= (unsigned long)a
<< b
;
620 return newintobject(a
);
632 err_setstr(ValueError
, "negative shift count");
635 if (a
== 0 || b
== 0) {
647 a
= ~( ~(unsigned long)a
>> b
);
649 a
= (unsigned long)a
>> b
;
651 return newintobject(a
);
662 return newintobject(a
& b
);
673 return newintobject(a
^ b
);
684 return newintobject(a
| b
);
699 return newlongobject((v
-> ob_ival
));
706 return newfloatobject((double)(v
-> ob_ival
));
714 long x
= v
-> ob_ival
;
718 sprintf(buf
, "0%lo", x
);
720 sprintf(buf
, "-0%lo", -x
);
721 return newstringobject(buf
);
729 long x
= v
-> ob_ival
;
731 sprintf(buf
, "0x%lx", x
);
733 sprintf(buf
, "-0x%lx", -x
);
734 return newstringobject(buf
);
737 static number_methods int_as_number
= {
738 (binaryfunc
)int_add
, /*nb_add*/
739 (binaryfunc
)int_sub
, /*nb_subtract*/
740 (binaryfunc
)int_mul
, /*nb_multiply*/
741 (binaryfunc
)int_div
, /*nb_divide*/
742 (binaryfunc
)int_mod
, /*nb_remainder*/
743 (binaryfunc
)int_divmod
, /*nb_divmod*/
744 (ternaryfunc
)int_pow
, /*nb_power*/
745 (unaryfunc
)int_neg
, /*nb_negative*/
746 (unaryfunc
)int_pos
, /*nb_positive*/
747 (unaryfunc
)int_abs
, /*nb_absolute*/
748 (inquiry
)int_nonzero
, /*nb_nonzero*/
749 (unaryfunc
)int_invert
, /*nb_invert*/
750 (binaryfunc
)int_lshift
, /*nb_lshift*/
751 (binaryfunc
)int_rshift
, /*nb_rshift*/
752 (binaryfunc
)int_and
, /*nb_and*/
753 (binaryfunc
)int_xor
, /*nb_xor*/
754 (binaryfunc
)int_or
, /*nb_or*/
756 (unaryfunc
)int_int
, /*nb_int*/
757 (unaryfunc
)int_long
, /*nb_long*/
758 (unaryfunc
)int_float
, /*nb_float*/
759 (unaryfunc
)int_oct
, /*nb_oct*/
760 (unaryfunc
)int_hex
, /*nb_hex*/
763 typeobject Inttype
= {
764 OB_HEAD_INIT(&Typetype
)
769 (destructor
)int_dealloc
, /*tp_dealloc*/
770 (printfunc
)int_print
, /*tp_print*/
773 (cmpfunc
)int_compare
, /*tp_compare*/
774 (reprfunc
)int_repr
, /*tp_repr*/
775 &int_as_number
, /*tp_as_number*/
776 0, /*tp_as_sequence*/
778 (hashfunc
)int_hash
, /*tp_hash*/