blob: 654d2fe120ecd84f28abdce1f7dfa16548af4e9c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Integer object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Barry Warsaw226ae6c1999-10-12 19:54:53 +00005#include <ctype.h>
Mark Dickinson6736cf82009-04-20 21:13:33 +00006#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00008static PyObject *int_int(PyIntObject *v);
9
Guido van Rossum2e1d4331993-12-24 10:22:45 +000010long
Fred Drakea2f55112000-07-09 15:16:51 +000011PyInt_GetMax(void)
Guido van Rossum2e1d4331993-12-24 10:22:45 +000012{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000013 return LONG_MAX; /* To initialize sys.maxint */
Guido van Rossum2e1d4331993-12-24 10:22:45 +000014}
15
Guido van Rossum3f5da241990-12-20 15:06:42 +000016/* Integers are quite normal objects, to make object handling uniform.
17 (Using odd pointers to represent integers would save much space
18 but require extra checks for this special case throughout the code.)
Tim Peters29c0afc2002-04-28 16:57:34 +000019 Since a typical Python program spends much of its time allocating
Guido van Rossum3f5da241990-12-20 15:06:42 +000020 and deallocating integers, these operations should be very fast.
21 Therefore we use a dedicated allocation scheme with a much lower
22 overhead (in space and time) than straight malloc(): a simple
23 dedicated free list, filled when necessary with memory from malloc().
Tim Peters29c0afc2002-04-28 16:57:34 +000024
25 block_list is a singly-linked list of all PyIntBlocks ever allocated,
26 linked via their next members. PyIntBlocks are never returned to the
27 system before shutdown (PyInt_Fini).
28
29 free_list is a singly-linked list of available PyIntObjects, linked
30 via abuse of their ob_type members.
Guido van Rossum3f5da241990-12-20 15:06:42 +000031*/
32
Antoine Pitrouc83ea132010-05-09 14:46:46 +000033#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
34#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
35#define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
Guido van Rossumda084ed1999-03-10 22:55:24 +000036
Guido van Rossum3fce8831999-03-12 19:43:17 +000037struct _intblock {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 struct _intblock *next;
39 PyIntObject objects[N_INTOBJECTS];
Guido van Rossum3fce8831999-03-12 19:43:17 +000040};
41
42typedef struct _intblock PyIntBlock;
43
44static PyIntBlock *block_list = NULL;
45static PyIntObject *free_list = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000046
Guido van Rossumc0b618a1997-05-02 03:12:38 +000047static PyIntObject *
Fred Drakea2f55112000-07-09 15:16:51 +000048fill_free_list(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +000049{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000050 PyIntObject *p, *q;
51 /* Python's object allocator isn't appropriate for large blocks. */
52 p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
53 if (p == NULL)
54 return (PyIntObject *) PyErr_NoMemory();
55 ((PyIntBlock *)p)->next = block_list;
56 block_list = (PyIntBlock *)p;
57 /* Link the int objects together, from rear to front, then return
58 the address of the last int object in the block. */
59 p = &((PyIntBlock *)p)->objects[0];
60 q = p + N_INTOBJECTS;
61 while (--q > p)
62 Py_TYPE(q) = (struct _typeobject *)(q-1);
63 Py_TYPE(q) = NULL;
64 return p + N_INTOBJECTS - 1;
Guido van Rossum3f5da241990-12-20 15:06:42 +000065}
66
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000067#ifndef NSMALLPOSINTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +000068#define NSMALLPOSINTS 257
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000069#endif
70#ifndef NSMALLNEGINTS
Antoine Pitrouc83ea132010-05-09 14:46:46 +000071#define NSMALLNEGINTS 5
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000072#endif
73#if NSMALLNEGINTS + NSMALLPOSINTS > 0
74/* References to small integers are saved in this array so that they
75 can be shared.
76 The integers that are saved are those in the range
77 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
78*/
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000080#endif
81#ifdef COUNT_ALLOCS
Martin v. Löwisb90304a2009-01-07 18:40:40 +000082Py_ssize_t quick_int_allocs;
83Py_ssize_t quick_neg_int_allocs;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000084#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +000085
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000087PyInt_FromLong(long ival)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000089 register PyIntObject *v;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000090#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +000091 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
92 v = small_ints[ival + NSMALLNEGINTS];
93 Py_INCREF(v);
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000094#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +000095 if (ival >= 0)
96 quick_int_allocs++;
97 else
98 quick_neg_int_allocs++;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000099#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000100 return (PyObject *) v;
101 }
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +0000102#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000103 if (free_list == NULL) {
104 if ((free_list = fill_free_list()) == NULL)
105 return NULL;
106 }
107 /* Inline PyObject_New */
108 v = free_list;
109 free_list = (PyIntObject *)Py_TYPE(v);
110 PyObject_INIT(v, &PyInt_Type);
111 v->ob_ival = ival;
112 return (PyObject *) v;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000113}
114
Martin v. Löwis18e16552006-02-15 17:27:45 +0000115PyObject *
116PyInt_FromSize_t(size_t ival)
117{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 if (ival <= LONG_MAX)
119 return PyInt_FromLong((long)ival);
120 return _PyLong_FromSize_t(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000121}
122
123PyObject *
124PyInt_FromSsize_t(Py_ssize_t ival)
125{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000126 if (ival >= LONG_MIN && ival <= LONG_MAX)
127 return PyInt_FromLong((long)ival);
128 return _PyLong_FromSsize_t(ival);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000129}
130
Guido van Rossum3f5da241990-12-20 15:06:42 +0000131static void
Fred Drakea2f55112000-07-09 15:16:51 +0000132int_dealloc(PyIntObject *v)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000133{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000134 if (PyInt_CheckExact(v)) {
135 Py_TYPE(v) = (struct _typeobject *)free_list;
136 free_list = v;
137 }
138 else
139 Py_TYPE(v)->tp_free((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Guido van Rossum93646982002-04-26 00:53:34 +0000142static void
143int_free(PyIntObject *v)
144{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000145 Py_TYPE(v) = (struct _typeobject *)free_list;
146 free_list = v;
Guido van Rossum93646982002-04-26 00:53:34 +0000147}
148
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149long
Fred Drakea2f55112000-07-09 15:16:51 +0000150PyInt_AsLong(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 PyNumberMethods *nb;
153 PyIntObject *io;
154 long val;
Tim Petersa3c01ce2001-12-04 23:05:10 +0000155
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000156 if (op && PyInt_Check(op))
157 return PyInt_AS_LONG((PyIntObject*) op);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000158
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
160 nb->nb_int == NULL) {
161 PyErr_SetString(PyExc_TypeError, "an integer is required");
162 return -1;
163 }
Tim Petersa3c01ce2001-12-04 23:05:10 +0000164
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000165 io = (PyIntObject*) (*nb->nb_int) (op);
166 if (io == NULL)
167 return -1;
168 if (!PyInt_Check(io)) {
169 if (PyLong_Check(io)) {
170 /* got a long? => retry int conversion */
171 val = PyLong_AsLong((PyObject *)io);
172 Py_DECREF(io);
173 if ((val == -1) && PyErr_Occurred())
174 return -1;
175 return val;
176 }
177 else
178 {
179 Py_DECREF(io);
180 PyErr_SetString(PyExc_TypeError,
181 "__int__ method should return an integer");
182 return -1;
183 }
184 }
Tim Petersa3c01ce2001-12-04 23:05:10 +0000185
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000186 val = PyInt_AS_LONG(io);
187 Py_DECREF(io);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000188
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000189 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190}
191
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +0200192int
193_PyInt_AsInt(PyObject *obj)
194{
195 long result = PyInt_AsLong(obj);
196 if (result == -1 && PyErr_Occurred())
197 return -1;
198 if (result > INT_MAX || result < INT_MIN) {
199 PyErr_SetString(PyExc_OverflowError,
200 "Python int too large to convert to C int");
201 return -1;
202 }
203 return (int)result;
204}
205
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206Py_ssize_t
207PyInt_AsSsize_t(register PyObject *op)
208{
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000209#if SIZEOF_SIZE_T != SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210 PyNumberMethods *nb;
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600211 PyObject *io;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 Py_ssize_t val;
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000213#endif
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000214
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000215 if (op == NULL) {
216 PyErr_SetString(PyExc_TypeError, "an integer is required");
217 return -1;
218 }
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000219
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 if (PyInt_Check(op))
221 return PyInt_AS_LONG((PyIntObject*) op);
222 if (PyLong_Check(op))
223 return _PyLong_AsSsize_t(op);
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000224#if SIZEOF_SIZE_T == SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000225 return PyInt_AsLong(op);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226#else
227
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000228 if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
229 (nb->nb_int == NULL && nb->nb_long == 0)) {
230 PyErr_SetString(PyExc_TypeError, "an integer is required");
231 return -1;
232 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000233
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 if (nb->nb_long != 0)
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600235 io = (*nb->nb_long)(op);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 else
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600237 io = (*nb->nb_int)(op);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000238 if (io == NULL)
239 return -1;
240 if (!PyInt_Check(io)) {
241 if (PyLong_Check(io)) {
242 /* got a long? => retry int conversion */
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600243 val = _PyLong_AsSsize_t(io);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 Py_DECREF(io);
245 if ((val == -1) && PyErr_Occurred())
246 return -1;
247 return val;
248 }
249 else
250 {
251 Py_DECREF(io);
252 PyErr_SetString(PyExc_TypeError,
253 "__int__ method should return an integer");
254 return -1;
255 }
256 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000257
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 val = PyInt_AS_LONG(io);
259 Py_DECREF(io);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000260
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 return val;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000262#endif
263}
264
Thomas Hellera4ea6032003-04-17 18:55:45 +0000265unsigned long
266PyInt_AsUnsignedLongMask(register PyObject *op)
267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 PyNumberMethods *nb;
269 PyIntObject *io;
270 unsigned long val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000271
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 if (op && PyInt_Check(op))
273 return PyInt_AS_LONG((PyIntObject*) op);
274 if (op && PyLong_Check(op))
275 return PyLong_AsUnsignedLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000276
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000277 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
278 nb->nb_int == NULL) {
279 PyErr_SetString(PyExc_TypeError, "an integer is required");
280 return (unsigned long)-1;
281 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 io = (PyIntObject*) (*nb->nb_int) (op);
284 if (io == NULL)
285 return (unsigned long)-1;
286 if (!PyInt_Check(io)) {
287 if (PyLong_Check(io)) {
288 val = PyLong_AsUnsignedLongMask((PyObject *)io);
289 Py_DECREF(io);
290 if (PyErr_Occurred())
291 return (unsigned long)-1;
292 return val;
293 }
294 else
295 {
296 Py_DECREF(io);
297 PyErr_SetString(PyExc_TypeError,
298 "__int__ method should return an integer");
299 return (unsigned long)-1;
300 }
301 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 val = PyInt_AS_LONG(io);
304 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000305
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000307}
308
309#ifdef HAVE_LONG_LONG
310unsigned PY_LONG_LONG
311PyInt_AsUnsignedLongLongMask(register PyObject *op)
312{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000313 PyNumberMethods *nb;
314 PyIntObject *io;
315 unsigned PY_LONG_LONG val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000316
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 if (op && PyInt_Check(op))
318 return PyInt_AS_LONG((PyIntObject*) op);
319 if (op && PyLong_Check(op))
320 return PyLong_AsUnsignedLongLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000321
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
323 nb->nb_int == NULL) {
324 PyErr_SetString(PyExc_TypeError, "an integer is required");
325 return (unsigned PY_LONG_LONG)-1;
326 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000327
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 io = (PyIntObject*) (*nb->nb_int) (op);
329 if (io == NULL)
330 return (unsigned PY_LONG_LONG)-1;
331 if (!PyInt_Check(io)) {
332 if (PyLong_Check(io)) {
333 val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
334 Py_DECREF(io);
335 if (PyErr_Occurred())
336 return (unsigned PY_LONG_LONG)-1;
337 return val;
338 }
339 else
340 {
341 Py_DECREF(io);
342 PyErr_SetString(PyExc_TypeError,
343 "__int__ method should return an integer");
344 return (unsigned PY_LONG_LONG)-1;
345 }
346 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000347
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000348 val = PyInt_AS_LONG(io);
349 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000350
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000352}
353#endif
354
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000355PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000356PyInt_FromString(char *s, char **pend, int base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 char *end;
359 long x;
360 Py_ssize_t slen;
361 PyObject *sobj, *srepr;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000362
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000363 if ((base != 0 && base < 2) || base > 36) {
364 PyErr_SetString(PyExc_ValueError,
365 "int() base must be >= 2 and <= 36");
366 return NULL;
367 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000368
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 while (*s && isspace(Py_CHARMASK(*s)))
370 s++;
371 errno = 0;
372 if (base == 0 && s[0] == '0') {
373 x = (long) PyOS_strtoul(s, &end, base);
374 if (x < 0)
375 return PyLong_FromString(s, pend, base);
376 }
377 else
378 x = PyOS_strtol(s, &end, base);
379 if (end == s || !isalnum(Py_CHARMASK(end[-1])))
380 goto bad;
381 while (*end && isspace(Py_CHARMASK(*end)))
382 end++;
383 if (*end != '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000384 bad:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000385 slen = strlen(s) < 200 ? strlen(s) : 200;
386 sobj = PyString_FromStringAndSize(s, slen);
387 if (sobj == NULL)
388 return NULL;
389 srepr = PyObject_Repr(sobj);
390 Py_DECREF(sobj);
391 if (srepr == NULL)
392 return NULL;
393 PyErr_Format(PyExc_ValueError,
394 "invalid literal for int() with base %d: %s",
395 base, PyString_AS_STRING(srepr));
396 Py_DECREF(srepr);
397 return NULL;
398 }
399 else if (errno != 0)
400 return PyLong_FromString(s, pend, base);
401 if (pend)
402 *pend = end;
403 return PyInt_FromLong(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000404}
405
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000406#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000407PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000408PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +0000409{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 PyObject *result;
411 char *buffer = (char *)PyMem_MALLOC(length+1);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 if (buffer == NULL)
414 return PyErr_NoMemory();
Walter Dörwald07e14762002-11-06 16:15:14 +0000415
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000416 if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
417 PyMem_FREE(buffer);
418 return NULL;
419 }
420 result = PyInt_FromString(buffer, NULL, base);
421 PyMem_FREE(buffer);
422 return result;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000423}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000424#endif
Guido van Rossum9e896b32000-04-05 20:11:21 +0000425
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426/* Methods */
427
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000428/* Integers are seen as the "smallest" of all numeric types and thus
429 don't have any knowledge about conversion of other types to
430 integers. */
431
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432#define CONVERT_TO_LONG(obj, lng) \
433 if (PyInt_Check(obj)) { \
434 lng = PyInt_AS_LONG(obj); \
435 } \
436 else { \
437 Py_INCREF(Py_NotImplemented); \
438 return Py_NotImplemented; \
439 }
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000440
Guido van Rossum719f5fa1992-03-27 17:31:02 +0000441/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000442static int
Fred Drakea2f55112000-07-09 15:16:51 +0000443int_print(PyIntObject *v, FILE *fp, int flags)
444 /* flags -- not used but required by interface */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000446 long int_val = v->ob_ival;
447 Py_BEGIN_ALLOW_THREADS
448 fprintf(fp, "%ld", int_val);
449 Py_END_ALLOW_THREADS
450 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451}
452
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453static int
Fred Drakea2f55112000-07-09 15:16:51 +0000454int_compare(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000456 register long i = v->ob_ival;
457 register long j = w->ob_ival;
458 return (i < j) ? -1 : (i > j) ? 1 : 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459}
460
Guido van Rossum9bfef441993-03-29 10:43:31 +0000461static long
Fred Drakea2f55112000-07-09 15:16:51 +0000462int_hash(PyIntObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 /* XXX If this is changed, you also need to change the way
465 Python's long, float and complex types are hashed. */
466 long x = v -> ob_ival;
467 if (x == -1)
468 x = -2;
469 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000470}
471
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000473int_add(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000475 register long a, b, x;
476 CONVERT_TO_LONG(v, a);
477 CONVERT_TO_LONG(w, b);
478 /* casts in the line below avoid undefined behaviour on overflow */
479 x = (long)((unsigned long)a + b);
480 if ((x^a) >= 0 || (x^b) >= 0)
481 return PyInt_FromLong(x);
482 return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483}
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000486int_sub(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 register long a, b, x;
489 CONVERT_TO_LONG(v, a);
490 CONVERT_TO_LONG(w, b);
491 /* casts in the line below avoid undefined behaviour on overflow */
492 x = (long)((unsigned long)a - b);
493 if ((x^a) >= 0 || (x^~b) >= 0)
494 return PyInt_FromLong(x);
495 return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
496 (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497}
498
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000499/*
Tim Petersa3c01ce2001-12-04 23:05:10 +0000500Integer overflow checking for * is painful: Python tried a couple ways, but
501they didn't work on all platforms, or failed in endcases (a product of
502-sys.maxint-1 has been a particular pain).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000503
Tim Petersa3c01ce2001-12-04 23:05:10 +0000504Here's another way:
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000505
Tim Petersa3c01ce2001-12-04 23:05:10 +0000506The native long product x*y is either exactly right or *way* off, being
507just the last n bits of the true product, where n is the number of bits
508in a long (the delivered product is the true product plus i*2**n for
509some integer i).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000510
Tim Petersa3c01ce2001-12-04 23:05:10 +0000511The native double product (double)x * (double)y is subject to three
512rounding errors: on a sizeof(long)==8 box, each cast to double can lose
513info, and even on a sizeof(long)==4 box, the multiplication can lose info.
514But, unlike the native long product, it's not in *range* trouble: even
515if sizeof(long)==32 (256-bit longs), the product easily fits in the
516dynamic range of a double. So the leading 50 (or so) bits of the double
517product are correct.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000518
Tim Petersa3c01ce2001-12-04 23:05:10 +0000519We check these two ways against each other, and declare victory if they're
520approximately the same. Else, because the native long product is the only
521one that can lose catastrophic amounts of information, it's the native long
522product that must have overflowed.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000523*/
524
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525static PyObject *
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000526int_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 long a, b;
529 long longprod; /* a*b in native long arithmetic */
530 double doubled_longprod; /* (double)longprod */
531 double doubleprod; /* (double)a * (double)b */
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 CONVERT_TO_LONG(v, a);
534 CONVERT_TO_LONG(w, b);
535 /* casts in the next line avoid undefined behaviour on overflow */
536 longprod = (long)((unsigned long)a * b);
537 doubleprod = (double)a * (double)b;
538 doubled_longprod = (double)longprod;
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000539
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000540 /* Fast path for normal case: small multiplicands, and no info
541 is lost in either method. */
542 if (doubled_longprod == doubleprod)
543 return PyInt_FromLong(longprod);
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000544
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 /* Somebody somewhere lost info. Close enough, or way off? Note
546 that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
547 The difference either is or isn't significant compared to the
548 true value (of which doubleprod is a good approximation).
549 */
550 {
551 const double diff = doubled_longprod - doubleprod;
552 const double absdiff = diff >= 0.0 ? diff : -diff;
553 const double absprod = doubleprod >= 0.0 ? doubleprod :
554 -doubleprod;
555 /* absdiff/absprod <= 1/32 iff
556 32 * absdiff <= absprod -- 5 good bits is "close enough" */
557 if (32.0 * absdiff <= absprod)
558 return PyInt_FromLong(longprod);
559 else
560 return PyLong_Type.tp_as_number->nb_multiply(v, w);
561 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Armin Rigo7ccbca92006-10-04 12:17:45 +0000564/* Integer overflow checking for unary negation: on a 2's-complement
565 * box, -x overflows iff x is the most negative long. In this case we
566 * get -x == x. However, -x is undefined (by C) if x /is/ the most
567 * negative long (it's a signed overflow case), and some compilers care.
568 * So we cast x to unsigned long first. However, then other compilers
569 * warn about applying unary minus to an unsigned operand. Hence the
570 * weird "0-".
571 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000572#define UNARY_NEG_WOULD_OVERFLOW(x) \
573 ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
Armin Rigo7ccbca92006-10-04 12:17:45 +0000574
Guido van Rossume27f7952001-08-23 02:59:04 +0000575/* Return type of i_divmod */
576enum divmod_result {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 DIVMOD_OK, /* Correct result */
578 DIVMOD_OVERFLOW, /* Overflow, try again using longs */
579 DIVMOD_ERROR /* Exception raised */
Guido van Rossume27f7952001-08-23 02:59:04 +0000580};
581
582static enum divmod_result
Tim Peters1dad6a82001-06-18 19:21:11 +0000583i_divmod(register long x, register long y,
Fred Drakea2f55112000-07-09 15:16:51 +0000584 long *p_xdivy, long *p_xmody)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000585{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000586 long xdivy, xmody;
Tim Petersa3c01ce2001-12-04 23:05:10 +0000587
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000588 if (y == 0) {
589 PyErr_SetString(PyExc_ZeroDivisionError,
590 "integer division or modulo by zero");
591 return DIVMOD_ERROR;
592 }
593 /* (-sys.maxint-1)/-1 is the only overflow case. */
594 if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
595 return DIVMOD_OVERFLOW;
596 xdivy = x / y;
597 /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
598 * for x and y with differing signs. (This is unusual
599 * behaviour, and C99 prohibits it, but it's allowed by C89;
600 * for an example of overflow, take x = LONG_MIN, y = 5 or x =
601 * LONG_MAX, y = -5.) However, x - xdivy*y is always
602 * representable as a long, since it lies strictly between
603 * -abs(y) and abs(y). We add casts to avoid intermediate
604 * overflow.
605 */
606 xmody = (long)(x - (unsigned long)xdivy * y);
607 /* If the signs of x and y differ, and the remainder is non-0,
608 * C89 doesn't define whether xdivy is now the floor or the
609 * ceiling of the infinitely precise quotient. We want the floor,
610 * and we have it iff the remainder's sign matches y's.
611 */
612 if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
613 xmody += y;
614 --xdivy;
615 assert(xmody && ((y ^ xmody) >= 0));
616 }
617 *p_xdivy = xdivy;
618 *p_xmody = xmody;
619 return DIVMOD_OK;
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000620}
621
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000623int_div(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000624{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000625 long xi, yi;
626 long d, m;
627 CONVERT_TO_LONG(x, xi);
628 CONVERT_TO_LONG(y, yi);
629 switch (i_divmod(xi, yi, &d, &m)) {
630 case DIVMOD_OK:
631 return PyInt_FromLong(d);
632 case DIVMOD_OVERFLOW:
633 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
634 (PyObject *)y);
635 default:
636 return NULL;
637 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000638}
639
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000641int_classic_div(PyIntObject *x, PyIntObject *y)
642{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000643 long xi, yi;
644 long d, m;
645 CONVERT_TO_LONG(x, xi);
646 CONVERT_TO_LONG(y, yi);
647 if (Py_DivisionWarningFlag &&
648 PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
649 return NULL;
650 switch (i_divmod(xi, yi, &d, &m)) {
651 case DIVMOD_OK:
652 return PyInt_FromLong(d);
653 case DIVMOD_OVERFLOW:
654 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
655 (PyObject *)y);
656 default:
657 return NULL;
658 }
Guido van Rossum393661d2001-08-31 17:40:15 +0000659}
660
661static PyObject *
Mark Dickinson46572832009-12-27 14:55:57 +0000662int_true_divide(PyIntObject *x, PyIntObject *y)
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000663{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000664 long xi, yi;
665 /* If they aren't both ints, give someone else a chance. In
666 particular, this lets int/long get handled by longs, which
667 underflows to 0 gracefully if the long is too big to convert
668 to float. */
669 CONVERT_TO_LONG(x, xi);
670 CONVERT_TO_LONG(y, yi);
671 if (yi == 0) {
672 PyErr_SetString(PyExc_ZeroDivisionError,
673 "division by zero");
674 return NULL;
675 }
676 if (xi == 0)
677 return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
Mark Dickinson46572832009-12-27 14:55:57 +0000678
679#define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG)
680#if DBL_MANT_DIG < WIDTH_OF_ULONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
682 (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
683 /* Large x or y. Use long integer arithmetic. */
684 return PyLong_Type.tp_as_number->nb_true_divide(
685 (PyObject *)x, (PyObject *)y);
686 else
Mark Dickinson46572832009-12-27 14:55:57 +0000687#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000688 /* Both ints can be exactly represented as doubles. Do a
689 floating-point division. */
690 return PyFloat_FromDouble((double)xi / (double)yi);
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000691}
692
693static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000694int_mod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000695{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 long xi, yi;
697 long d, m;
698 CONVERT_TO_LONG(x, xi);
699 CONVERT_TO_LONG(y, yi);
700 switch (i_divmod(xi, yi, &d, &m)) {
701 case DIVMOD_OK:
702 return PyInt_FromLong(m);
703 case DIVMOD_OVERFLOW:
704 return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
705 (PyObject *)y);
706 default:
707 return NULL;
708 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000709}
710
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000712int_divmod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000713{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 long xi, yi;
715 long d, m;
716 CONVERT_TO_LONG(x, xi);
717 CONVERT_TO_LONG(y, yi);
718 switch (i_divmod(xi, yi, &d, &m)) {
719 case DIVMOD_OK:
720 return Py_BuildValue("(ll)", d, m);
721 case DIVMOD_OVERFLOW:
722 return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
723 (PyObject *)y);
724 default:
725 return NULL;
726 }
Guido van Rossum00466951991-05-05 20:08:27 +0000727}
728
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000730int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 register long iv, iw, iz=0, ix, temp, prev;
733 CONVERT_TO_LONG(v, iv);
734 CONVERT_TO_LONG(w, iw);
735 if (iw < 0) {
736 if ((PyObject *)z != Py_None) {
737 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
738 "cannot be negative when 3rd argument specified");
739 return NULL;
740 }
741 /* Return a float. This works because we know that
742 this calls float_pow() which converts its
743 arguments to double. */
744 return PyFloat_Type.tp_as_number->nb_power(
745 (PyObject *)v, (PyObject *)w, (PyObject *)z);
746 }
747 if ((PyObject *)z != Py_None) {
748 CONVERT_TO_LONG(z, iz);
749 if (iz == 0) {
750 PyErr_SetString(PyExc_ValueError,
751 "pow() 3rd argument cannot be 0");
752 return NULL;
753 }
754 }
755 /*
756 * XXX: The original exponentiation code stopped looping
757 * when temp hit zero; this code will continue onwards
758 * unnecessarily, but at least it won't cause any errors.
759 * Hopefully the speed improvement from the fast exponentiation
760 * will compensate for the slight inefficiency.
761 * XXX: Better handling of overflows is desperately needed.
762 */
763 temp = iv;
764 ix = 1;
765 while (iw > 0) {
766 prev = ix; /* Save value for overflow check */
767 if (iw & 1) {
Mark Dickinsondbbed042011-09-19 16:38:08 +0100768 /*
769 * The (unsigned long) cast below ensures that the multiplication
770 * is interpreted as an unsigned operation rather than a signed one
771 * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour
772 * from signed arithmetic overflow (C99 6.5p5). See issue #12973.
773 */
774 ix = (unsigned long)ix * temp;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000775 if (temp == 0)
776 break; /* Avoid ix / 0 */
777 if (ix / temp != prev) {
778 return PyLong_Type.tp_as_number->nb_power(
779 (PyObject *)v,
780 (PyObject *)w,
781 (PyObject *)z);
782 }
783 }
784 iw >>= 1; /* Shift exponent down by 1 bit */
785 if (iw==0) break;
786 prev = temp;
Mark Dickinsondbbed042011-09-19 16:38:08 +0100787 temp = (unsigned long)temp * temp; /* Square the value of temp */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000788 if (prev != 0 && temp / prev != prev) {
789 return PyLong_Type.tp_as_number->nb_power(
790 (PyObject *)v, (PyObject *)w, (PyObject *)z);
791 }
792 if (iz) {
793 /* If we did a multiplication, perform a modulo */
794 ix = ix % iz;
795 temp = temp % iz;
796 }
797 }
798 if (iz) {
799 long div, mod;
800 switch (i_divmod(ix, iz, &div, &mod)) {
801 case DIVMOD_OK:
802 ix = mod;
803 break;
804 case DIVMOD_OVERFLOW:
805 return PyLong_Type.tp_as_number->nb_power(
806 (PyObject *)v, (PyObject *)w, (PyObject *)z);
807 default:
808 return NULL;
809 }
810 }
811 return PyInt_FromLong(ix);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000812}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000813
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000814static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000815int_neg(PyIntObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 register long a;
818 a = v->ob_ival;
819 /* check for overflow */
820 if (UNARY_NEG_WOULD_OVERFLOW(a)) {
821 PyObject *o = PyLong_FromLong(a);
822 if (o != NULL) {
823 PyObject *result = PyNumber_Negative(o);
824 Py_DECREF(o);
825 return result;
826 }
827 return NULL;
828 }
829 return PyInt_FromLong(-a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830}
831
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000833int_abs(PyIntObject *v)
Guido van Rossum00466951991-05-05 20:08:27 +0000834{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 if (v->ob_ival >= 0)
836 return int_int(v);
837 else
838 return int_neg(v);
Guido van Rossum00466951991-05-05 20:08:27 +0000839}
840
Guido van Rossum0bff0151991-05-14 12:05:32 +0000841static int
Fred Drakea2f55112000-07-09 15:16:51 +0000842int_nonzero(PyIntObject *v)
Guido van Rossum0bff0151991-05-14 12:05:32 +0000843{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000844 return v->ob_ival != 0;
Guido van Rossum0bff0151991-05-14 12:05:32 +0000845}
846
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000847static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000848int_invert(PyIntObject *v)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000849{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000850 return PyInt_FromLong(~v->ob_ival);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000851}
852
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000853static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000854int_lshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000855{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000856 long a, b, c;
857 PyObject *vv, *ww, *result;
Raymond Hettingera006c372004-06-26 23:22:57 +0000858
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 CONVERT_TO_LONG(v, a);
860 CONVERT_TO_LONG(w, b);
861 if (b < 0) {
862 PyErr_SetString(PyExc_ValueError, "negative shift count");
863 return NULL;
864 }
865 if (a == 0 || b == 0)
866 return int_int(v);
867 if (b >= LONG_BIT) {
868 vv = PyLong_FromLong(PyInt_AS_LONG(v));
869 if (vv == NULL)
870 return NULL;
871 ww = PyLong_FromLong(PyInt_AS_LONG(w));
872 if (ww == NULL) {
873 Py_DECREF(vv);
874 return NULL;
875 }
876 result = PyNumber_Lshift(vv, ww);
877 Py_DECREF(vv);
878 Py_DECREF(ww);
879 return result;
880 }
881 c = a << b;
882 if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
883 vv = PyLong_FromLong(PyInt_AS_LONG(v));
884 if (vv == NULL)
885 return NULL;
886 ww = PyLong_FromLong(PyInt_AS_LONG(w));
887 if (ww == NULL) {
888 Py_DECREF(vv);
889 return NULL;
890 }
891 result = PyNumber_Lshift(vv, ww);
892 Py_DECREF(vv);
893 Py_DECREF(ww);
894 return result;
895 }
896 return PyInt_FromLong(c);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000897}
898
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000899static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000900int_rshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000901{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000902 register long a, b;
903 CONVERT_TO_LONG(v, a);
904 CONVERT_TO_LONG(w, b);
905 if (b < 0) {
906 PyErr_SetString(PyExc_ValueError, "negative shift count");
907 return NULL;
908 }
909 if (a == 0 || b == 0)
910 return int_int(v);
911 if (b >= LONG_BIT) {
912 if (a < 0)
913 a = -1;
914 else
915 a = 0;
916 }
917 else {
918 a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
919 }
920 return PyInt_FromLong(a);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000921}
922
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000923static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000924int_and(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 register long a, b;
927 CONVERT_TO_LONG(v, a);
928 CONVERT_TO_LONG(w, b);
929 return PyInt_FromLong(a & b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000930}
931
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000933int_xor(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 register long a, b;
936 CONVERT_TO_LONG(v, a);
937 CONVERT_TO_LONG(w, b);
938 return PyInt_FromLong(a ^ b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000939}
940
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000942int_or(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 register long a, b;
945 CONVERT_TO_LONG(v, a);
946 CONVERT_TO_LONG(w, b);
947 return PyInt_FromLong(a | b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000948}
949
Guido van Rossum1952e382001-09-19 01:25:16 +0000950static int
951int_coerce(PyObject **pv, PyObject **pw)
952{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 if (PyInt_Check(*pw)) {
954 Py_INCREF(*pv);
955 Py_INCREF(*pw);
956 return 0;
957 }
958 return 1; /* Can't do it */
Guido van Rossum1952e382001-09-19 01:25:16 +0000959}
960
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000961static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000962int_int(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000963{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 if (PyInt_CheckExact(v))
965 Py_INCREF(v);
966 else
967 v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
968 return (PyObject *)v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000969}
970
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000971static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000972int_long(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000973{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000974 return PyLong_FromLong((v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000975}
976
Mark Dickinson6736cf82009-04-20 21:13:33 +0000977static const unsigned char BitLengthTable[32] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000978 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
979 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson6736cf82009-04-20 21:13:33 +0000980};
981
982static int
983bits_in_ulong(unsigned long d)
984{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 int d_bits = 0;
986 while (d >= 32) {
987 d_bits += 6;
988 d >>= 6;
989 }
990 d_bits += (int)BitLengthTable[d];
991 return d_bits;
Mark Dickinson6736cf82009-04-20 21:13:33 +0000992}
993
994#if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG
995/* Every Python int can be exactly represented as a float. */
996
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000998int_float(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000999{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 return PyFloat_FromDouble((double)(v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001001}
1002
Mark Dickinson6736cf82009-04-20 21:13:33 +00001003#else
1004/* Here not all Python ints are exactly representable as floats, so we may
1005 have to round. We do this manually, since the C standards don't specify
1006 whether converting an integer to a float rounds up or down */
1007
1008static PyObject *
1009int_float(PyIntObject *v)
1010{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 unsigned long abs_ival, lsb;
1012 int round_up;
Mark Dickinson6736cf82009-04-20 21:13:33 +00001013
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001014 if (v->ob_ival < 0)
1015 abs_ival = 0U-(unsigned long)v->ob_ival;
1016 else
1017 abs_ival = (unsigned long)v->ob_ival;
1018 if (abs_ival < (1L << DBL_MANT_DIG))
1019 /* small integer; no need to round */
1020 return PyFloat_FromDouble((double)v->ob_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001022 /* Round abs_ival to MANT_DIG significant bits, using the
1023 round-half-to-even rule. abs_ival & lsb picks out the 'rounding'
1024 bit: the first bit after the most significant MANT_DIG bits of
1025 abs_ival. We round up if this bit is set, provided that either:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 (1) abs_ival isn't exactly halfway between two floats, in which
1028 case at least one of the bits following the rounding bit must be
1029 set; i.e., abs_ival & lsb-1 != 0, or:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001030
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001031 (2) the resulting rounded value has least significant bit 0; or
1032 in other words the bit above the rounding bit is set (this is the
1033 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
Mark Dickinson6736cf82009-04-20 21:13:33 +00001034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001035 The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
Mark Dickinson6736cf82009-04-20 21:13:33 +00001036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001037 lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
1038 round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
1039 abs_ival &= -2*lsb;
1040 if (round_up)
1041 abs_ival += 2*lsb;
1042 return PyFloat_FromDouble(v->ob_ival < 0 ?
1043 -(double)abs_ival :
1044 (double)abs_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001045}
1046
1047#endif
1048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001050int_oct(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 return _PyInt_Format(v, 8, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001053}
1054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001056int_hex(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 return _PyInt_Format(v, 16, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001059}
1060
Jeremy Hylton938ace62002-07-17 16:30:39 +00001061static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001062int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1063
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064static PyObject *
1065int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1066{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001067 PyObject *x = NULL;
1068 int base = -909;
1069 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001071 if (type != &PyInt_Type)
1072 return int_subtype_new(type, args, kwds); /* Wimp out */
1073 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
1074 &x, &base))
1075 return NULL;
Serhiy Storchakacf095f82012-12-28 09:31:59 +02001076 if (x == NULL) {
1077 if (base != -909) {
1078 PyErr_SetString(PyExc_TypeError,
1079 "int() missing string argument");
1080 return NULL;
1081 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001082 return PyInt_FromLong(0L);
Serhiy Storchakacf095f82012-12-28 09:31:59 +02001083 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001084 if (base == -909)
1085 return PyNumber_Int(x);
1086 if (PyString_Check(x)) {
1087 /* Since PyInt_FromString doesn't have a length parameter,
1088 * check here for possible NULs in the string. */
1089 char *string = PyString_AS_STRING(x);
1090 if (strlen(string) != PyString_Size(x)) {
1091 /* create a repr() of the input string,
1092 * just like PyInt_FromString does */
1093 PyObject *srepr;
1094 srepr = PyObject_Repr(x);
1095 if (srepr == NULL)
1096 return NULL;
1097 PyErr_Format(PyExc_ValueError,
1098 "invalid literal for int() with base %d: %s",
1099 base, PyString_AS_STRING(srepr));
1100 Py_DECREF(srepr);
1101 return NULL;
1102 }
1103 return PyInt_FromString(string, NULL, base);
1104 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001105#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001106 if (PyUnicode_Check(x))
1107 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
1108 PyUnicode_GET_SIZE(x),
1109 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001110#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001111 PyErr_SetString(PyExc_TypeError,
1112 "int() can't convert non-string with explicit base");
1113 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114}
1115
Guido van Rossumbef14172001-08-29 15:47:46 +00001116/* Wimpy, slow approach to tp_new calls for subtypes of int:
1117 first create a regular int from whatever arguments we got,
1118 then allocate a subtype instance and initialize its ob_ival
1119 from the regular int. The regular int is then thrown away.
1120*/
1121static PyObject *
1122int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1123{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001124 PyObject *tmp, *newobj;
1125 long ival;
Guido van Rossumbef14172001-08-29 15:47:46 +00001126
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 assert(PyType_IsSubtype(type, &PyInt_Type));
1128 tmp = int_new(&PyInt_Type, args, kwds);
1129 if (tmp == NULL)
1130 return NULL;
1131 if (!PyInt_Check(tmp)) {
1132 ival = PyLong_AsLong(tmp);
1133 if (ival == -1 && PyErr_Occurred()) {
1134 Py_DECREF(tmp);
1135 return NULL;
1136 }
1137 } else {
1138 ival = ((PyIntObject *)tmp)->ob_ival;
1139 }
Neal Norwitzde8b94c2003-02-10 02:12:43 +00001140
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001141 newobj = type->tp_alloc(type, 0);
1142 if (newobj == NULL) {
1143 Py_DECREF(tmp);
1144 return NULL;
1145 }
1146 ((PyIntObject *)newobj)->ob_ival = ival;
1147 Py_DECREF(tmp);
1148 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001149}
1150
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001151static PyObject *
1152int_getnewargs(PyIntObject *v)
1153{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001154 return Py_BuildValue("(l)", v->ob_ival);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001155}
1156
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001157static PyObject *
Mark Dickinson85e269b2009-05-03 20:39:06 +00001158int_get0(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001159 return PyInt_FromLong(0L);
Mark Dickinson85e269b2009-05-03 20:39:06 +00001160}
1161
1162static PyObject *
1163int_get1(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001164 return PyInt_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001165}
1166
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001167/* Convert an integer to a decimal string. On many platforms, this
1168 will be significantly faster than the general arbitrary-base
1169 conversion machinery in _PyInt_Format, thanks to optimization
1170 opportunities offered by division by a compile-time constant. */
1171static PyObject *
1172int_to_decimal_string(PyIntObject *v) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001173 char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
1174 long n = v->ob_ival;
1175 unsigned long absn;
1176 p = bufend = buf + sizeof(buf);
1177 absn = n < 0 ? 0UL - n : n;
1178 do {
1179 *--p = '0' + (char)(absn % 10);
1180 absn /= 10;
1181 } while (absn);
1182 if (n < 0)
1183 *--p = '-';
1184 return PyString_FromStringAndSize(p, bufend - p);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001185}
1186
Eric Smith5e527eb2008-02-10 01:36:53 +00001187/* Convert an integer to the given base. Returns a string.
1188 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
1189 If newstyle is zero, then use the pre-2.6 behavior of octal having
1190 a leading "0" */
1191PyAPI_FUNC(PyObject*)
1192_PyInt_Format(PyIntObject *v, int base, int newstyle)
1193{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001194 /* There are no doubt many, many ways to optimize this, using code
1195 similar to _PyLong_Format */
1196 long n = v->ob_ival;
1197 int negative = n < 0;
1198 int is_zero = n == 0;
Eric Smith5e527eb2008-02-10 01:36:53 +00001199
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001200 /* For the reasoning behind this size, see
1201 http://c-faq.com/misc/hexio.html. Then, add a few bytes for
1202 the possible sign and prefix "0[box]" */
1203 char buf[sizeof(n)*CHAR_BIT+6];
Eric Smith5e527eb2008-02-10 01:36:53 +00001204
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001205 /* Start by pointing to the end of the buffer. We fill in from
1206 the back forward. */
1207 char* p = &buf[sizeof(buf)];
Eric Smith5e527eb2008-02-10 01:36:53 +00001208
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001209 assert(base >= 2 && base <= 36);
Eric Smith5e527eb2008-02-10 01:36:53 +00001210
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001211 /* Special case base 10, for speed */
1212 if (base == 10)
1213 return int_to_decimal_string(v);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001214
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001215 do {
1216 /* I'd use i_divmod, except it doesn't produce the results
1217 I want when n is negative. So just duplicate the salient
1218 part here. */
1219 long div = n / base;
1220 long mod = n - div * base;
Eric Smith5e527eb2008-02-10 01:36:53 +00001221
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001222 /* convert abs(mod) to the right character in [0-9, a-z] */
1223 char cdigit = (char)(mod < 0 ? -mod : mod);
1224 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1225 *--p = cdigit;
Eric Smith5e527eb2008-02-10 01:36:53 +00001226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001227 n = div;
1228 } while(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001229
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 if (base == 2) {
1231 *--p = 'b';
1232 *--p = '0';
1233 }
1234 else if (base == 8) {
1235 if (newstyle) {
1236 *--p = 'o';
1237 *--p = '0';
1238 }
1239 else
1240 if (!is_zero)
1241 *--p = '0';
1242 }
1243 else if (base == 16) {
1244 *--p = 'x';
1245 *--p = '0';
1246 }
1247 else {
1248 *--p = '#';
1249 *--p = '0' + base%10;
1250 if (base > 10)
1251 *--p = '0' + base/10;
1252 }
1253 if (negative)
1254 *--p = '-';
Eric Smith5e527eb2008-02-10 01:36:53 +00001255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
Eric Smith5e527eb2008-02-10 01:36:53 +00001257}
1258
Eric Smitha9f7d622008-02-17 19:46:49 +00001259static PyObject *
1260int__format__(PyObject *self, PyObject *args)
1261{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001262 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001263
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001264 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1265 return NULL;
1266 if (PyBytes_Check(format_spec))
1267 return _PyInt_FormatAdvanced(self,
1268 PyBytes_AS_STRING(format_spec),
1269 PyBytes_GET_SIZE(format_spec));
1270 if (PyUnicode_Check(format_spec)) {
1271 /* Convert format_spec to a str */
1272 PyObject *result;
1273 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001274
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 if (str_spec == NULL)
1276 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001277
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001278 result = _PyInt_FormatAdvanced(self,
1279 PyBytes_AS_STRING(str_spec),
1280 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001282 Py_DECREF(str_spec);
1283 return result;
1284 }
1285 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1286 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001287}
1288
Mark Dickinson1a707982008-12-17 16:14:37 +00001289static PyObject *
1290int_bit_length(PyIntObject *v)
1291{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001292 unsigned long n;
Mark Dickinson1a707982008-12-17 16:14:37 +00001293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001294 if (v->ob_ival < 0)
1295 /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
1296 n = 0U-(unsigned long)v->ob_ival;
1297 else
1298 n = (unsigned long)v->ob_ival;
Mark Dickinson1a707982008-12-17 16:14:37 +00001299
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 return PyInt_FromLong(bits_in_ulong(n));
Mark Dickinson1a707982008-12-17 16:14:37 +00001301}
1302
1303PyDoc_STRVAR(int_bit_length_doc,
1304"int.bit_length() -> int\n\
1305\n\
1306Number of bits necessary to represent self in binary.\n\
1307>>> bin(37)\n\
1308'0b100101'\n\
1309>>> (37).bit_length()\n\
13106");
1311
Christian Heimes6f341092008-04-18 23:13:07 +00001312#if 0
1313static PyObject *
1314int_is_finite(PyObject *v)
1315{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001316 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00001317}
1318#endif
1319
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001320static PyMethodDef int_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001321 {"conjugate", (PyCFunction)int_int, METH_NOARGS,
1322 "Returns self, the complex conjugate of any int."},
1323 {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
1324 int_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001325#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001326 {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
1327 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00001328#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001329 {"__trunc__", (PyCFunction)int_int, METH_NOARGS,
1330 "Truncating an Integral returns itself."},
1331 {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
1332 {"__format__", (PyCFunction)int__format__, METH_VARARGS},
1333 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001334};
1335
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001336static PyGetSetDef int_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 {"real",
1338 (getter)int_int, (setter)NULL,
1339 "the real part of a complex number",
1340 NULL},
1341 {"imag",
1342 (getter)int_get0, (setter)NULL,
1343 "the imaginary part of a complex number",
1344 NULL},
1345 {"numerator",
1346 (getter)int_int, (setter)NULL,
1347 "the numerator of a rational number in lowest terms",
1348 NULL},
1349 {"denominator",
1350 (getter)int_get1, (setter)NULL,
1351 "the denominator of a rational number in lowest terms",
1352 NULL},
1353 {NULL} /* Sentinel */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001354};
1355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001356PyDoc_STRVAR(int_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -07001357"int(x=0) -> int or long\n\
1358int(x, base=10) -> int or long\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359\n\
Chris Jerdonekad4b0002012-10-07 20:37:54 -07001360Convert a number or string to an integer, or return 0 if no arguments\n\
1361are given. If x is floating point, the conversion truncates towards zero.\n\
1362If x is outside the integer range, the function returns a long instead.\n\
1363\n\
1364If x is not a number or if base is given, then x must be a string or\n\
1365Unicode object representing an integer literal in the given base. The\n\
1366literal can be preceded by '+' or '-' and be surrounded by whitespace.\n\
1367The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n\
1368interpret the base from the string as an integer literal.\n\
1369>>> int('0b100', base=0)\n\
13704");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372static PyNumberMethods int_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001373 (binaryfunc)int_add, /*nb_add*/
1374 (binaryfunc)int_sub, /*nb_subtract*/
1375 (binaryfunc)int_mul, /*nb_multiply*/
1376 (binaryfunc)int_classic_div, /*nb_divide*/
1377 (binaryfunc)int_mod, /*nb_remainder*/
1378 (binaryfunc)int_divmod, /*nb_divmod*/
1379 (ternaryfunc)int_pow, /*nb_power*/
1380 (unaryfunc)int_neg, /*nb_negative*/
1381 (unaryfunc)int_int, /*nb_positive*/
1382 (unaryfunc)int_abs, /*nb_absolute*/
1383 (inquiry)int_nonzero, /*nb_nonzero*/
1384 (unaryfunc)int_invert, /*nb_invert*/
1385 (binaryfunc)int_lshift, /*nb_lshift*/
1386 (binaryfunc)int_rshift, /*nb_rshift*/
1387 (binaryfunc)int_and, /*nb_and*/
1388 (binaryfunc)int_xor, /*nb_xor*/
1389 (binaryfunc)int_or, /*nb_or*/
1390 int_coerce, /*nb_coerce*/
1391 (unaryfunc)int_int, /*nb_int*/
1392 (unaryfunc)int_long, /*nb_long*/
1393 (unaryfunc)int_float, /*nb_float*/
1394 (unaryfunc)int_oct, /*nb_oct*/
1395 (unaryfunc)int_hex, /*nb_hex*/
1396 0, /*nb_inplace_add*/
1397 0, /*nb_inplace_subtract*/
1398 0, /*nb_inplace_multiply*/
1399 0, /*nb_inplace_divide*/
1400 0, /*nb_inplace_remainder*/
1401 0, /*nb_inplace_power*/
1402 0, /*nb_inplace_lshift*/
1403 0, /*nb_inplace_rshift*/
1404 0, /*nb_inplace_and*/
1405 0, /*nb_inplace_xor*/
1406 0, /*nb_inplace_or*/
1407 (binaryfunc)int_div, /* nb_floor_divide */
1408 (binaryfunc)int_true_divide, /* nb_true_divide */
1409 0, /* nb_inplace_floor_divide */
1410 0, /* nb_inplace_true_divide */
1411 (unaryfunc)int_int, /* nb_index */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412};
1413
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001414PyTypeObject PyInt_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1416 "int",
1417 sizeof(PyIntObject),
1418 0,
1419 (destructor)int_dealloc, /* tp_dealloc */
1420 (printfunc)int_print, /* tp_print */
1421 0, /* tp_getattr */
1422 0, /* tp_setattr */
1423 (cmpfunc)int_compare, /* tp_compare */
1424 (reprfunc)int_to_decimal_string, /* tp_repr */
1425 &int_as_number, /* tp_as_number */
1426 0, /* tp_as_sequence */
1427 0, /* tp_as_mapping */
1428 (hashfunc)int_hash, /* tp_hash */
1429 0, /* tp_call */
1430 (reprfunc)int_to_decimal_string, /* tp_str */
1431 PyObject_GenericGetAttr, /* tp_getattro */
1432 0, /* tp_setattro */
1433 0, /* tp_as_buffer */
1434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1435 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
1436 int_doc, /* tp_doc */
1437 0, /* tp_traverse */
1438 0, /* tp_clear */
1439 0, /* tp_richcompare */
1440 0, /* tp_weaklistoffset */
1441 0, /* tp_iter */
1442 0, /* tp_iternext */
1443 int_methods, /* tp_methods */
1444 0, /* tp_members */
1445 int_getset, /* tp_getset */
1446 0, /* tp_base */
1447 0, /* tp_dict */
1448 0, /* tp_descr_get */
1449 0, /* tp_descr_set */
1450 0, /* tp_dictoffset */
1451 0, /* tp_init */
1452 0, /* tp_alloc */
1453 int_new, /* tp_new */
1454 (freefunc)int_free, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001455};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001456
Neal Norwitzc91ed402002-12-30 22:29:22 +00001457int
Neal Norwitzb2501f42002-12-31 03:42:13 +00001458_PyInt_Init(void)
Neal Norwitzc91ed402002-12-30 22:29:22 +00001459{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001460 PyIntObject *v;
1461 int ival;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001462#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
1464 if (!free_list && (free_list = fill_free_list()) == NULL)
1465 return 0;
1466 /* PyObject_New is inlined */
1467 v = free_list;
1468 free_list = (PyIntObject *)Py_TYPE(v);
1469 PyObject_INIT(v, &PyInt_Type);
1470 v->ob_ival = ival;
1471 small_ints[ival + NSMALLNEGINTS] = v;
1472 }
Neal Norwitzc91ed402002-12-30 22:29:22 +00001473#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001475}
1476
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001477int
1478PyInt_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001479{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 PyIntObject *p;
1481 PyIntBlock *list, *next;
1482 int i;
1483 int u; /* remaining unfreed ints per block */
1484 int freelist_size = 0;
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001485
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001486 list = block_list;
1487 block_list = NULL;
1488 free_list = NULL;
1489 while (list != NULL) {
1490 u = 0;
1491 for (i = 0, p = &list->objects[0];
1492 i < N_INTOBJECTS;
1493 i++, p++) {
1494 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1495 u++;
1496 }
1497 next = list->next;
1498 if (u) {
1499 list->next = block_list;
1500 block_list = list;
1501 for (i = 0, p = &list->objects[0];
1502 i < N_INTOBJECTS;
1503 i++, p++) {
1504 if (!PyInt_CheckExact(p) ||
1505 p->ob_refcnt == 0) {
1506 Py_TYPE(p) = (struct _typeobject *)
1507 free_list;
1508 free_list = p;
1509 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001510#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001511 else if (-NSMALLNEGINTS <= p->ob_ival &&
1512 p->ob_ival < NSMALLPOSINTS &&
1513 small_ints[p->ob_ival +
1514 NSMALLNEGINTS] == NULL) {
1515 Py_INCREF(p);
1516 small_ints[p->ob_ival +
1517 NSMALLNEGINTS] = p;
1518 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001519#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 }
1521 }
1522 else {
1523 PyMem_FREE(list);
1524 }
1525 freelist_size += u;
1526 list = next;
1527 }
Christian Heimes422051a2008-02-04 18:00:12 +00001528
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001529 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001530}
1531
1532void
1533PyInt_Fini(void)
1534{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001535 PyIntObject *p;
1536 PyIntBlock *list;
1537 int i;
1538 int u; /* total unfreed ints per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001539
1540#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001541 PyIntObject **q;
Christian Heimes422051a2008-02-04 18:00:12 +00001542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 i = NSMALLNEGINTS + NSMALLPOSINTS;
1544 q = small_ints;
1545 while (--i >= 0) {
1546 Py_XDECREF(*q);
1547 *q++ = NULL;
1548 }
Christian Heimes422051a2008-02-04 18:00:12 +00001549#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 u = PyInt_ClearFreeList();
1551 if (!Py_VerboseFlag)
1552 return;
1553 fprintf(stderr, "# cleanup ints");
1554 if (!u) {
1555 fprintf(stderr, "\n");
1556 }
1557 else {
1558 fprintf(stderr,
1559 ": %d unfreed int%s\n",
1560 u, u == 1 ? "" : "s");
1561 }
1562 if (Py_VerboseFlag > 1) {
1563 list = block_list;
1564 while (list != NULL) {
1565 for (i = 0, p = &list->objects[0];
1566 i < N_INTOBJECTS;
1567 i++, p++) {
1568 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1569 /* XXX(twouters) cast refcount to
1570 long until %zd is universally
1571 available
1572 */
1573 fprintf(stderr,
1574 "# <int at %p, refcnt=%ld, val=%ld>\n",
1575 p, (long)p->ob_refcnt,
1576 p->ob_ival);
1577 }
1578 list = list->next;
1579 }
1580 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001581}