blob: 0c5ea65ac027b8c6e6506b7f6c66d176ace327c8 [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);
Martin Panter646b5282016-06-21 23:58:05 +0000110 (void)PyObject_INIT(v, &PyInt_Type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000111 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
142long
Fred Drakea2f55112000-07-09 15:16:51 +0000143PyInt_AsLong(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000145 PyNumberMethods *nb;
146 PyIntObject *io;
147 long val;
Tim Petersa3c01ce2001-12-04 23:05:10 +0000148
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 if (op && PyInt_Check(op))
150 return PyInt_AS_LONG((PyIntObject*) op);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000151
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
153 nb->nb_int == NULL) {
154 PyErr_SetString(PyExc_TypeError, "an integer is required");
155 return -1;
156 }
Tim Petersa3c01ce2001-12-04 23:05:10 +0000157
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000158 io = (PyIntObject*) (*nb->nb_int) (op);
159 if (io == NULL)
160 return -1;
161 if (!PyInt_Check(io)) {
162 if (PyLong_Check(io)) {
163 /* got a long? => retry int conversion */
164 val = PyLong_AsLong((PyObject *)io);
165 Py_DECREF(io);
166 if ((val == -1) && PyErr_Occurred())
167 return -1;
168 return val;
169 }
170 else
171 {
172 Py_DECREF(io);
173 PyErr_SetString(PyExc_TypeError,
174 "__int__ method should return an integer");
175 return -1;
176 }
177 }
Tim Petersa3c01ce2001-12-04 23:05:10 +0000178
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 val = PyInt_AS_LONG(io);
180 Py_DECREF(io);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000181
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000182 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +0200185int
186_PyInt_AsInt(PyObject *obj)
187{
188 long result = PyInt_AsLong(obj);
189 if (result == -1 && PyErr_Occurred())
190 return -1;
191 if (result > INT_MAX || result < INT_MIN) {
192 PyErr_SetString(PyExc_OverflowError,
193 "Python int too large to convert to C int");
194 return -1;
195 }
196 return (int)result;
197}
198
Martin v. Löwis18e16552006-02-15 17:27:45 +0000199Py_ssize_t
200PyInt_AsSsize_t(register PyObject *op)
201{
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000202#if SIZEOF_SIZE_T != SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 PyNumberMethods *nb;
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600204 PyObject *io;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 Py_ssize_t val;
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000206#endif
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000207
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000208 if (op == NULL) {
209 PyErr_SetString(PyExc_TypeError, "an integer is required");
210 return -1;
211 }
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000212
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000213 if (PyInt_Check(op))
214 return PyInt_AS_LONG((PyIntObject*) op);
215 if (PyLong_Check(op))
216 return _PyLong_AsSsize_t(op);
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000217#if SIZEOF_SIZE_T == SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000218 return PyInt_AsLong(op);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000219#else
220
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000221 if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
222 (nb->nb_int == NULL && nb->nb_long == 0)) {
223 PyErr_SetString(PyExc_TypeError, "an integer is required");
224 return -1;
225 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 if (nb->nb_long != 0)
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600228 io = (*nb->nb_long)(op);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 else
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600230 io = (*nb->nb_int)(op);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000231 if (io == NULL)
232 return -1;
233 if (!PyInt_Check(io)) {
234 if (PyLong_Check(io)) {
235 /* got a long? => retry int conversion */
Benjamin Petersonc6b6ab02014-11-23 12:58:54 -0600236 val = _PyLong_AsSsize_t(io);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000237 Py_DECREF(io);
238 if ((val == -1) && PyErr_Occurred())
239 return -1;
240 return val;
241 }
242 else
243 {
244 Py_DECREF(io);
245 PyErr_SetString(PyExc_TypeError,
246 "__int__ method should return an integer");
247 return -1;
248 }
249 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 val = PyInt_AS_LONG(io);
252 Py_DECREF(io);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 return val;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000255#endif
256}
257
Thomas Hellera4ea6032003-04-17 18:55:45 +0000258unsigned long
259PyInt_AsUnsignedLongMask(register PyObject *op)
260{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 PyNumberMethods *nb;
262 PyIntObject *io;
263 unsigned long val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 if (op && PyInt_Check(op))
266 return PyInt_AS_LONG((PyIntObject*) op);
267 if (op && PyLong_Check(op))
268 return PyLong_AsUnsignedLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
271 nb->nb_int == NULL) {
272 PyErr_SetString(PyExc_TypeError, "an integer is required");
273 return (unsigned long)-1;
274 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000275
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 io = (PyIntObject*) (*nb->nb_int) (op);
277 if (io == NULL)
278 return (unsigned long)-1;
279 if (!PyInt_Check(io)) {
280 if (PyLong_Check(io)) {
281 val = PyLong_AsUnsignedLongMask((PyObject *)io);
282 Py_DECREF(io);
283 if (PyErr_Occurred())
284 return (unsigned long)-1;
285 return val;
286 }
287 else
288 {
289 Py_DECREF(io);
290 PyErr_SetString(PyExc_TypeError,
291 "__int__ method should return an integer");
292 return (unsigned long)-1;
293 }
294 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000295
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 val = PyInt_AS_LONG(io);
297 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000298
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000300}
301
302#ifdef HAVE_LONG_LONG
303unsigned PY_LONG_LONG
304PyInt_AsUnsignedLongLongMask(register PyObject *op)
305{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 PyNumberMethods *nb;
307 PyIntObject *io;
308 unsigned PY_LONG_LONG val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000309
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000310 if (op && PyInt_Check(op))
311 return PyInt_AS_LONG((PyIntObject*) op);
312 if (op && PyLong_Check(op))
313 return PyLong_AsUnsignedLongLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000314
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
316 nb->nb_int == NULL) {
317 PyErr_SetString(PyExc_TypeError, "an integer is required");
318 return (unsigned PY_LONG_LONG)-1;
319 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000320
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000321 io = (PyIntObject*) (*nb->nb_int) (op);
322 if (io == NULL)
323 return (unsigned PY_LONG_LONG)-1;
324 if (!PyInt_Check(io)) {
325 if (PyLong_Check(io)) {
326 val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
327 Py_DECREF(io);
328 if (PyErr_Occurred())
329 return (unsigned PY_LONG_LONG)-1;
330 return val;
331 }
332 else
333 {
334 Py_DECREF(io);
335 PyErr_SetString(PyExc_TypeError,
336 "__int__ method should return an integer");
337 return (unsigned PY_LONG_LONG)-1;
338 }
339 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000340
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 val = PyInt_AS_LONG(io);
342 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000343
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000344 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000345}
346#endif
347
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000348PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000349PyInt_FromString(char *s, char **pend, int base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000350{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 char *end;
352 long x;
353 Py_ssize_t slen;
354 PyObject *sobj, *srepr;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000355
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000356 if ((base != 0 && base < 2) || base > 36) {
357 PyErr_SetString(PyExc_ValueError,
358 "int() base must be >= 2 and <= 36");
359 return NULL;
360 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000361
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 while (*s && isspace(Py_CHARMASK(*s)))
363 s++;
364 errno = 0;
365 if (base == 0 && s[0] == '0') {
366 x = (long) PyOS_strtoul(s, &end, base);
367 if (x < 0)
368 return PyLong_FromString(s, pend, base);
369 }
370 else
371 x = PyOS_strtol(s, &end, base);
372 if (end == s || !isalnum(Py_CHARMASK(end[-1])))
373 goto bad;
374 while (*end && isspace(Py_CHARMASK(*end)))
375 end++;
376 if (*end != '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000377 bad:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 slen = strlen(s) < 200 ? strlen(s) : 200;
379 sobj = PyString_FromStringAndSize(s, slen);
380 if (sobj == NULL)
381 return NULL;
382 srepr = PyObject_Repr(sobj);
383 Py_DECREF(sobj);
384 if (srepr == NULL)
385 return NULL;
386 PyErr_Format(PyExc_ValueError,
387 "invalid literal for int() with base %d: %s",
388 base, PyString_AS_STRING(srepr));
389 Py_DECREF(srepr);
390 return NULL;
391 }
392 else if (errno != 0)
393 return PyLong_FromString(s, pend, base);
394 if (pend)
395 *pend = end;
396 return PyInt_FromLong(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000397}
398
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000399#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000400PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000401PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +0000402{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000403 PyObject *result;
404 char *buffer = (char *)PyMem_MALLOC(length+1);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000405
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 if (buffer == NULL)
407 return PyErr_NoMemory();
Walter Dörwald07e14762002-11-06 16:15:14 +0000408
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
410 PyMem_FREE(buffer);
411 return NULL;
412 }
413 result = PyInt_FromString(buffer, NULL, base);
414 PyMem_FREE(buffer);
415 return result;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000416}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000417#endif
Guido van Rossum9e896b32000-04-05 20:11:21 +0000418
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419/* Methods */
420
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000421/* Integers are seen as the "smallest" of all numeric types and thus
422 don't have any knowledge about conversion of other types to
423 integers. */
424
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425#define CONVERT_TO_LONG(obj, lng) \
426 if (PyInt_Check(obj)) { \
427 lng = PyInt_AS_LONG(obj); \
428 } \
429 else { \
430 Py_INCREF(Py_NotImplemented); \
431 return Py_NotImplemented; \
432 }
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000433
Guido van Rossum719f5fa1992-03-27 17:31:02 +0000434/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000435static int
Fred Drakea2f55112000-07-09 15:16:51 +0000436int_print(PyIntObject *v, FILE *fp, int flags)
437 /* flags -- not used but required by interface */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000439 long int_val = v->ob_ival;
440 Py_BEGIN_ALLOW_THREADS
441 fprintf(fp, "%ld", int_val);
442 Py_END_ALLOW_THREADS
443 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444}
445
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446static int
Fred Drakea2f55112000-07-09 15:16:51 +0000447int_compare(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000449 register long i = v->ob_ival;
450 register long j = w->ob_ival;
451 return (i < j) ? -1 : (i > j) ? 1 : 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452}
453
Guido van Rossum9bfef441993-03-29 10:43:31 +0000454static long
Fred Drakea2f55112000-07-09 15:16:51 +0000455int_hash(PyIntObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000456{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000457 /* XXX If this is changed, you also need to change the way
458 Python's long, float and complex types are hashed. */
459 long x = v -> ob_ival;
460 if (x == -1)
461 x = -2;
462 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000463}
464
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000466int_add(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000467{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 register long a, b, x;
469 CONVERT_TO_LONG(v, a);
470 CONVERT_TO_LONG(w, b);
471 /* casts in the line below avoid undefined behaviour on overflow */
472 x = (long)((unsigned long)a + b);
473 if ((x^a) >= 0 || (x^b) >= 0)
474 return PyInt_FromLong(x);
475 return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476}
477
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000479int_sub(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000481 register long a, b, x;
482 CONVERT_TO_LONG(v, a);
483 CONVERT_TO_LONG(w, b);
484 /* casts in the line below avoid undefined behaviour on overflow */
485 x = (long)((unsigned long)a - b);
486 if ((x^a) >= 0 || (x^~b) >= 0)
487 return PyInt_FromLong(x);
488 return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
489 (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000490}
491
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000492/*
Tim Petersa3c01ce2001-12-04 23:05:10 +0000493Integer overflow checking for * is painful: Python tried a couple ways, but
494they didn't work on all platforms, or failed in endcases (a product of
495-sys.maxint-1 has been a particular pain).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000496
Tim Petersa3c01ce2001-12-04 23:05:10 +0000497Here's another way:
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000498
Tim Petersa3c01ce2001-12-04 23:05:10 +0000499The native long product x*y is either exactly right or *way* off, being
500just the last n bits of the true product, where n is the number of bits
501in a long (the delivered product is the true product plus i*2**n for
502some integer i).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000503
Tim Petersa3c01ce2001-12-04 23:05:10 +0000504The native double product (double)x * (double)y is subject to three
505rounding errors: on a sizeof(long)==8 box, each cast to double can lose
506info, and even on a sizeof(long)==4 box, the multiplication can lose info.
507But, unlike the native long product, it's not in *range* trouble: even
508if sizeof(long)==32 (256-bit longs), the product easily fits in the
509dynamic range of a double. So the leading 50 (or so) bits of the double
510product are correct.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000511
Tim Petersa3c01ce2001-12-04 23:05:10 +0000512We check these two ways against each other, and declare victory if they're
513approximately the same. Else, because the native long product is the only
514one that can lose catastrophic amounts of information, it's the native long
515product that must have overflowed.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000516*/
517
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518static PyObject *
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000519int_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000520{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000521 long a, b;
522 long longprod; /* a*b in native long arithmetic */
523 double doubled_longprod; /* (double)longprod */
524 double doubleprod; /* (double)a * (double)b */
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000525
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 CONVERT_TO_LONG(v, a);
527 CONVERT_TO_LONG(w, b);
528 /* casts in the next line avoid undefined behaviour on overflow */
529 longprod = (long)((unsigned long)a * b);
530 doubleprod = (double)a * (double)b;
531 doubled_longprod = (double)longprod;
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 /* Fast path for normal case: small multiplicands, and no info
534 is lost in either method. */
535 if (doubled_longprod == doubleprod)
536 return PyInt_FromLong(longprod);
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000537
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000538 /* Somebody somewhere lost info. Close enough, or way off? Note
539 that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
540 The difference either is or isn't significant compared to the
541 true value (of which doubleprod is a good approximation).
542 */
543 {
544 const double diff = doubled_longprod - doubleprod;
545 const double absdiff = diff >= 0.0 ? diff : -diff;
546 const double absprod = doubleprod >= 0.0 ? doubleprod :
547 -doubleprod;
548 /* absdiff/absprod <= 1/32 iff
549 32 * absdiff <= absprod -- 5 good bits is "close enough" */
550 if (32.0 * absdiff <= absprod)
551 return PyInt_FromLong(longprod);
552 else
553 return PyLong_Type.tp_as_number->nb_multiply(v, w);
554 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000555}
556
Armin Rigo7ccbca92006-10-04 12:17:45 +0000557/* Integer overflow checking for unary negation: on a 2's-complement
558 * box, -x overflows iff x is the most negative long. In this case we
559 * get -x == x. However, -x is undefined (by C) if x /is/ the most
560 * negative long (it's a signed overflow case), and some compilers care.
561 * So we cast x to unsigned long first. However, then other compilers
562 * warn about applying unary minus to an unsigned operand. Hence the
563 * weird "0-".
564 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565#define UNARY_NEG_WOULD_OVERFLOW(x) \
566 ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
Armin Rigo7ccbca92006-10-04 12:17:45 +0000567
Guido van Rossume27f7952001-08-23 02:59:04 +0000568/* Return type of i_divmod */
569enum divmod_result {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 DIVMOD_OK, /* Correct result */
571 DIVMOD_OVERFLOW, /* Overflow, try again using longs */
572 DIVMOD_ERROR /* Exception raised */
Guido van Rossume27f7952001-08-23 02:59:04 +0000573};
574
575static enum divmod_result
Tim Peters1dad6a82001-06-18 19:21:11 +0000576i_divmod(register long x, register long y,
Fred Drakea2f55112000-07-09 15:16:51 +0000577 long *p_xdivy, long *p_xmody)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 long xdivy, xmody;
Tim Petersa3c01ce2001-12-04 23:05:10 +0000580
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000581 if (y == 0) {
582 PyErr_SetString(PyExc_ZeroDivisionError,
583 "integer division or modulo by zero");
584 return DIVMOD_ERROR;
585 }
586 /* (-sys.maxint-1)/-1 is the only overflow case. */
587 if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
588 return DIVMOD_OVERFLOW;
589 xdivy = x / y;
590 /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
591 * for x and y with differing signs. (This is unusual
592 * behaviour, and C99 prohibits it, but it's allowed by C89;
593 * for an example of overflow, take x = LONG_MIN, y = 5 or x =
594 * LONG_MAX, y = -5.) However, x - xdivy*y is always
595 * representable as a long, since it lies strictly between
596 * -abs(y) and abs(y). We add casts to avoid intermediate
597 * overflow.
598 */
599 xmody = (long)(x - (unsigned long)xdivy * y);
600 /* If the signs of x and y differ, and the remainder is non-0,
601 * C89 doesn't define whether xdivy is now the floor or the
602 * ceiling of the infinitely precise quotient. We want the floor,
603 * and we have it iff the remainder's sign matches y's.
604 */
605 if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
606 xmody += y;
607 --xdivy;
608 assert(xmody && ((y ^ xmody) >= 0));
609 }
610 *p_xdivy = xdivy;
611 *p_xmody = xmody;
612 return DIVMOD_OK;
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000613}
614
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000616int_div(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000617{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 long xi, yi;
619 long d, m;
620 CONVERT_TO_LONG(x, xi);
621 CONVERT_TO_LONG(y, yi);
622 switch (i_divmod(xi, yi, &d, &m)) {
623 case DIVMOD_OK:
624 return PyInt_FromLong(d);
625 case DIVMOD_OVERFLOW:
626 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
627 (PyObject *)y);
628 default:
629 return NULL;
630 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000631}
632
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000634int_classic_div(PyIntObject *x, PyIntObject *y)
635{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 long xi, yi;
637 long d, m;
638 CONVERT_TO_LONG(x, xi);
639 CONVERT_TO_LONG(y, yi);
640 if (Py_DivisionWarningFlag &&
641 PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
642 return NULL;
643 switch (i_divmod(xi, yi, &d, &m)) {
644 case DIVMOD_OK:
645 return PyInt_FromLong(d);
646 case DIVMOD_OVERFLOW:
647 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
648 (PyObject *)y);
649 default:
650 return NULL;
651 }
Guido van Rossum393661d2001-08-31 17:40:15 +0000652}
653
654static PyObject *
Mark Dickinson46572832009-12-27 14:55:57 +0000655int_true_divide(PyIntObject *x, PyIntObject *y)
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000656{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 long xi, yi;
658 /* If they aren't both ints, give someone else a chance. In
659 particular, this lets int/long get handled by longs, which
660 underflows to 0 gracefully if the long is too big to convert
661 to float. */
662 CONVERT_TO_LONG(x, xi);
663 CONVERT_TO_LONG(y, yi);
664 if (yi == 0) {
665 PyErr_SetString(PyExc_ZeroDivisionError,
666 "division by zero");
667 return NULL;
668 }
669 if (xi == 0)
670 return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
Mark Dickinson46572832009-12-27 14:55:57 +0000671
672#define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG)
673#if DBL_MANT_DIG < WIDTH_OF_ULONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
675 (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
676 /* Large x or y. Use long integer arithmetic. */
677 return PyLong_Type.tp_as_number->nb_true_divide(
678 (PyObject *)x, (PyObject *)y);
679 else
Mark Dickinson46572832009-12-27 14:55:57 +0000680#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 /* Both ints can be exactly represented as doubles. Do a
682 floating-point division. */
683 return PyFloat_FromDouble((double)xi / (double)yi);
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000684}
685
686static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000687int_mod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000688{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000689 long xi, yi;
690 long d, m;
691 CONVERT_TO_LONG(x, xi);
692 CONVERT_TO_LONG(y, yi);
693 switch (i_divmod(xi, yi, &d, &m)) {
694 case DIVMOD_OK:
695 return PyInt_FromLong(m);
696 case DIVMOD_OVERFLOW:
697 return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
698 (PyObject *)y);
699 default:
700 return NULL;
701 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000702}
703
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000705int_divmod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000706{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 long xi, yi;
708 long d, m;
709 CONVERT_TO_LONG(x, xi);
710 CONVERT_TO_LONG(y, yi);
711 switch (i_divmod(xi, yi, &d, &m)) {
712 case DIVMOD_OK:
713 return Py_BuildValue("(ll)", d, m);
714 case DIVMOD_OVERFLOW:
715 return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
716 (PyObject *)y);
717 default:
718 return NULL;
719 }
Guido van Rossum00466951991-05-05 20:08:27 +0000720}
721
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000722static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000723int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000724{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 register long iv, iw, iz=0, ix, temp, prev;
726 CONVERT_TO_LONG(v, iv);
727 CONVERT_TO_LONG(w, iw);
728 if (iw < 0) {
729 if ((PyObject *)z != Py_None) {
730 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
731 "cannot be negative when 3rd argument specified");
732 return NULL;
733 }
734 /* Return a float. This works because we know that
735 this calls float_pow() which converts its
736 arguments to double. */
737 return PyFloat_Type.tp_as_number->nb_power(
738 (PyObject *)v, (PyObject *)w, (PyObject *)z);
739 }
740 if ((PyObject *)z != Py_None) {
741 CONVERT_TO_LONG(z, iz);
742 if (iz == 0) {
743 PyErr_SetString(PyExc_ValueError,
744 "pow() 3rd argument cannot be 0");
745 return NULL;
746 }
747 }
748 /*
749 * XXX: The original exponentiation code stopped looping
750 * when temp hit zero; this code will continue onwards
751 * unnecessarily, but at least it won't cause any errors.
752 * Hopefully the speed improvement from the fast exponentiation
753 * will compensate for the slight inefficiency.
754 * XXX: Better handling of overflows is desperately needed.
755 */
756 temp = iv;
757 ix = 1;
758 while (iw > 0) {
759 prev = ix; /* Save value for overflow check */
760 if (iw & 1) {
Mark Dickinsondbbed042011-09-19 16:38:08 +0100761 /*
762 * The (unsigned long) cast below ensures that the multiplication
763 * is interpreted as an unsigned operation rather than a signed one
764 * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour
765 * from signed arithmetic overflow (C99 6.5p5). See issue #12973.
766 */
767 ix = (unsigned long)ix * temp;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000768 if (temp == 0)
769 break; /* Avoid ix / 0 */
770 if (ix / temp != prev) {
771 return PyLong_Type.tp_as_number->nb_power(
772 (PyObject *)v,
773 (PyObject *)w,
774 (PyObject *)z);
775 }
776 }
777 iw >>= 1; /* Shift exponent down by 1 bit */
778 if (iw==0) break;
779 prev = temp;
Mark Dickinsondbbed042011-09-19 16:38:08 +0100780 temp = (unsigned long)temp * temp; /* Square the value of temp */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781 if (prev != 0 && temp / prev != prev) {
782 return PyLong_Type.tp_as_number->nb_power(
783 (PyObject *)v, (PyObject *)w, (PyObject *)z);
784 }
785 if (iz) {
786 /* If we did a multiplication, perform a modulo */
787 ix = ix % iz;
788 temp = temp % iz;
789 }
790 }
791 if (iz) {
792 long div, mod;
793 switch (i_divmod(ix, iz, &div, &mod)) {
794 case DIVMOD_OK:
795 ix = mod;
796 break;
797 case DIVMOD_OVERFLOW:
798 return PyLong_Type.tp_as_number->nb_power(
799 (PyObject *)v, (PyObject *)w, (PyObject *)z);
800 default:
801 return NULL;
802 }
803 }
804 return PyInt_FromLong(ix);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000805}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000808int_neg(PyIntObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000810 register long a;
811 a = v->ob_ival;
812 /* check for overflow */
813 if (UNARY_NEG_WOULD_OVERFLOW(a)) {
814 PyObject *o = PyLong_FromLong(a);
815 if (o != NULL) {
816 PyObject *result = PyNumber_Negative(o);
817 Py_DECREF(o);
818 return result;
819 }
820 return NULL;
821 }
822 return PyInt_FromLong(-a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823}
824
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000825static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000826int_abs(PyIntObject *v)
Guido van Rossum00466951991-05-05 20:08:27 +0000827{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 if (v->ob_ival >= 0)
829 return int_int(v);
830 else
831 return int_neg(v);
Guido van Rossum00466951991-05-05 20:08:27 +0000832}
833
Guido van Rossum0bff0151991-05-14 12:05:32 +0000834static int
Fred Drakea2f55112000-07-09 15:16:51 +0000835int_nonzero(PyIntObject *v)
Guido van Rossum0bff0151991-05-14 12:05:32 +0000836{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000837 return v->ob_ival != 0;
Guido van Rossum0bff0151991-05-14 12:05:32 +0000838}
839
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000841int_invert(PyIntObject *v)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000842{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000843 return PyInt_FromLong(~v->ob_ival);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000844}
845
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000846static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000847int_lshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000848{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 long a, b, c;
850 PyObject *vv, *ww, *result;
Raymond Hettingera006c372004-06-26 23:22:57 +0000851
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000852 CONVERT_TO_LONG(v, a);
853 CONVERT_TO_LONG(w, b);
854 if (b < 0) {
855 PyErr_SetString(PyExc_ValueError, "negative shift count");
856 return NULL;
857 }
858 if (a == 0 || b == 0)
859 return int_int(v);
860 if (b >= LONG_BIT) {
861 vv = PyLong_FromLong(PyInt_AS_LONG(v));
862 if (vv == NULL)
863 return NULL;
864 ww = PyLong_FromLong(PyInt_AS_LONG(w));
865 if (ww == NULL) {
866 Py_DECREF(vv);
867 return NULL;
868 }
869 result = PyNumber_Lshift(vv, ww);
870 Py_DECREF(vv);
871 Py_DECREF(ww);
872 return result;
873 }
874 c = a << b;
875 if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
876 vv = PyLong_FromLong(PyInt_AS_LONG(v));
877 if (vv == NULL)
878 return NULL;
879 ww = PyLong_FromLong(PyInt_AS_LONG(w));
880 if (ww == NULL) {
881 Py_DECREF(vv);
882 return NULL;
883 }
884 result = PyNumber_Lshift(vv, ww);
885 Py_DECREF(vv);
886 Py_DECREF(ww);
887 return result;
888 }
889 return PyInt_FromLong(c);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000890}
891
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000892static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000893int_rshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000894{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 register long a, b;
896 CONVERT_TO_LONG(v, a);
897 CONVERT_TO_LONG(w, b);
898 if (b < 0) {
899 PyErr_SetString(PyExc_ValueError, "negative shift count");
900 return NULL;
901 }
902 if (a == 0 || b == 0)
903 return int_int(v);
904 if (b >= LONG_BIT) {
905 if (a < 0)
906 a = -1;
907 else
908 a = 0;
909 }
910 else {
911 a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
912 }
913 return PyInt_FromLong(a);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000914}
915
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000916static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000917int_and(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 register long a, b;
920 CONVERT_TO_LONG(v, a);
921 CONVERT_TO_LONG(w, b);
922 return PyInt_FromLong(a & b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000923}
924
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000926int_xor(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000927{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 register long a, b;
929 CONVERT_TO_LONG(v, a);
930 CONVERT_TO_LONG(w, b);
931 return PyInt_FromLong(a ^ b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000932}
933
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000934static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000935int_or(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 register long a, b;
938 CONVERT_TO_LONG(v, a);
939 CONVERT_TO_LONG(w, b);
940 return PyInt_FromLong(a | b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000941}
942
Guido van Rossum1952e382001-09-19 01:25:16 +0000943static int
944int_coerce(PyObject **pv, PyObject **pw)
945{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 if (PyInt_Check(*pw)) {
947 Py_INCREF(*pv);
948 Py_INCREF(*pw);
949 return 0;
950 }
951 return 1; /* Can't do it */
Guido van Rossum1952e382001-09-19 01:25:16 +0000952}
953
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000955int_int(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000956{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 if (PyInt_CheckExact(v))
958 Py_INCREF(v);
959 else
960 v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
961 return (PyObject *)v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000962}
963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000965int_long(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 return PyLong_FromLong((v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000968}
969
Mark Dickinson6736cf82009-04-20 21:13:33 +0000970static const unsigned char BitLengthTable[32] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000971 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
972 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson6736cf82009-04-20 21:13:33 +0000973};
974
975static int
976bits_in_ulong(unsigned long d)
977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000978 int d_bits = 0;
979 while (d >= 32) {
980 d_bits += 6;
981 d >>= 6;
982 }
983 d_bits += (int)BitLengthTable[d];
984 return d_bits;
Mark Dickinson6736cf82009-04-20 21:13:33 +0000985}
986
987#if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG
988/* Every Python int can be exactly represented as a float. */
989
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000990static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000991int_float(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 return PyFloat_FromDouble((double)(v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000994}
995
Mark Dickinson6736cf82009-04-20 21:13:33 +0000996#else
997/* Here not all Python ints are exactly representable as floats, so we may
998 have to round. We do this manually, since the C standards don't specify
999 whether converting an integer to a float rounds up or down */
1000
1001static PyObject *
1002int_float(PyIntObject *v)
1003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 unsigned long abs_ival, lsb;
1005 int round_up;
Mark Dickinson6736cf82009-04-20 21:13:33 +00001006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001007 if (v->ob_ival < 0)
1008 abs_ival = 0U-(unsigned long)v->ob_ival;
1009 else
1010 abs_ival = (unsigned long)v->ob_ival;
1011 if (abs_ival < (1L << DBL_MANT_DIG))
1012 /* small integer; no need to round */
1013 return PyFloat_FromDouble((double)v->ob_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 /* Round abs_ival to MANT_DIG significant bits, using the
1016 round-half-to-even rule. abs_ival & lsb picks out the 'rounding'
1017 bit: the first bit after the most significant MANT_DIG bits of
1018 abs_ival. We round up if this bit is set, provided that either:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001019
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 (1) abs_ival isn't exactly halfway between two floats, in which
1021 case at least one of the bits following the rounding bit must be
1022 set; i.e., abs_ival & lsb-1 != 0, or:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001023
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 (2) the resulting rounded value has least significant bit 0; or
1025 in other words the bit above the rounding bit is set (this is the
1026 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
Mark Dickinson6736cf82009-04-20 21:13:33 +00001027
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
Mark Dickinson6736cf82009-04-20 21:13:33 +00001029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
1031 round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
1032 abs_ival &= -2*lsb;
1033 if (round_up)
1034 abs_ival += 2*lsb;
1035 return PyFloat_FromDouble(v->ob_ival < 0 ?
1036 -(double)abs_ival :
1037 (double)abs_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001038}
1039
1040#endif
1041
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001042static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001043int_oct(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001044{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001045 return _PyInt_Format(v, 8, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001046}
1047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001048static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001049int_hex(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001050{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 return _PyInt_Format(v, 16, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001052}
1053
Jeremy Hylton938ace62002-07-17 16:30:39 +00001054static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001055int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1056
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057static PyObject *
1058int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1059{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 PyObject *x = NULL;
1061 int base = -909;
1062 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 if (type != &PyInt_Type)
1065 return int_subtype_new(type, args, kwds); /* Wimp out */
1066 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
1067 &x, &base))
1068 return NULL;
Serhiy Storchakacf095f82012-12-28 09:31:59 +02001069 if (x == NULL) {
1070 if (base != -909) {
1071 PyErr_SetString(PyExc_TypeError,
1072 "int() missing string argument");
1073 return NULL;
1074 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001075 return PyInt_FromLong(0L);
Serhiy Storchakacf095f82012-12-28 09:31:59 +02001076 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 if (base == -909)
1078 return PyNumber_Int(x);
1079 if (PyString_Check(x)) {
1080 /* Since PyInt_FromString doesn't have a length parameter,
1081 * check here for possible NULs in the string. */
1082 char *string = PyString_AS_STRING(x);
1083 if (strlen(string) != PyString_Size(x)) {
1084 /* create a repr() of the input string,
1085 * just like PyInt_FromString does */
1086 PyObject *srepr;
1087 srepr = PyObject_Repr(x);
1088 if (srepr == NULL)
1089 return NULL;
1090 PyErr_Format(PyExc_ValueError,
1091 "invalid literal for int() with base %d: %s",
1092 base, PyString_AS_STRING(srepr));
1093 Py_DECREF(srepr);
1094 return NULL;
1095 }
1096 return PyInt_FromString(string, NULL, base);
1097 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001098#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 if (PyUnicode_Check(x))
1100 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
1101 PyUnicode_GET_SIZE(x),
1102 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001103#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001104 PyErr_SetString(PyExc_TypeError,
1105 "int() can't convert non-string with explicit base");
1106 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107}
1108
Guido van Rossumbef14172001-08-29 15:47:46 +00001109/* Wimpy, slow approach to tp_new calls for subtypes of int:
1110 first create a regular int from whatever arguments we got,
1111 then allocate a subtype instance and initialize its ob_ival
1112 from the regular int. The regular int is then thrown away.
1113*/
1114static PyObject *
1115int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1116{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 PyObject *tmp, *newobj;
1118 long ival;
Guido van Rossumbef14172001-08-29 15:47:46 +00001119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 assert(PyType_IsSubtype(type, &PyInt_Type));
1121 tmp = int_new(&PyInt_Type, args, kwds);
1122 if (tmp == NULL)
1123 return NULL;
1124 if (!PyInt_Check(tmp)) {
1125 ival = PyLong_AsLong(tmp);
1126 if (ival == -1 && PyErr_Occurred()) {
1127 Py_DECREF(tmp);
1128 return NULL;
1129 }
1130 } else {
1131 ival = ((PyIntObject *)tmp)->ob_ival;
1132 }
Neal Norwitzde8b94c2003-02-10 02:12:43 +00001133
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001134 newobj = type->tp_alloc(type, 0);
1135 if (newobj == NULL) {
1136 Py_DECREF(tmp);
1137 return NULL;
1138 }
1139 ((PyIntObject *)newobj)->ob_ival = ival;
1140 Py_DECREF(tmp);
1141 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001142}
1143
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001144static PyObject *
1145int_getnewargs(PyIntObject *v)
1146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 return Py_BuildValue("(l)", v->ob_ival);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001148}
1149
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001150static PyObject *
Mark Dickinson85e269b2009-05-03 20:39:06 +00001151int_get0(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001152 return PyInt_FromLong(0L);
Mark Dickinson85e269b2009-05-03 20:39:06 +00001153}
1154
1155static PyObject *
1156int_get1(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001157 return PyInt_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001158}
1159
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001160/* Convert an integer to a decimal string. On many platforms, this
1161 will be significantly faster than the general arbitrary-base
1162 conversion machinery in _PyInt_Format, thanks to optimization
1163 opportunities offered by division by a compile-time constant. */
1164static PyObject *
1165int_to_decimal_string(PyIntObject *v) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
1167 long n = v->ob_ival;
1168 unsigned long absn;
1169 p = bufend = buf + sizeof(buf);
1170 absn = n < 0 ? 0UL - n : n;
1171 do {
1172 *--p = '0' + (char)(absn % 10);
1173 absn /= 10;
1174 } while (absn);
1175 if (n < 0)
1176 *--p = '-';
1177 return PyString_FromStringAndSize(p, bufend - p);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001178}
1179
Eric Smith5e527eb2008-02-10 01:36:53 +00001180/* Convert an integer to the given base. Returns a string.
1181 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
1182 If newstyle is zero, then use the pre-2.6 behavior of octal having
1183 a leading "0" */
1184PyAPI_FUNC(PyObject*)
1185_PyInt_Format(PyIntObject *v, int base, int newstyle)
1186{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001187 /* There are no doubt many, many ways to optimize this, using code
1188 similar to _PyLong_Format */
1189 long n = v->ob_ival;
1190 int negative = n < 0;
1191 int is_zero = n == 0;
Eric Smith5e527eb2008-02-10 01:36:53 +00001192
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 /* For the reasoning behind this size, see
1194 http://c-faq.com/misc/hexio.html. Then, add a few bytes for
1195 the possible sign and prefix "0[box]" */
1196 char buf[sizeof(n)*CHAR_BIT+6];
Eric Smith5e527eb2008-02-10 01:36:53 +00001197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 /* Start by pointing to the end of the buffer. We fill in from
1199 the back forward. */
1200 char* p = &buf[sizeof(buf)];
Eric Smith5e527eb2008-02-10 01:36:53 +00001201
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001202 assert(base >= 2 && base <= 36);
Eric Smith5e527eb2008-02-10 01:36:53 +00001203
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001204 /* Special case base 10, for speed */
1205 if (base == 10)
1206 return int_to_decimal_string(v);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001207
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001208 do {
1209 /* I'd use i_divmod, except it doesn't produce the results
1210 I want when n is negative. So just duplicate the salient
1211 part here. */
1212 long div = n / base;
1213 long mod = n - div * base;
Eric Smith5e527eb2008-02-10 01:36:53 +00001214
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001215 /* convert abs(mod) to the right character in [0-9, a-z] */
1216 char cdigit = (char)(mod < 0 ? -mod : mod);
1217 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1218 *--p = cdigit;
Eric Smith5e527eb2008-02-10 01:36:53 +00001219
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001220 n = div;
1221 } while(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001222
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 if (base == 2) {
1224 *--p = 'b';
1225 *--p = '0';
1226 }
1227 else if (base == 8) {
1228 if (newstyle) {
1229 *--p = 'o';
1230 *--p = '0';
1231 }
1232 else
1233 if (!is_zero)
1234 *--p = '0';
1235 }
1236 else if (base == 16) {
1237 *--p = 'x';
1238 *--p = '0';
1239 }
1240 else {
1241 *--p = '#';
1242 *--p = '0' + base%10;
1243 if (base > 10)
1244 *--p = '0' + base/10;
1245 }
1246 if (negative)
1247 *--p = '-';
Eric Smith5e527eb2008-02-10 01:36:53 +00001248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001249 return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
Eric Smith5e527eb2008-02-10 01:36:53 +00001250}
1251
Eric Smitha9f7d622008-02-17 19:46:49 +00001252static PyObject *
1253int__format__(PyObject *self, PyObject *args)
1254{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001255 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001256
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001257 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1258 return NULL;
1259 if (PyBytes_Check(format_spec))
1260 return _PyInt_FormatAdvanced(self,
1261 PyBytes_AS_STRING(format_spec),
1262 PyBytes_GET_SIZE(format_spec));
1263 if (PyUnicode_Check(format_spec)) {
1264 /* Convert format_spec to a str */
1265 PyObject *result;
1266 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 if (str_spec == NULL)
1269 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001270
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001271 result = _PyInt_FormatAdvanced(self,
1272 PyBytes_AS_STRING(str_spec),
1273 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001274
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 Py_DECREF(str_spec);
1276 return result;
1277 }
1278 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1279 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001280}
1281
Mark Dickinson1a707982008-12-17 16:14:37 +00001282static PyObject *
1283int_bit_length(PyIntObject *v)
1284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 unsigned long n;
Mark Dickinson1a707982008-12-17 16:14:37 +00001286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001287 if (v->ob_ival < 0)
1288 /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
1289 n = 0U-(unsigned long)v->ob_ival;
1290 else
1291 n = (unsigned long)v->ob_ival;
Mark Dickinson1a707982008-12-17 16:14:37 +00001292
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001293 return PyInt_FromLong(bits_in_ulong(n));
Mark Dickinson1a707982008-12-17 16:14:37 +00001294}
1295
1296PyDoc_STRVAR(int_bit_length_doc,
1297"int.bit_length() -> int\n\
1298\n\
1299Number of bits necessary to represent self in binary.\n\
1300>>> bin(37)\n\
1301'0b100101'\n\
1302>>> (37).bit_length()\n\
13036");
1304
Christian Heimes6f341092008-04-18 23:13:07 +00001305#if 0
1306static PyObject *
1307int_is_finite(PyObject *v)
1308{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001309 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00001310}
1311#endif
1312
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001313static PyMethodDef int_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001314 {"conjugate", (PyCFunction)int_int, METH_NOARGS,
1315 "Returns self, the complex conjugate of any int."},
1316 {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
1317 int_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001318#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001319 {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
1320 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00001321#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001322 {"__trunc__", (PyCFunction)int_int, METH_NOARGS,
1323 "Truncating an Integral returns itself."},
1324 {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
1325 {"__format__", (PyCFunction)int__format__, METH_VARARGS},
1326 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001327};
1328
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001329static PyGetSetDef int_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 {"real",
1331 (getter)int_int, (setter)NULL,
1332 "the real part of a complex number",
1333 NULL},
1334 {"imag",
1335 (getter)int_get0, (setter)NULL,
1336 "the imaginary part of a complex number",
1337 NULL},
1338 {"numerator",
1339 (getter)int_int, (setter)NULL,
1340 "the numerator of a rational number in lowest terms",
1341 NULL},
1342 {"denominator",
1343 (getter)int_get1, (setter)NULL,
1344 "the denominator of a rational number in lowest terms",
1345 NULL},
1346 {NULL} /* Sentinel */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001347};
1348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001349PyDoc_STRVAR(int_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -07001350"int(x=0) -> int or long\n\
1351int(x, base=10) -> int or long\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352\n\
Chris Jerdonekad4b0002012-10-07 20:37:54 -07001353Convert a number or string to an integer, or return 0 if no arguments\n\
1354are given. If x is floating point, the conversion truncates towards zero.\n\
1355If x is outside the integer range, the function returns a long instead.\n\
1356\n\
1357If x is not a number or if base is given, then x must be a string or\n\
1358Unicode object representing an integer literal in the given base. The\n\
1359literal can be preceded by '+' or '-' and be surrounded by whitespace.\n\
1360The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n\
1361interpret the base from the string as an integer literal.\n\
1362>>> int('0b100', base=0)\n\
13634");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365static PyNumberMethods int_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001366 (binaryfunc)int_add, /*nb_add*/
1367 (binaryfunc)int_sub, /*nb_subtract*/
1368 (binaryfunc)int_mul, /*nb_multiply*/
1369 (binaryfunc)int_classic_div, /*nb_divide*/
1370 (binaryfunc)int_mod, /*nb_remainder*/
1371 (binaryfunc)int_divmod, /*nb_divmod*/
1372 (ternaryfunc)int_pow, /*nb_power*/
1373 (unaryfunc)int_neg, /*nb_negative*/
1374 (unaryfunc)int_int, /*nb_positive*/
1375 (unaryfunc)int_abs, /*nb_absolute*/
1376 (inquiry)int_nonzero, /*nb_nonzero*/
1377 (unaryfunc)int_invert, /*nb_invert*/
1378 (binaryfunc)int_lshift, /*nb_lshift*/
1379 (binaryfunc)int_rshift, /*nb_rshift*/
1380 (binaryfunc)int_and, /*nb_and*/
1381 (binaryfunc)int_xor, /*nb_xor*/
1382 (binaryfunc)int_or, /*nb_or*/
1383 int_coerce, /*nb_coerce*/
1384 (unaryfunc)int_int, /*nb_int*/
1385 (unaryfunc)int_long, /*nb_long*/
1386 (unaryfunc)int_float, /*nb_float*/
1387 (unaryfunc)int_oct, /*nb_oct*/
1388 (unaryfunc)int_hex, /*nb_hex*/
1389 0, /*nb_inplace_add*/
1390 0, /*nb_inplace_subtract*/
1391 0, /*nb_inplace_multiply*/
1392 0, /*nb_inplace_divide*/
1393 0, /*nb_inplace_remainder*/
1394 0, /*nb_inplace_power*/
1395 0, /*nb_inplace_lshift*/
1396 0, /*nb_inplace_rshift*/
1397 0, /*nb_inplace_and*/
1398 0, /*nb_inplace_xor*/
1399 0, /*nb_inplace_or*/
1400 (binaryfunc)int_div, /* nb_floor_divide */
1401 (binaryfunc)int_true_divide, /* nb_true_divide */
1402 0, /* nb_inplace_floor_divide */
1403 0, /* nb_inplace_true_divide */
1404 (unaryfunc)int_int, /* nb_index */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405};
1406
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001407PyTypeObject PyInt_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001408 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1409 "int",
1410 sizeof(PyIntObject),
1411 0,
1412 (destructor)int_dealloc, /* tp_dealloc */
1413 (printfunc)int_print, /* tp_print */
1414 0, /* tp_getattr */
1415 0, /* tp_setattr */
1416 (cmpfunc)int_compare, /* tp_compare */
1417 (reprfunc)int_to_decimal_string, /* tp_repr */
1418 &int_as_number, /* tp_as_number */
1419 0, /* tp_as_sequence */
1420 0, /* tp_as_mapping */
1421 (hashfunc)int_hash, /* tp_hash */
1422 0, /* tp_call */
1423 (reprfunc)int_to_decimal_string, /* tp_str */
1424 PyObject_GenericGetAttr, /* tp_getattro */
1425 0, /* tp_setattro */
1426 0, /* tp_as_buffer */
1427 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1428 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
1429 int_doc, /* tp_doc */
1430 0, /* tp_traverse */
1431 0, /* tp_clear */
1432 0, /* tp_richcompare */
1433 0, /* tp_weaklistoffset */
1434 0, /* tp_iter */
1435 0, /* tp_iternext */
1436 int_methods, /* tp_methods */
1437 0, /* tp_members */
1438 int_getset, /* tp_getset */
1439 0, /* tp_base */
1440 0, /* tp_dict */
1441 0, /* tp_descr_get */
1442 0, /* tp_descr_set */
1443 0, /* tp_dictoffset */
1444 0, /* tp_init */
1445 0, /* tp_alloc */
1446 int_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001447};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001448
Neal Norwitzc91ed402002-12-30 22:29:22 +00001449int
Neal Norwitzb2501f42002-12-31 03:42:13 +00001450_PyInt_Init(void)
Neal Norwitzc91ed402002-12-30 22:29:22 +00001451{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001452 PyIntObject *v;
1453 int ival;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001454#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
Martin Panterca56dd42016-09-17 07:54:55 +00001456 if (!free_list && (free_list = fill_free_list()) == NULL)
1457 return 0;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001458 /* PyObject_New is inlined */
1459 v = free_list;
1460 free_list = (PyIntObject *)Py_TYPE(v);
Martin Panter646b5282016-06-21 23:58:05 +00001461 (void)PyObject_INIT(v, &PyInt_Type);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001462 v->ob_ival = ival;
1463 small_ints[ival + NSMALLNEGINTS] = v;
1464 }
Neal Norwitzc91ed402002-12-30 22:29:22 +00001465#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001467}
1468
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001469int
1470PyInt_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001471{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001472 PyIntObject *p;
1473 PyIntBlock *list, *next;
1474 int i;
1475 int u; /* remaining unfreed ints per block */
1476 int freelist_size = 0;
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001477
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001478 list = block_list;
1479 block_list = NULL;
1480 free_list = NULL;
1481 while (list != NULL) {
1482 u = 0;
1483 for (i = 0, p = &list->objects[0];
1484 i < N_INTOBJECTS;
1485 i++, p++) {
1486 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1487 u++;
1488 }
1489 next = list->next;
1490 if (u) {
1491 list->next = block_list;
1492 block_list = list;
1493 for (i = 0, p = &list->objects[0];
1494 i < N_INTOBJECTS;
1495 i++, p++) {
1496 if (!PyInt_CheckExact(p) ||
1497 p->ob_refcnt == 0) {
1498 Py_TYPE(p) = (struct _typeobject *)
1499 free_list;
1500 free_list = p;
1501 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001502#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 else if (-NSMALLNEGINTS <= p->ob_ival &&
1504 p->ob_ival < NSMALLPOSINTS &&
1505 small_ints[p->ob_ival +
1506 NSMALLNEGINTS] == NULL) {
1507 Py_INCREF(p);
1508 small_ints[p->ob_ival +
1509 NSMALLNEGINTS] = p;
1510 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001511#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001512 }
1513 }
1514 else {
1515 PyMem_FREE(list);
1516 }
1517 freelist_size += u;
1518 list = next;
1519 }
Christian Heimes422051a2008-02-04 18:00:12 +00001520
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001521 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001522}
1523
1524void
1525PyInt_Fini(void)
1526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 PyIntObject *p;
1528 PyIntBlock *list;
1529 int i;
1530 int u; /* total unfreed ints per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001531
1532#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001533 PyIntObject **q;
Christian Heimes422051a2008-02-04 18:00:12 +00001534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001535 i = NSMALLNEGINTS + NSMALLPOSINTS;
1536 q = small_ints;
1537 while (--i >= 0) {
1538 Py_XDECREF(*q);
1539 *q++ = NULL;
1540 }
Christian Heimes422051a2008-02-04 18:00:12 +00001541#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001542 u = PyInt_ClearFreeList();
1543 if (!Py_VerboseFlag)
1544 return;
1545 fprintf(stderr, "# cleanup ints");
1546 if (!u) {
1547 fprintf(stderr, "\n");
1548 }
1549 else {
1550 fprintf(stderr,
1551 ": %d unfreed int%s\n",
1552 u, u == 1 ? "" : "s");
1553 }
1554 if (Py_VerboseFlag > 1) {
1555 list = block_list;
1556 while (list != NULL) {
1557 for (i = 0, p = &list->objects[0];
1558 i < N_INTOBJECTS;
1559 i++, p++) {
1560 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1561 /* XXX(twouters) cast refcount to
1562 long until %zd is universally
1563 available
1564 */
1565 fprintf(stderr,
1566 "# <int at %p, refcnt=%ld, val=%ld>\n",
1567 p, (long)p->ob_refcnt,
1568 p->ob_ival);
1569 }
1570 list = list->next;
1571 }
1572 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001573}