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
int quick_int_allocs, quick_neg_int_allocs;
85
PyInt_FromLong(long ival)
87
register PyIntObject *v;
88
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
89
if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
90
v = small_ints[ival + NSMALLNEGINTS];
96
quick_neg_int_allocs++;
98
return (PyObject *) v;
101
if (free_list == NULL) {
102
if ((free_list = fill_free_list()) == NULL)
105
/* Inline PyObject_New */
107
free_list = (PyIntObject *)Py_TYPE(v);
108
PyObject_INIT(v, &PyInt_Type);
110
return (PyObject *) v;
114
PyInt_FromSize_t(size_t ival)
116
if (ival <= LONG_MAX)
117
return PyInt_FromLong((long)ival);
118
return _PyLong_FromSize_t(ival);
122
PyInt_FromSsize_t(Py_ssize_t ival)
124
if (ival >= LONG_MIN && ival <= LONG_MAX)
125
return PyInt_FromLong((long)ival);
126
return _PyLong_FromSsize_t(ival);
130
int_dealloc(PyIntObject *v)
132
if (PyInt_CheckExact(v)) {
133
Py_TYPE(v) = (struct _typeobject *)free_list;
137
Py_TYPE(v)->tp_free((PyObject *)v);
141
int_free(PyIntObject *v)
143
Py_TYPE(v) = (struct _typeobject *)free_list;
148
PyInt_AsLong(register PyObject *op)
154
if (op && PyInt_Check(op))
155
return PyInt_AS_LONG((PyIntObject*) op);
157
if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
158
nb->nb_int == NULL) {
159
PyErr_SetString(PyExc_TypeError, "an integer is required");
163
io = (PyIntObject*) (*nb->nb_int) (op);
166
if (!PyInt_Check(io)) {
167
if (PyLong_Check(io)) {
168
/* got a long? => retry int conversion */
169
val = PyLong_AsLong((PyObject *)io);
171
if ((val == -1) && PyErr_Occurred())
178
PyErr_SetString(PyExc_TypeError,
179
"nb_int should return int object");
184
val = PyInt_AS_LONG(io);
191
PyInt_AsSsize_t(register PyObject *op)
193
#if SIZEOF_SIZE_T != SIZEOF_LONG
200
PyErr_SetString(PyExc_TypeError, "an integer is required");
205
return PyInt_AS_LONG((PyIntObject*) op);
206
if (PyLong_Check(op))
207
return _PyLong_AsSsize_t(op);
208
#if SIZEOF_SIZE_T == SIZEOF_LONG
209
return PyInt_AsLong(op);
212
if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
213
(nb->nb_int == NULL && nb->nb_long == 0)) {
214
PyErr_SetString(PyExc_TypeError, "an integer is required");
218
if (nb->nb_long != 0)
219
io = (PyIntObject*) (*nb->nb_long) (op);
221
io = (PyIntObject*) (*nb->nb_int) (op);
224
if (!PyInt_Check(io)) {
225
if (PyLong_Check(io)) {
226
/* got a long? => retry int conversion */
227
val = _PyLong_AsSsize_t((PyObject *)io);
229
if ((val == -1) && PyErr_Occurred())
236
PyErr_SetString(PyExc_TypeError,
237
"nb_int should return int object");
242
val = PyInt_AS_LONG(io);
250
PyInt_AsUnsignedLongMask(register PyObject *op)
256
if (op && PyInt_Check(op))
257
return PyInt_AS_LONG((PyIntObject*) op);
258
if (op && PyLong_Check(op))
259
return PyLong_AsUnsignedLongMask(op);
261
if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
262
nb->nb_int == NULL) {
263
PyErr_SetString(PyExc_TypeError, "an integer is required");
264
return (unsigned long)-1;
267
io = (PyIntObject*) (*nb->nb_int) (op);
269
return (unsigned long)-1;
270
if (!PyInt_Check(io)) {
271
if (PyLong_Check(io)) {
272
val = PyLong_AsUnsignedLongMask((PyObject *)io);
274
if (PyErr_Occurred())
275
return (unsigned long)-1;
281
PyErr_SetString(PyExc_TypeError,
282
"nb_int should return int object");
283
return (unsigned long)-1;
287
val = PyInt_AS_LONG(io);
293
#ifdef HAVE_LONG_LONG
294
unsigned PY_LONG_LONG
295
PyInt_AsUnsignedLongLongMask(register PyObject *op)
299
unsigned PY_LONG_LONG val;
301
if (op && PyInt_Check(op))
302
return PyInt_AS_LONG((PyIntObject*) op);
303
if (op && PyLong_Check(op))
304
return PyLong_AsUnsignedLongLongMask(op);
306
if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
307
nb->nb_int == NULL) {
308
PyErr_SetString(PyExc_TypeError, "an integer is required");
309
return (unsigned PY_LONG_LONG)-1;
312
io = (PyIntObject*) (*nb->nb_int) (op);
314
return (unsigned PY_LONG_LONG)-1;
315
if (!PyInt_Check(io)) {
316
if (PyLong_Check(io)) {
317
val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
319
if (PyErr_Occurred())
320
return (unsigned PY_LONG_LONG)-1;
326
PyErr_SetString(PyExc_TypeError,
327
"nb_int should return int object");
328
return (unsigned PY_LONG_LONG)-1;
332
val = PyInt_AS_LONG(io);
340
PyInt_FromString(char *s, char **pend, int base)
345
PyObject *sobj, *srepr;
347
if ((base != 0 && base < 2) || base > 36) {
348
PyErr_SetString(PyExc_ValueError,
349
"int() base must be >= 2 and <= 36");
353
while (*s && isspace(Py_CHARMASK(*s)))
356
if (base == 0 && s[0] == '0') {
357
x = (long) PyOS_strtoul(s, &end, base);
359
return PyLong_FromString(s, pend, base);
362
x = PyOS_strtol(s, &end, base);
363
if (end == s || !isalnum(Py_CHARMASK(end[-1])))
365
while (*end && isspace(Py_CHARMASK(*end)))
369
slen = strlen(s) < 200 ? strlen(s) : 200;
370
sobj = PyString_FromStringAndSize(s, slen);
373
srepr = PyObject_Repr(sobj);
377
PyErr_Format(PyExc_ValueError,
378
"invalid literal for int() with base %d: %s",
379
base, PyString_AS_STRING(srepr));
384
return PyLong_FromString(s, pend, base);
387
return PyInt_FromLong(x);
390
#ifdef Py_USING_UNICODE
392
PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
395
char *buffer = (char *)PyMem_MALLOC(length+1);
398
return PyErr_NoMemory();
400
if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
404
result = PyInt_FromString(buffer, NULL, base);
412
/* Integers are seen as the "smallest" of all numeric types and thus
413
don't have any knowledge about conversion of other types to
416
#define CONVERT_TO_LONG(obj, lng) \
417
if (PyInt_Check(obj)) { \
418
lng = PyInt_AS_LONG(obj); \
421
Py_INCREF(Py_NotImplemented); \
422
return Py_NotImplemented; \
427
int_print(PyIntObject *v, FILE *fp, int flags)
428
/* flags -- not used but required by interface */
430
long int_val = v->ob_ival;
431
Py_BEGIN_ALLOW_THREADS
432
fprintf(fp, "%ld", int_val);
438
int_repr(PyIntObject *v)
440
return _PyInt_Format(v, 10, 0);
444
int_compare(PyIntObject *v, PyIntObject *w)
446
register long i = v->ob_ival;
447
register long j = w->ob_ival;
448
return (i < j) ? -1 : (i > j) ? 1 : 0;
452
int_hash(PyIntObject *v)
454
/* XXX If this is changed, you also need to change the way
455
Python's long, float and complex types are hashed. */
456
long x = v -> ob_ival;
463
int_add(PyIntObject *v, PyIntObject *w)
465
register long a, b, x;
466
CONVERT_TO_LONG(v, a);
467
CONVERT_TO_LONG(w, b);
469
if ((x^a) >= 0 || (x^b) >= 0)
470
return PyInt_FromLong(x);
471
return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
475
int_sub(PyIntObject *v, PyIntObject *w)
477
register long a, b, x;
478
CONVERT_TO_LONG(v, a);
479
CONVERT_TO_LONG(w, b);
481
if ((x^a) >= 0 || (x^~b) >= 0)
482
return PyInt_FromLong(x);
483
return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
488
Integer overflow checking for * is painful: Python tried a couple ways, but
489
they didn't work on all platforms, or failed in endcases (a product of
490
-sys.maxint-1 has been a particular pain).
494
The native long product x*y is either exactly right or *way* off, being
495
just the last n bits of the true product, where n is the number of bits
496
in a long (the delivered product is the true product plus i*2**n for
499
The native double product (double)x * (double)y is subject to three
500
rounding errors: on a sizeof(long)==8 box, each cast to double can lose
501
info, and even on a sizeof(long)==4 box, the multiplication can lose info.
502
But, unlike the native long product, it's not in *range* trouble: even
503
if sizeof(long)==32 (256-bit longs), the product easily fits in the
504
dynamic range of a double. So the leading 50 (or so) bits of the double
507
We check these two ways against each other, and declare victory if they're
508
approximately the same. Else, because the native long product is the only
509
one that can lose catastrophic amounts of information, it's the native long
510
product that must have overflowed.
514
int_mul(PyObject *v, PyObject *w)
517
long longprod; /* a*b in native long arithmetic */
518
double doubled_longprod; /* (double)longprod */
519
double doubleprod; /* (double)a * (double)b */
521
CONVERT_TO_LONG(v, a);
522
CONVERT_TO_LONG(w, b);
524
doubleprod = (double)a * (double)b;
525
doubled_longprod = (double)longprod;
527
/* Fast path for normal case: small multiplicands, and no info
528
is lost in either method. */
529
if (doubled_longprod == doubleprod)
530
return PyInt_FromLong(longprod);
532
/* Somebody somewhere lost info. Close enough, or way off? Note
533
that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
534
The difference either is or isn't significant compared to the
535
true value (of which doubleprod is a good approximation).
538
const double diff = doubled_longprod - doubleprod;
539
const double absdiff = diff >= 0.0 ? diff : -diff;
540
const double absprod = doubleprod >= 0.0 ? doubleprod :
542
/* absdiff/absprod <= 1/32 iff
543
32 * absdiff <= absprod -- 5 good bits is "close enough" */
544
if (32.0 * absdiff <= absprod)
545
return PyInt_FromLong(longprod);
547
return PyLong_Type.tp_as_number->nb_multiply(v, w);
551
/* Integer overflow checking for unary negation: on a 2's-complement
552
* box, -x overflows iff x is the most negative long. In this case we
553
* get -x == x. However, -x is undefined (by C) if x /is/ the most
554
* negative long (it's a signed overflow case), and some compilers care.
555
* So we cast x to unsigned long first. However, then other compilers
556
* warn about applying unary minus to an unsigned operand. Hence the
559
#define UNARY_NEG_WOULD_OVERFLOW(x) \
560
((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
562
/* Return type of i_divmod */
564
DIVMOD_OK, /* Correct result */
565
DIVMOD_OVERFLOW, /* Overflow, try again using longs */
566
DIVMOD_ERROR /* Exception raised */
569
static enum divmod_result
570
i_divmod(register long x, register long y,
571
long *p_xdivy, long *p_xmody)
576
PyErr_SetString(PyExc_ZeroDivisionError,
577
"integer division or modulo by zero");
580
/* (-sys.maxint-1)/-1 is the only overflow case. */
581
if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
582
return DIVMOD_OVERFLOW;
584
xmody = x - xdivy * y;
585
/* If the signs of x and y differ, and the remainder is non-0,
586
* C89 doesn't define whether xdivy is now the floor or the
587
* ceiling of the infinitely precise quotient. We want the floor,
588
* and we have it iff the remainder's sign matches y's.
590
if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
593
assert(xmody && ((y ^ xmody) >= 0));
601
int_div(PyIntObject *x, PyIntObject *y)
605
CONVERT_TO_LONG(x, xi);
606
CONVERT_TO_LONG(y, yi);
607
switch (i_divmod(xi, yi, &d, &m)) {
609
return PyInt_FromLong(d);
610
case DIVMOD_OVERFLOW:
611
return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
619
int_classic_div(PyIntObject *x, PyIntObject *y)
623
CONVERT_TO_LONG(x, xi);
624
CONVERT_TO_LONG(y, yi);
625
if (Py_DivisionWarningFlag &&
626
PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
628
switch (i_divmod(xi, yi, &d, &m)) {
630
return PyInt_FromLong(d);
631
case DIVMOD_OVERFLOW:
632
return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
640
int_true_divide(PyObject *v, PyObject *w)
642
/* If they aren't both ints, give someone else a chance. In
643
particular, this lets int/long get handled by longs, which
644
underflows to 0 gracefully if the long is too big to convert
646
if (PyInt_Check(v) && PyInt_Check(w))
647
return PyFloat_Type.tp_as_number->nb_true_divide(v, w);
648
Py_INCREF(Py_NotImplemented);
649
return Py_NotImplemented;
653
int_mod(PyIntObject *x, PyIntObject *y)
657
CONVERT_TO_LONG(x, xi);
658
CONVERT_TO_LONG(y, yi);
659
switch (i_divmod(xi, yi, &d, &m)) {
661
return PyInt_FromLong(m);
662
case DIVMOD_OVERFLOW:
663
return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
671
int_divmod(PyIntObject *x, PyIntObject *y)
675
CONVERT_TO_LONG(x, xi);
676
CONVERT_TO_LONG(y, yi);
677
switch (i_divmod(xi, yi, &d, &m)) {
679
return Py_BuildValue("(ll)", d, m);
680
case DIVMOD_OVERFLOW:
681
return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
689
int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
691
register long iv, iw, iz=0, ix, temp, prev;
692
CONVERT_TO_LONG(v, iv);
693
CONVERT_TO_LONG(w, iw);
695
if ((PyObject *)z != Py_None) {
696
PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
697
"cannot be negative when 3rd argument specified");
700
/* Return a float. This works because we know that
701
this calls float_pow() which converts its
702
arguments to double. */
703
return PyFloat_Type.tp_as_number->nb_power(
704
(PyObject *)v, (PyObject *)w, (PyObject *)z);
706
if ((PyObject *)z != Py_None) {
707
CONVERT_TO_LONG(z, iz);
709
PyErr_SetString(PyExc_ValueError,
710
"pow() 3rd argument cannot be 0");
715
* XXX: The original exponentiation code stopped looping
716
* when temp hit zero; this code will continue onwards
717
* unnecessarily, but at least it won't cause any errors.
718
* Hopefully the speed improvement from the fast exponentiation
719
* will compensate for the slight inefficiency.
720
* XXX: Better handling of overflows is desperately needed.
725
prev = ix; /* Save value for overflow check */
729
break; /* Avoid ix / 0 */
730
if (ix / temp != prev) {
731
return PyLong_Type.tp_as_number->nb_power(
737
iw >>= 1; /* Shift exponent down by 1 bit */
740
temp *= temp; /* Square the value of temp */
741
if (prev != 0 && temp / prev != prev) {
742
return PyLong_Type.tp_as_number->nb_power(
743
(PyObject *)v, (PyObject *)w, (PyObject *)z);
746
/* If we did a multiplication, perform a modulo */
753
switch (i_divmod(ix, iz, &div, &mod)) {
757
case DIVMOD_OVERFLOW:
758
return PyLong_Type.tp_as_number->nb_power(
759
(PyObject *)v, (PyObject *)w, (PyObject *)z);
764
return PyInt_FromLong(ix);
768
int_neg(PyIntObject *v)
772
/* check for overflow */
773
if (UNARY_NEG_WOULD_OVERFLOW(a)) {
774
PyObject *o = PyLong_FromLong(a);
776
PyObject *result = PyNumber_Negative(o);
782
return PyInt_FromLong(-a);
786
int_abs(PyIntObject *v)
795
int_nonzero(PyIntObject *v)
797
return v->ob_ival != 0;
801
int_invert(PyIntObject *v)
803
return PyInt_FromLong(~v->ob_ival);
807
int_lshift(PyIntObject *v, PyIntObject *w)
810
PyObject *vv, *ww, *result;
812
CONVERT_TO_LONG(v, a);
813
CONVERT_TO_LONG(w, b);
815
PyErr_SetString(PyExc_ValueError, "negative shift count");
818
if (a == 0 || b == 0)
821
vv = PyLong_FromLong(PyInt_AS_LONG(v));
824
ww = PyLong_FromLong(PyInt_AS_LONG(w));
829
result = PyNumber_Lshift(vv, ww);
835
if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
836
vv = PyLong_FromLong(PyInt_AS_LONG(v));
839
ww = PyLong_FromLong(PyInt_AS_LONG(w));
844
result = PyNumber_Lshift(vv, ww);
849
return PyInt_FromLong(c);
853
int_rshift(PyIntObject *v, PyIntObject *w)
856
CONVERT_TO_LONG(v, a);
857
CONVERT_TO_LONG(w, b);
859
PyErr_SetString(PyExc_ValueError, "negative shift count");
862
if (a == 0 || b == 0)
871
a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
873
return PyInt_FromLong(a);
877
int_and(PyIntObject *v, PyIntObject *w)
880
CONVERT_TO_LONG(v, a);
881
CONVERT_TO_LONG(w, b);
882
return PyInt_FromLong(a & b);
886
int_xor(PyIntObject *v, PyIntObject *w)
889
CONVERT_TO_LONG(v, a);
890
CONVERT_TO_LONG(w, b);
891
return PyInt_FromLong(a ^ b);
895
int_or(PyIntObject *v, PyIntObject *w)
898
CONVERT_TO_LONG(v, a);
899
CONVERT_TO_LONG(w, b);
900
return PyInt_FromLong(a | b);
904
int_coerce(PyObject **pv, PyObject **pw)
906
if (PyInt_Check(*pw)) {
911
return 1; /* Can't do it */
915
int_int(PyIntObject *v)
917
if (PyInt_CheckExact(v))
920
v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
921
return (PyObject *)v;
925
int_long(PyIntObject *v)
927
return PyLong_FromLong((v -> ob_ival));
931
int_float(PyIntObject *v)
933
return PyFloat_FromDouble((double)(v -> ob_ival));
937
int_oct(PyIntObject *v)
939
return _PyInt_Format(v, 8, 0);
943
int_hex(PyIntObject *v)
945
return _PyInt_Format(v, 16, 0);
949
int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
952
int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
956
static char *kwlist[] = {"x", "base", 0};
958
if (type != &PyInt_Type)
959
return int_subtype_new(type, args, kwds); /* Wimp out */
960
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
964
return PyInt_FromLong(0L);
966
return PyNumber_Int(x);
967
if (PyString_Check(x)) {
968
/* Since PyInt_FromString doesn't have a length parameter,
969
* check here for possible NULs in the string. */
970
char *string = PyString_AS_STRING(x);
971
if (strlen(string) != PyString_Size(x)) {
972
/* create a repr() of the input string,
973
* just like PyInt_FromString does */
975
srepr = PyObject_Repr(x);
978
PyErr_Format(PyExc_ValueError,
979
"invalid literal for int() with base %d: %s",
980
base, PyString_AS_STRING(srepr));
984
return PyInt_FromString(string, NULL, base);
986
#ifdef Py_USING_UNICODE
987
if (PyUnicode_Check(x))
988
return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
989
PyUnicode_GET_SIZE(x),
992
PyErr_SetString(PyExc_TypeError,
993
"int() can't convert non-string with explicit base");
997
/* Wimpy, slow approach to tp_new calls for subtypes of int:
998
first create a regular int from whatever arguments we got,
999
then allocate a subtype instance and initialize its ob_ival
1000
from the regular int. The regular int is then thrown away.
1003
int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1005
PyObject *tmp, *newobj;
1008
assert(PyType_IsSubtype(type, &PyInt_Type));
1009
tmp = int_new(&PyInt_Type, args, kwds);
1012
if (!PyInt_Check(tmp)) {
1013
ival = PyLong_AsLong(tmp);
1014
if (ival == -1 && PyErr_Occurred()) {
1019
ival = ((PyIntObject *)tmp)->ob_ival;
1022
newobj = type->tp_alloc(type, 0);
1023
if (newobj == NULL) {
1027
((PyIntObject *)newobj)->ob_ival = ival;
1033
int_getnewargs(PyIntObject *v)
1035
return Py_BuildValue("(l)", v->ob_ival);
1039
int_getN(PyIntObject *v, void *context) {
1040
return PyInt_FromLong((Py_intptr_t)context);
1043
/* Convert an integer to the given base. Returns a string.
1044
If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
1045
If newstyle is zero, then use the pre-2.6 behavior of octal having
1047
PyAPI_FUNC(PyObject*)
1048
_PyInt_Format(PyIntObject *v, int base, int newstyle)
1050
/* There are no doubt many, many ways to optimize this, using code
1051
similar to _PyLong_Format */
1052
long n = v->ob_ival;
1053
int negative = n < 0;
1054
int is_zero = n == 0;
1056
/* For the reasoning behind this size, see
1057
http://c-faq.com/misc/hexio.html. Then, add a few bytes for
1058
the possible sign and prefix "0[box]" */
1059
char buf[sizeof(n)*CHAR_BIT+6];
1061
/* Start by pointing to the end of the buffer. We fill in from
1062
the back forward. */
1063
char* p = &buf[sizeof(buf)];
1065
assert(base >= 2 && base <= 36);
1068
/* I'd use i_divmod, except it doesn't produce the results
1069
I want when n is negative. So just duplicate the salient
1071
long div = n / base;
1072
long mod = n - div * base;
1074
/* convert abs(mod) to the right character in [0-9, a-z] */
1075
char cdigit = (char)(mod < 0 ? -mod : mod);
1076
cdigit += (cdigit < 10) ? '0' : 'a'-10;
1086
else if (base == 8) {
1095
else if (base == 16) {
1099
else if (base != 10) {
1101
*--p = '0' + base%10;
1103
*--p = '0' + base/10;
1108
return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
1112
int__format__(PyObject *self, PyObject *args)
1114
PyObject *format_spec;
1116
if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1118
if (PyBytes_Check(format_spec))
1119
return _PyInt_FormatAdvanced(self,
1120
PyBytes_AS_STRING(format_spec),
1121
PyBytes_GET_SIZE(format_spec));
1122
if (PyUnicode_Check(format_spec)) {
1123
/* Convert format_spec to a str */
1125
PyObject *str_spec = PyObject_Str(format_spec);
1127
if (str_spec == NULL)
1130
result = _PyInt_FormatAdvanced(self,
1131
PyBytes_AS_STRING(str_spec),
1132
PyBytes_GET_SIZE(str_spec));
1134
Py_DECREF(str_spec);
1137
PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1143
int_is_finite(PyObject *v)
1149
static PyMethodDef int_methods[] = {
1150
{"conjugate", (PyCFunction)int_int, METH_NOARGS,
1151
"Returns self, the complex conjugate of any int."},
1153
{"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
1154
"Returns always True."},
1156
{"__trunc__", (PyCFunction)int_int, METH_NOARGS,
1157
"Truncating an Integral returns itself."},
1158
{"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
1159
{"__format__", (PyCFunction)int__format__, METH_VARARGS},
1160
{NULL, NULL} /* sentinel */
1163
static PyGetSetDef int_getset[] = {
1165
(getter)int_int, (setter)NULL,
1166
"the real part of a complex number",
1169
(getter)int_getN, (setter)NULL,
1170
"the imaginary part of a complex number",
1173
(getter)int_int, (setter)NULL,
1174
"the numerator of a rational number in lowest terms",
1177
(getter)int_getN, (setter)NULL,
1178
"the denominator of a rational number in lowest terms",
1180
{NULL} /* Sentinel */
1183
PyDoc_STRVAR(int_doc,
1184
"int(x[, base]) -> integer\n\
1186
Convert a string or number to an integer, if possible. A floating point\n\
1187
argument will be truncated towards zero (this does not include a string\n\
1188
representation of a floating point number!) When converting a string, use\n\
1189
the optional base. It is an error to supply a base when converting a\n\
1190
non-string. If base is zero, the proper base is guessed based on the\n\
1191
string content. If the argument is outside the integer range a\n\
1192
long object will be returned instead.");
1194
static PyNumberMethods int_as_number = {
1195
(binaryfunc)int_add, /*nb_add*/
1196
(binaryfunc)int_sub, /*nb_subtract*/
1197
(binaryfunc)int_mul, /*nb_multiply*/
1198
(binaryfunc)int_classic_div, /*nb_divide*/
1199
(binaryfunc)int_mod, /*nb_remainder*/
1200
(binaryfunc)int_divmod, /*nb_divmod*/
1201
(ternaryfunc)int_pow, /*nb_power*/
1202
(unaryfunc)int_neg, /*nb_negative*/
1203
(unaryfunc)int_int, /*nb_positive*/
1204
(unaryfunc)int_abs, /*nb_absolute*/
1205
(inquiry)int_nonzero, /*nb_nonzero*/
1206
(unaryfunc)int_invert, /*nb_invert*/
1207
(binaryfunc)int_lshift, /*nb_lshift*/
1208
(binaryfunc)int_rshift, /*nb_rshift*/
1209
(binaryfunc)int_and, /*nb_and*/
1210
(binaryfunc)int_xor, /*nb_xor*/
1211
(binaryfunc)int_or, /*nb_or*/
1212
int_coerce, /*nb_coerce*/
1213
(unaryfunc)int_int, /*nb_int*/
1214
(unaryfunc)int_long, /*nb_long*/
1215
(unaryfunc)int_float, /*nb_float*/
1216
(unaryfunc)int_oct, /*nb_oct*/
1217
(unaryfunc)int_hex, /*nb_hex*/
1218
0, /*nb_inplace_add*/
1219
0, /*nb_inplace_subtract*/
1220
0, /*nb_inplace_multiply*/
1221
0, /*nb_inplace_divide*/
1222
0, /*nb_inplace_remainder*/
1223
0, /*nb_inplace_power*/
1224
0, /*nb_inplace_lshift*/
1225
0, /*nb_inplace_rshift*/
1226
0, /*nb_inplace_and*/
1227
0, /*nb_inplace_xor*/
1228
0, /*nb_inplace_or*/
1229
(binaryfunc)int_div, /* nb_floor_divide */
1230
int_true_divide, /* nb_true_divide */
1231
0, /* nb_inplace_floor_divide */
1232
0, /* nb_inplace_true_divide */
1233
(unaryfunc)int_int, /* nb_index */
1236
PyTypeObject PyInt_Type = {
1237
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1239
sizeof(PyIntObject),
1241
(destructor)int_dealloc, /* tp_dealloc */
1242
(printfunc)int_print, /* tp_print */
1245
(cmpfunc)int_compare, /* tp_compare */
1246
(reprfunc)int_repr, /* tp_repr */
1247
&int_as_number, /* tp_as_number */
1248
0, /* tp_as_sequence */
1249
0, /* tp_as_mapping */
1250
(hashfunc)int_hash, /* tp_hash */
1252
(reprfunc)int_repr, /* tp_str */
1253
PyObject_GenericGetAttr, /* tp_getattro */
1254
0, /* tp_setattro */
1255
0, /* tp_as_buffer */
1256
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1257
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
1258
int_doc, /* tp_doc */
1259
0, /* tp_traverse */
1261
0, /* tp_richcompare */
1262
0, /* tp_weaklistoffset */
1264
0, /* tp_iternext */
1265
int_methods, /* tp_methods */
1267
int_getset, /* tp_getset */
1270
0, /* tp_descr_get */
1271
0, /* tp_descr_set */
1272
0, /* tp_dictoffset */
1275
int_new, /* tp_new */
1276
(freefunc)int_free, /* tp_free */
1284
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
1285
for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
1286
if (!free_list && (free_list = fill_free_list()) == NULL)
1288
/* PyObject_New is inlined */
1290
free_list = (PyIntObject *)Py_TYPE(v);
1291
PyObject_INIT(v, &PyInt_Type);
1293
small_ints[ival + NSMALLNEGINTS] = v;
1300
PyInt_ClearFreeList(void)
1303
PyIntBlock *list, *next;
1305
int u; /* remaining unfreed ints per block */
1306
int freelist_size = 0;
1311
while (list != NULL) {
1313
for (i = 0, p = &list->objects[0];
1316
if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1321
list->next = block_list;
1323
for (i = 0, p = &list->objects[0];
1326
if (!PyInt_CheckExact(p) ||
1327
p->ob_refcnt == 0) {
1328
Py_TYPE(p) = (struct _typeobject *)
1332
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
1333
else if (-NSMALLNEGINTS <= p->ob_ival &&
1334
p->ob_ival < NSMALLPOSINTS &&
1335
small_ints[p->ob_ival +
1336
NSMALLNEGINTS] == NULL) {
1338
small_ints[p->ob_ival +
1351
return freelist_size;
1360
int u; /* total unfreed ints per block */
1362
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
1365
i = NSMALLNEGINTS + NSMALLPOSINTS;
1372
u = PyInt_ClearFreeList();
1373
if (!Py_VerboseFlag)
1375
fprintf(stderr, "# cleanup ints");
1377
fprintf(stderr, "\n");
1381
": %d unfreed int%s\n",
1382
u, u == 1 ? "" : "s");
1384
if (Py_VerboseFlag > 1) {
1386
while (list != NULL) {
1387
for (i = 0, p = &list->objects[0];
1390
if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1391
/* XXX(twouters) cast refcount to
1392
long until %zd is universally
1396
"# <int at %p, refcnt=%ld, val=%ld>\n",
1397
p, (long)p->ob_refcnt,