2 /* Integer object implementation */
7 static PyObject
*int_int(PyIntObject
*v
);
12 return LONG_MAX
; /* To initialize sys.maxint */
15 /* Integers are quite normal objects, to make object handling uniform.
16 (Using odd pointers to represent integers would save much space
17 but require extra checks for this special case throughout the code.)
18 Since a typical Python program spends much of its time allocating
19 and deallocating integers, these operations should be very fast.
20 Therefore we use a dedicated allocation scheme with a much lower
21 overhead (in space and time) than straight malloc(): a simple
22 dedicated free list, filled when necessary with memory from malloc().
24 block_list is a singly-linked list of all PyIntBlocks ever allocated,
25 linked via their next members. PyIntBlocks are never returned to the
26 system before shutdown (PyInt_Fini).
28 free_list is a singly-linked list of available PyIntObjects, linked
29 via abuse of their ob_type members.
32 #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
33 #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
34 #define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
37 struct _intblock
*next
;
38 PyIntObject objects
[N_INTOBJECTS
];
41 typedef struct _intblock PyIntBlock
;
43 static PyIntBlock
*block_list
= NULL
;
44 static PyIntObject
*free_list
= NULL
;
50 /* Python's object allocator isn't appropriate for large blocks. */
51 p
= (PyIntObject
*) PyMem_MALLOC(sizeof(PyIntBlock
));
53 return (PyIntObject
*) PyErr_NoMemory();
54 ((PyIntBlock
*)p
)->next
= block_list
;
55 block_list
= (PyIntBlock
*)p
;
56 /* Link the int objects together, from rear to front, then return
57 the address of the last int object in the block. */
58 p
= &((PyIntBlock
*)p
)->objects
[0];
61 Py_TYPE(q
) = (struct _typeobject
*)(q
-1);
63 return p
+ N_INTOBJECTS
- 1;
67 #define NSMALLPOSINTS 257
70 #define NSMALLNEGINTS 5
72 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
73 /* References to small integers are saved in this array so that they
75 The integers that are saved are those in the range
76 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
78 static PyIntObject
*small_ints
[NSMALLNEGINTS
+ NSMALLPOSINTS
];
81 Py_ssize_t quick_int_allocs
;
82 Py_ssize_t quick_neg_int_allocs
;
86 PyInt_FromLong(long ival
)
88 register PyIntObject
*v
;
89 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
90 if (-NSMALLNEGINTS
<= ival
&& ival
< NSMALLPOSINTS
) {
91 v
= small_ints
[ival
+ NSMALLNEGINTS
];
97 quick_neg_int_allocs
++;
99 return (PyObject
*) v
;
102 if (free_list
== NULL
) {
103 if ((free_list
= fill_free_list()) == NULL
)
106 /* Inline PyObject_New */
108 free_list
= (PyIntObject
*)Py_TYPE(v
);
109 PyObject_INIT(v
, &PyInt_Type
);
111 return (PyObject
*) v
;
115 PyInt_FromSize_t(size_t ival
)
117 if (ival
<= LONG_MAX
)
118 return PyInt_FromLong((long)ival
);
119 return _PyLong_FromSize_t(ival
);
123 PyInt_FromSsize_t(Py_ssize_t ival
)
125 if (ival
>= LONG_MIN
&& ival
<= LONG_MAX
)
126 return PyInt_FromLong((long)ival
);
127 return _PyLong_FromSsize_t(ival
);
131 int_dealloc(PyIntObject
*v
)
133 if (PyInt_CheckExact(v
)) {
134 Py_TYPE(v
) = (struct _typeobject
*)free_list
;
138 Py_TYPE(v
)->tp_free((PyObject
*)v
);
142 int_free(PyIntObject
*v
)
144 Py_TYPE(v
) = (struct _typeobject
*)free_list
;
149 PyInt_AsLong(register PyObject
*op
)
155 if (op
&& PyInt_Check(op
))
156 return PyInt_AS_LONG((PyIntObject
*) op
);
158 if (op
== NULL
|| (nb
= Py_TYPE(op
)->tp_as_number
) == NULL
||
159 nb
->nb_int
== NULL
) {
160 PyErr_SetString(PyExc_TypeError
, "an integer is required");
164 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
167 if (!PyInt_Check(io
)) {
168 if (PyLong_Check(io
)) {
169 /* got a long? => retry int conversion */
170 val
= PyLong_AsLong((PyObject
*)io
);
172 if ((val
== -1) && PyErr_Occurred())
179 PyErr_SetString(PyExc_TypeError
,
180 "nb_int should return int object");
185 val
= PyInt_AS_LONG(io
);
192 PyInt_AsSsize_t(register PyObject
*op
)
194 #if SIZEOF_SIZE_T != SIZEOF_LONG
201 PyErr_SetString(PyExc_TypeError
, "an integer is required");
206 return PyInt_AS_LONG((PyIntObject
*) op
);
207 if (PyLong_Check(op
))
208 return _PyLong_AsSsize_t(op
);
209 #if SIZEOF_SIZE_T == SIZEOF_LONG
210 return PyInt_AsLong(op
);
213 if ((nb
= Py_TYPE(op
)->tp_as_number
) == NULL
||
214 (nb
->nb_int
== NULL
&& nb
->nb_long
== 0)) {
215 PyErr_SetString(PyExc_TypeError
, "an integer is required");
219 if (nb
->nb_long
!= 0)
220 io
= (PyIntObject
*) (*nb
->nb_long
) (op
);
222 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
225 if (!PyInt_Check(io
)) {
226 if (PyLong_Check(io
)) {
227 /* got a long? => retry int conversion */
228 val
= _PyLong_AsSsize_t((PyObject
*)io
);
230 if ((val
== -1) && PyErr_Occurred())
237 PyErr_SetString(PyExc_TypeError
,
238 "nb_int should return int object");
243 val
= PyInt_AS_LONG(io
);
251 PyInt_AsUnsignedLongMask(register PyObject
*op
)
257 if (op
&& PyInt_Check(op
))
258 return PyInt_AS_LONG((PyIntObject
*) op
);
259 if (op
&& PyLong_Check(op
))
260 return PyLong_AsUnsignedLongMask(op
);
262 if (op
== NULL
|| (nb
= Py_TYPE(op
)->tp_as_number
) == NULL
||
263 nb
->nb_int
== NULL
) {
264 PyErr_SetString(PyExc_TypeError
, "an integer is required");
265 return (unsigned long)-1;
268 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
270 return (unsigned long)-1;
271 if (!PyInt_Check(io
)) {
272 if (PyLong_Check(io
)) {
273 val
= PyLong_AsUnsignedLongMask((PyObject
*)io
);
275 if (PyErr_Occurred())
276 return (unsigned long)-1;
282 PyErr_SetString(PyExc_TypeError
,
283 "nb_int should return int object");
284 return (unsigned long)-1;
288 val
= PyInt_AS_LONG(io
);
294 #ifdef HAVE_LONG_LONG
295 unsigned PY_LONG_LONG
296 PyInt_AsUnsignedLongLongMask(register PyObject
*op
)
300 unsigned PY_LONG_LONG val
;
302 if (op
&& PyInt_Check(op
))
303 return PyInt_AS_LONG((PyIntObject
*) op
);
304 if (op
&& PyLong_Check(op
))
305 return PyLong_AsUnsignedLongLongMask(op
);
307 if (op
== NULL
|| (nb
= Py_TYPE(op
)->tp_as_number
) == NULL
||
308 nb
->nb_int
== NULL
) {
309 PyErr_SetString(PyExc_TypeError
, "an integer is required");
310 return (unsigned PY_LONG_LONG
)-1;
313 io
= (PyIntObject
*) (*nb
->nb_int
) (op
);
315 return (unsigned PY_LONG_LONG
)-1;
316 if (!PyInt_Check(io
)) {
317 if (PyLong_Check(io
)) {
318 val
= PyLong_AsUnsignedLongLongMask((PyObject
*)io
);
320 if (PyErr_Occurred())
321 return (unsigned PY_LONG_LONG
)-1;
327 PyErr_SetString(PyExc_TypeError
,
328 "nb_int should return int object");
329 return (unsigned PY_LONG_LONG
)-1;
333 val
= PyInt_AS_LONG(io
);
341 PyInt_FromString(char *s
, char **pend
, int base
)
346 PyObject
*sobj
, *srepr
;
348 if ((base
!= 0 && base
< 2) || base
> 36) {
349 PyErr_SetString(PyExc_ValueError
,
350 "int() base must be >= 2 and <= 36");
354 while (*s
&& isspace(Py_CHARMASK(*s
)))
357 if (base
== 0 && s
[0] == '0') {
358 x
= (long) PyOS_strtoul(s
, &end
, base
);
360 return PyLong_FromString(s
, pend
, base
);
363 x
= PyOS_strtol(s
, &end
, base
);
364 if (end
== s
|| !isalnum(Py_CHARMASK(end
[-1])))
366 while (*end
&& isspace(Py_CHARMASK(*end
)))
370 slen
= strlen(s
) < 200 ? strlen(s
) : 200;
371 sobj
= PyString_FromStringAndSize(s
, slen
);
374 srepr
= PyObject_Repr(sobj
);
378 PyErr_Format(PyExc_ValueError
,
379 "invalid literal for int() with base %d: %s",
380 base
, PyString_AS_STRING(srepr
));
385 return PyLong_FromString(s
, pend
, base
);
388 return PyInt_FromLong(x
);
391 #ifdef Py_USING_UNICODE
393 PyInt_FromUnicode(Py_UNICODE
*s
, Py_ssize_t length
, int base
)
396 char *buffer
= (char *)PyMem_MALLOC(length
+1);
399 return PyErr_NoMemory();
401 if (PyUnicode_EncodeDecimal(s
, length
, buffer
, NULL
)) {
405 result
= PyInt_FromString(buffer
, NULL
, base
);
413 /* Integers are seen as the "smallest" of all numeric types and thus
414 don't have any knowledge about conversion of other types to
417 #define CONVERT_TO_LONG(obj, lng) \
418 if (PyInt_Check(obj)) { \
419 lng = PyInt_AS_LONG(obj); \
422 Py_INCREF(Py_NotImplemented); \
423 return Py_NotImplemented; \
428 int_print(PyIntObject
*v
, FILE *fp
, int flags
)
429 /* flags -- not used but required by interface */
431 long int_val
= v
->ob_ival
;
432 Py_BEGIN_ALLOW_THREADS
433 fprintf(fp
, "%ld", int_val
);
439 int_repr(PyIntObject
*v
)
441 return _PyInt_Format(v
, 10, 0);
445 int_compare(PyIntObject
*v
, PyIntObject
*w
)
447 register long i
= v
->ob_ival
;
448 register long j
= w
->ob_ival
;
449 return (i
< j
) ? -1 : (i
> j
) ? 1 : 0;
453 int_hash(PyIntObject
*v
)
455 /* XXX If this is changed, you also need to change the way
456 Python's long, float and complex types are hashed. */
457 long x
= v
-> ob_ival
;
464 int_add(PyIntObject
*v
, PyIntObject
*w
)
466 register long a
, b
, x
;
467 CONVERT_TO_LONG(v
, a
);
468 CONVERT_TO_LONG(w
, b
);
470 if ((x
^a
) >= 0 || (x
^b
) >= 0)
471 return PyInt_FromLong(x
);
472 return PyLong_Type
.tp_as_number
->nb_add((PyObject
*)v
, (PyObject
*)w
);
476 int_sub(PyIntObject
*v
, PyIntObject
*w
)
478 register long a
, b
, x
;
479 CONVERT_TO_LONG(v
, a
);
480 CONVERT_TO_LONG(w
, b
);
482 if ((x
^a
) >= 0 || (x
^~b
) >= 0)
483 return PyInt_FromLong(x
);
484 return PyLong_Type
.tp_as_number
->nb_subtract((PyObject
*)v
,
489 Integer overflow checking for * is painful: Python tried a couple ways, but
490 they didn't work on all platforms, or failed in endcases (a product of
491 -sys.maxint-1 has been a particular pain).
495 The native long product x*y is either exactly right or *way* off, being
496 just the last n bits of the true product, where n is the number of bits
497 in a long (the delivered product is the true product plus i*2**n for
500 The native double product (double)x * (double)y is subject to three
501 rounding errors: on a sizeof(long)==8 box, each cast to double can lose
502 info, and even on a sizeof(long)==4 box, the multiplication can lose info.
503 But, unlike the native long product, it's not in *range* trouble: even
504 if sizeof(long)==32 (256-bit longs), the product easily fits in the
505 dynamic range of a double. So the leading 50 (or so) bits of the double
508 We check these two ways against each other, and declare victory if they're
509 approximately the same. Else, because the native long product is the only
510 one that can lose catastrophic amounts of information, it's the native long
511 product that must have overflowed.
515 int_mul(PyObject
*v
, PyObject
*w
)
518 long longprod
; /* a*b in native long arithmetic */
519 double doubled_longprod
; /* (double)longprod */
520 double doubleprod
; /* (double)a * (double)b */
522 CONVERT_TO_LONG(v
, a
);
523 CONVERT_TO_LONG(w
, b
);
525 doubleprod
= (double)a
* (double)b
;
526 doubled_longprod
= (double)longprod
;
528 /* Fast path for normal case: small multiplicands, and no info
529 is lost in either method. */
530 if (doubled_longprod
== doubleprod
)
531 return PyInt_FromLong(longprod
);
533 /* Somebody somewhere lost info. Close enough, or way off? Note
534 that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
535 The difference either is or isn't significant compared to the
536 true value (of which doubleprod is a good approximation).
539 const double diff
= doubled_longprod
- doubleprod
;
540 const double absdiff
= diff
>= 0.0 ? diff
: -diff
;
541 const double absprod
= doubleprod
>= 0.0 ? doubleprod
:
543 /* absdiff/absprod <= 1/32 iff
544 32 * absdiff <= absprod -- 5 good bits is "close enough" */
545 if (32.0 * absdiff
<= absprod
)
546 return PyInt_FromLong(longprod
);
548 return PyLong_Type
.tp_as_number
->nb_multiply(v
, w
);
552 /* Integer overflow checking for unary negation: on a 2's-complement
553 * box, -x overflows iff x is the most negative long. In this case we
554 * get -x == x. However, -x is undefined (by C) if x /is/ the most
555 * negative long (it's a signed overflow case), and some compilers care.
556 * So we cast x to unsigned long first. However, then other compilers
557 * warn about applying unary minus to an unsigned operand. Hence the
560 #define UNARY_NEG_WOULD_OVERFLOW(x) \
561 ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
563 /* Return type of i_divmod */
565 DIVMOD_OK
, /* Correct result */
566 DIVMOD_OVERFLOW
, /* Overflow, try again using longs */
567 DIVMOD_ERROR
/* Exception raised */
570 static enum divmod_result
571 i_divmod(register long x
, register long y
,
572 long *p_xdivy
, long *p_xmody
)
577 PyErr_SetString(PyExc_ZeroDivisionError
,
578 "integer division or modulo by zero");
581 /* (-sys.maxint-1)/-1 is the only overflow case. */
582 if (y
== -1 && UNARY_NEG_WOULD_OVERFLOW(x
))
583 return DIVMOD_OVERFLOW
;
585 xmody
= x
- xdivy
* y
;
586 /* If the signs of x and y differ, and the remainder is non-0,
587 * C89 doesn't define whether xdivy is now the floor or the
588 * ceiling of the infinitely precise quotient. We want the floor,
589 * and we have it iff the remainder's sign matches y's.
591 if (xmody
&& ((y
^ xmody
) < 0) /* i.e. and signs differ */) {
594 assert(xmody
&& ((y
^ xmody
) >= 0));
602 int_div(PyIntObject
*x
, PyIntObject
*y
)
606 CONVERT_TO_LONG(x
, xi
);
607 CONVERT_TO_LONG(y
, yi
);
608 switch (i_divmod(xi
, yi
, &d
, &m
)) {
610 return PyInt_FromLong(d
);
611 case DIVMOD_OVERFLOW
:
612 return PyLong_Type
.tp_as_number
->nb_divide((PyObject
*)x
,
620 int_classic_div(PyIntObject
*x
, PyIntObject
*y
)
624 CONVERT_TO_LONG(x
, xi
);
625 CONVERT_TO_LONG(y
, yi
);
626 if (Py_DivisionWarningFlag
&&
627 PyErr_Warn(PyExc_DeprecationWarning
, "classic int division") < 0)
629 switch (i_divmod(xi
, yi
, &d
, &m
)) {
631 return PyInt_FromLong(d
);
632 case DIVMOD_OVERFLOW
:
633 return PyLong_Type
.tp_as_number
->nb_divide((PyObject
*)x
,
641 int_true_divide(PyObject
*v
, PyObject
*w
)
643 /* If they aren't both ints, give someone else a chance. In
644 particular, this lets int/long get handled by longs, which
645 underflows to 0 gracefully if the long is too big to convert
647 if (PyInt_Check(v
) && PyInt_Check(w
))
648 return PyFloat_Type
.tp_as_number
->nb_true_divide(v
, w
);
649 Py_INCREF(Py_NotImplemented
);
650 return Py_NotImplemented
;
654 int_mod(PyIntObject
*x
, PyIntObject
*y
)
658 CONVERT_TO_LONG(x
, xi
);
659 CONVERT_TO_LONG(y
, yi
);
660 switch (i_divmod(xi
, yi
, &d
, &m
)) {
662 return PyInt_FromLong(m
);
663 case DIVMOD_OVERFLOW
:
664 return PyLong_Type
.tp_as_number
->nb_remainder((PyObject
*)x
,
672 int_divmod(PyIntObject
*x
, PyIntObject
*y
)
676 CONVERT_TO_LONG(x
, xi
);
677 CONVERT_TO_LONG(y
, yi
);
678 switch (i_divmod(xi
, yi
, &d
, &m
)) {
680 return Py_BuildValue("(ll)", d
, m
);
681 case DIVMOD_OVERFLOW
:
682 return PyLong_Type
.tp_as_number
->nb_divmod((PyObject
*)x
,
690 int_pow(PyIntObject
*v
, PyIntObject
*w
, PyIntObject
*z
)
692 register long iv
, iw
, iz
=0, ix
, temp
, prev
;
693 CONVERT_TO_LONG(v
, iv
);
694 CONVERT_TO_LONG(w
, iw
);
696 if ((PyObject
*)z
!= Py_None
) {
697 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
698 "cannot be negative when 3rd argument specified");
701 /* Return a float. This works because we know that
702 this calls float_pow() which converts its
703 arguments to double. */
704 return PyFloat_Type
.tp_as_number
->nb_power(
705 (PyObject
*)v
, (PyObject
*)w
, (PyObject
*)z
);
707 if ((PyObject
*)z
!= Py_None
) {
708 CONVERT_TO_LONG(z
, iz
);
710 PyErr_SetString(PyExc_ValueError
,
711 "pow() 3rd argument cannot be 0");
716 * XXX: The original exponentiation code stopped looping
717 * when temp hit zero; this code will continue onwards
718 * unnecessarily, but at least it won't cause any errors.
719 * Hopefully the speed improvement from the fast exponentiation
720 * will compensate for the slight inefficiency.
721 * XXX: Better handling of overflows is desperately needed.
726 prev
= ix
; /* Save value for overflow check */
730 break; /* Avoid ix / 0 */
731 if (ix
/ temp
!= prev
) {
732 return PyLong_Type
.tp_as_number
->nb_power(
738 iw
>>= 1; /* Shift exponent down by 1 bit */
741 temp
*= temp
; /* Square the value of temp */
742 if (prev
!= 0 && temp
/ prev
!= prev
) {
743 return PyLong_Type
.tp_as_number
->nb_power(
744 (PyObject
*)v
, (PyObject
*)w
, (PyObject
*)z
);
747 /* If we did a multiplication, perform a modulo */
754 switch (i_divmod(ix
, iz
, &div
, &mod
)) {
758 case DIVMOD_OVERFLOW
:
759 return PyLong_Type
.tp_as_number
->nb_power(
760 (PyObject
*)v
, (PyObject
*)w
, (PyObject
*)z
);
765 return PyInt_FromLong(ix
);
769 int_neg(PyIntObject
*v
)
773 /* check for overflow */
774 if (UNARY_NEG_WOULD_OVERFLOW(a
)) {
775 PyObject
*o
= PyLong_FromLong(a
);
777 PyObject
*result
= PyNumber_Negative(o
);
783 return PyInt_FromLong(-a
);
787 int_abs(PyIntObject
*v
)
796 int_nonzero(PyIntObject
*v
)
798 return v
->ob_ival
!= 0;
802 int_invert(PyIntObject
*v
)
804 return PyInt_FromLong(~v
->ob_ival
);
808 int_lshift(PyIntObject
*v
, PyIntObject
*w
)
811 PyObject
*vv
, *ww
, *result
;
813 CONVERT_TO_LONG(v
, a
);
814 CONVERT_TO_LONG(w
, b
);
816 PyErr_SetString(PyExc_ValueError
, "negative shift count");
819 if (a
== 0 || b
== 0)
822 vv
= PyLong_FromLong(PyInt_AS_LONG(v
));
825 ww
= PyLong_FromLong(PyInt_AS_LONG(w
));
830 result
= PyNumber_Lshift(vv
, ww
);
836 if (a
!= Py_ARITHMETIC_RIGHT_SHIFT(long, c
, b
)) {
837 vv
= PyLong_FromLong(PyInt_AS_LONG(v
));
840 ww
= PyLong_FromLong(PyInt_AS_LONG(w
));
845 result
= PyNumber_Lshift(vv
, ww
);
850 return PyInt_FromLong(c
);
854 int_rshift(PyIntObject
*v
, PyIntObject
*w
)
857 CONVERT_TO_LONG(v
, a
);
858 CONVERT_TO_LONG(w
, b
);
860 PyErr_SetString(PyExc_ValueError
, "negative shift count");
863 if (a
== 0 || b
== 0)
872 a
= Py_ARITHMETIC_RIGHT_SHIFT(long, a
, b
);
874 return PyInt_FromLong(a
);
878 int_and(PyIntObject
*v
, PyIntObject
*w
)
881 CONVERT_TO_LONG(v
, a
);
882 CONVERT_TO_LONG(w
, b
);
883 return PyInt_FromLong(a
& b
);
887 int_xor(PyIntObject
*v
, PyIntObject
*w
)
890 CONVERT_TO_LONG(v
, a
);
891 CONVERT_TO_LONG(w
, b
);
892 return PyInt_FromLong(a
^ b
);
896 int_or(PyIntObject
*v
, PyIntObject
*w
)
899 CONVERT_TO_LONG(v
, a
);
900 CONVERT_TO_LONG(w
, b
);
901 return PyInt_FromLong(a
| b
);
905 int_coerce(PyObject
**pv
, PyObject
**pw
)
907 if (PyInt_Check(*pw
)) {
912 return 1; /* Can't do it */
916 int_int(PyIntObject
*v
)
918 if (PyInt_CheckExact(v
))
921 v
= (PyIntObject
*)PyInt_FromLong(v
->ob_ival
);
922 return (PyObject
*)v
;
926 int_long(PyIntObject
*v
)
928 return PyLong_FromLong((v
-> ob_ival
));
932 int_float(PyIntObject
*v
)
934 return PyFloat_FromDouble((double)(v
-> ob_ival
));
938 int_oct(PyIntObject
*v
)
940 return _PyInt_Format(v
, 8, 0);
944 int_hex(PyIntObject
*v
)
946 return _PyInt_Format(v
, 16, 0);
950 int_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
953 int_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
957 static char *kwlist
[] = {"x", "base", 0};
959 if (type
!= &PyInt_Type
)
960 return int_subtype_new(type
, args
, kwds
); /* Wimp out */
961 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:int", kwlist
,
965 return PyInt_FromLong(0L);
967 return PyNumber_Int(x
);
968 if (PyString_Check(x
)) {
969 /* Since PyInt_FromString doesn't have a length parameter,
970 * check here for possible NULs in the string. */
971 char *string
= PyString_AS_STRING(x
);
972 if (strlen(string
) != PyString_Size(x
)) {
973 /* create a repr() of the input string,
974 * just like PyInt_FromString does */
976 srepr
= PyObject_Repr(x
);
979 PyErr_Format(PyExc_ValueError
,
980 "invalid literal for int() with base %d: %s",
981 base
, PyString_AS_STRING(srepr
));
985 return PyInt_FromString(string
, NULL
, base
);
987 #ifdef Py_USING_UNICODE
988 if (PyUnicode_Check(x
))
989 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x
),
990 PyUnicode_GET_SIZE(x
),
993 PyErr_SetString(PyExc_TypeError
,
994 "int() can't convert non-string with explicit base");
998 /* Wimpy, slow approach to tp_new calls for subtypes of int:
999 first create a regular int from whatever arguments we got,
1000 then allocate a subtype instance and initialize its ob_ival
1001 from the regular int. The regular int is then thrown away.
1004 int_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1006 PyObject
*tmp
, *newobj
;
1009 assert(PyType_IsSubtype(type
, &PyInt_Type
));
1010 tmp
= int_new(&PyInt_Type
, args
, kwds
);
1013 if (!PyInt_Check(tmp
)) {
1014 ival
= PyLong_AsLong(tmp
);
1015 if (ival
== -1 && PyErr_Occurred()) {
1020 ival
= ((PyIntObject
*)tmp
)->ob_ival
;
1023 newobj
= type
->tp_alloc(type
, 0);
1024 if (newobj
== NULL
) {
1028 ((PyIntObject
*)newobj
)->ob_ival
= ival
;
1034 int_getnewargs(PyIntObject
*v
)
1036 return Py_BuildValue("(l)", v
->ob_ival
);
1040 int_getN(PyIntObject
*v
, void *context
) {
1041 return PyInt_FromLong((Py_intptr_t
)context
);
1044 /* Convert an integer to the given base. Returns a string.
1045 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
1046 If newstyle is zero, then use the pre-2.6 behavior of octal having
1048 PyAPI_FUNC(PyObject
*)
1049 _PyInt_Format(PyIntObject
*v
, int base
, int newstyle
)
1051 /* There are no doubt many, many ways to optimize this, using code
1052 similar to _PyLong_Format */
1053 long n
= v
->ob_ival
;
1054 int negative
= n
< 0;
1055 int is_zero
= n
== 0;
1057 /* For the reasoning behind this size, see
1058 http://c-faq.com/misc/hexio.html. Then, add a few bytes for
1059 the possible sign and prefix "0[box]" */
1060 char buf
[sizeof(n
)*CHAR_BIT
+6];
1062 /* Start by pointing to the end of the buffer. We fill in from
1063 the back forward. */
1064 char* p
= &buf
[sizeof(buf
)];
1066 assert(base
>= 2 && base
<= 36);
1069 /* I'd use i_divmod, except it doesn't produce the results
1070 I want when n is negative. So just duplicate the salient
1072 long div
= n
/ base
;
1073 long mod
= n
- div
* base
;
1075 /* convert abs(mod) to the right character in [0-9, a-z] */
1076 char cdigit
= (char)(mod
< 0 ? -mod
: mod
);
1077 cdigit
+= (cdigit
< 10) ? '0' : 'a'-10;
1087 else if (base
== 8) {
1096 else if (base
== 16) {
1100 else if (base
!= 10) {
1102 *--p
= '0' + base
%10;
1104 *--p
= '0' + base
/10;
1109 return PyString_FromStringAndSize(p
, &buf
[sizeof(buf
)] - p
);
1113 int__format__(PyObject
*self
, PyObject
*args
)
1115 PyObject
*format_spec
;
1117 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
1119 if (PyBytes_Check(format_spec
))
1120 return _PyInt_FormatAdvanced(self
,
1121 PyBytes_AS_STRING(format_spec
),
1122 PyBytes_GET_SIZE(format_spec
));
1123 if (PyUnicode_Check(format_spec
)) {
1124 /* Convert format_spec to a str */
1126 PyObject
*str_spec
= PyObject_Str(format_spec
);
1128 if (str_spec
== NULL
)
1131 result
= _PyInt_FormatAdvanced(self
,
1132 PyBytes_AS_STRING(str_spec
),
1133 PyBytes_GET_SIZE(str_spec
));
1135 Py_DECREF(str_spec
);
1138 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
1142 static const unsigned char BitLengthTable
[32] = {
1143 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1144 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1148 int_bit_length(PyIntObject
*v
)
1154 /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
1155 n
= 0U-(unsigned long)v
->ob_ival
;
1157 n
= (unsigned long)v
->ob_ival
;
1163 r
+= (long)(BitLengthTable
[n
]);
1164 return PyInt_FromLong(r
);
1167 PyDoc_STRVAR(int_bit_length_doc
,
1168 "int.bit_length() -> int\n\
1170 Number of bits necessary to represent self in binary.\n\
1173 >>> (37).bit_length()\n\
1178 int_is_finite(PyObject
*v
)
1184 static PyMethodDef int_methods
[] = {
1185 {"conjugate", (PyCFunction
)int_int
, METH_NOARGS
,
1186 "Returns self, the complex conjugate of any int."},
1187 {"bit_length", (PyCFunction
)int_bit_length
, METH_NOARGS
,
1188 int_bit_length_doc
},
1190 {"is_finite", (PyCFunction
)int_is_finite
, METH_NOARGS
,
1191 "Returns always True."},
1193 {"__trunc__", (PyCFunction
)int_int
, METH_NOARGS
,
1194 "Truncating an Integral returns itself."},
1195 {"__getnewargs__", (PyCFunction
)int_getnewargs
, METH_NOARGS
},
1196 {"__format__", (PyCFunction
)int__format__
, METH_VARARGS
},
1197 {NULL
, NULL
} /* sentinel */
1200 static PyGetSetDef int_getset
[] = {
1202 (getter
)int_int
, (setter
)NULL
,
1203 "the real part of a complex number",
1206 (getter
)int_getN
, (setter
)NULL
,
1207 "the imaginary part of a complex number",
1210 (getter
)int_int
, (setter
)NULL
,
1211 "the numerator of a rational number in lowest terms",
1214 (getter
)int_getN
, (setter
)NULL
,
1215 "the denominator of a rational number in lowest terms",
1217 {NULL
} /* Sentinel */
1220 PyDoc_STRVAR(int_doc
,
1221 "int(x[, base]) -> integer\n\
1223 Convert a string or number to an integer, if possible. A floating point\n\
1224 argument will be truncated towards zero (this does not include a string\n\
1225 representation of a floating point number!) When converting a string, use\n\
1226 the optional base. It is an error to supply a base when converting a\n\
1227 non-string. If base is zero, the proper base is guessed based on the\n\
1228 string content. If the argument is outside the integer range a\n\
1229 long object will be returned instead.");
1231 static PyNumberMethods int_as_number
= {
1232 (binaryfunc
)int_add
, /*nb_add*/
1233 (binaryfunc
)int_sub
, /*nb_subtract*/
1234 (binaryfunc
)int_mul
, /*nb_multiply*/
1235 (binaryfunc
)int_classic_div
, /*nb_divide*/
1236 (binaryfunc
)int_mod
, /*nb_remainder*/
1237 (binaryfunc
)int_divmod
, /*nb_divmod*/
1238 (ternaryfunc
)int_pow
, /*nb_power*/
1239 (unaryfunc
)int_neg
, /*nb_negative*/
1240 (unaryfunc
)int_int
, /*nb_positive*/
1241 (unaryfunc
)int_abs
, /*nb_absolute*/
1242 (inquiry
)int_nonzero
, /*nb_nonzero*/
1243 (unaryfunc
)int_invert
, /*nb_invert*/
1244 (binaryfunc
)int_lshift
, /*nb_lshift*/
1245 (binaryfunc
)int_rshift
, /*nb_rshift*/
1246 (binaryfunc
)int_and
, /*nb_and*/
1247 (binaryfunc
)int_xor
, /*nb_xor*/
1248 (binaryfunc
)int_or
, /*nb_or*/
1249 int_coerce
, /*nb_coerce*/
1250 (unaryfunc
)int_int
, /*nb_int*/
1251 (unaryfunc
)int_long
, /*nb_long*/
1252 (unaryfunc
)int_float
, /*nb_float*/
1253 (unaryfunc
)int_oct
, /*nb_oct*/
1254 (unaryfunc
)int_hex
, /*nb_hex*/
1255 0, /*nb_inplace_add*/
1256 0, /*nb_inplace_subtract*/
1257 0, /*nb_inplace_multiply*/
1258 0, /*nb_inplace_divide*/
1259 0, /*nb_inplace_remainder*/
1260 0, /*nb_inplace_power*/
1261 0, /*nb_inplace_lshift*/
1262 0, /*nb_inplace_rshift*/
1263 0, /*nb_inplace_and*/
1264 0, /*nb_inplace_xor*/
1265 0, /*nb_inplace_or*/
1266 (binaryfunc
)int_div
, /* nb_floor_divide */
1267 int_true_divide
, /* nb_true_divide */
1268 0, /* nb_inplace_floor_divide */
1269 0, /* nb_inplace_true_divide */
1270 (unaryfunc
)int_int
, /* nb_index */
1273 PyTypeObject PyInt_Type
= {
1274 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
1276 sizeof(PyIntObject
),
1278 (destructor
)int_dealloc
, /* tp_dealloc */
1279 (printfunc
)int_print
, /* tp_print */
1282 (cmpfunc
)int_compare
, /* tp_compare */
1283 (reprfunc
)int_repr
, /* tp_repr */
1284 &int_as_number
, /* tp_as_number */
1285 0, /* tp_as_sequence */
1286 0, /* tp_as_mapping */
1287 (hashfunc
)int_hash
, /* tp_hash */
1289 (reprfunc
)int_repr
, /* tp_str */
1290 PyObject_GenericGetAttr
, /* tp_getattro */
1291 0, /* tp_setattro */
1292 0, /* tp_as_buffer */
1293 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
1294 Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_INT_SUBCLASS
, /* tp_flags */
1295 int_doc
, /* tp_doc */
1296 0, /* tp_traverse */
1298 0, /* tp_richcompare */
1299 0, /* tp_weaklistoffset */
1301 0, /* tp_iternext */
1302 int_methods
, /* tp_methods */
1304 int_getset
, /* tp_getset */
1307 0, /* tp_descr_get */
1308 0, /* tp_descr_set */
1309 0, /* tp_dictoffset */
1312 int_new
, /* tp_new */
1313 (freefunc
)int_free
, /* tp_free */
1321 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
1322 for (ival
= -NSMALLNEGINTS
; ival
< NSMALLPOSINTS
; ival
++) {
1323 if (!free_list
&& (free_list
= fill_free_list()) == NULL
)
1325 /* PyObject_New is inlined */
1327 free_list
= (PyIntObject
*)Py_TYPE(v
);
1328 PyObject_INIT(v
, &PyInt_Type
);
1330 small_ints
[ival
+ NSMALLNEGINTS
] = v
;
1337 PyInt_ClearFreeList(void)
1340 PyIntBlock
*list
, *next
;
1342 int u
; /* remaining unfreed ints per block */
1343 int freelist_size
= 0;
1348 while (list
!= NULL
) {
1350 for (i
= 0, p
= &list
->objects
[0];
1353 if (PyInt_CheckExact(p
) && p
->ob_refcnt
!= 0)
1358 list
->next
= block_list
;
1360 for (i
= 0, p
= &list
->objects
[0];
1363 if (!PyInt_CheckExact(p
) ||
1364 p
->ob_refcnt
== 0) {
1365 Py_TYPE(p
) = (struct _typeobject
*)
1369 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
1370 else if (-NSMALLNEGINTS
<= p
->ob_ival
&&
1371 p
->ob_ival
< NSMALLPOSINTS
&&
1372 small_ints
[p
->ob_ival
+
1373 NSMALLNEGINTS
] == NULL
) {
1375 small_ints
[p
->ob_ival
+
1388 return freelist_size
;
1397 int u
; /* total unfreed ints per block */
1399 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
1402 i
= NSMALLNEGINTS
+ NSMALLPOSINTS
;
1409 u
= PyInt_ClearFreeList();
1410 if (!Py_VerboseFlag
)
1412 fprintf(stderr
, "# cleanup ints");
1414 fprintf(stderr
, "\n");
1418 ": %d unfreed int%s\n",
1419 u
, u
== 1 ? "" : "s");
1421 if (Py_VerboseFlag
> 1) {
1423 while (list
!= NULL
) {
1424 for (i
= 0, p
= &list
->objects
[0];
1427 if (PyInt_CheckExact(p
) && p
->ob_refcnt
!= 0)
1428 /* XXX(twouters) cast refcount to
1429 long until %zd is universally
1433 "# <int at %p, refcnt=%ld, val=%ld>\n",
1434 p
, (long)p
->ob_refcnt
,