blob: 7d70bfb6e399f1ef0ebf48306ae99879ece0944b [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
Martin v. Löwis18e16552006-02-15 17:27:45 +0000192Py_ssize_t
193PyInt_AsSsize_t(register PyObject *op)
194{
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000195#if SIZEOF_SIZE_T != SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 PyNumberMethods *nb;
197 PyIntObject *io;
198 Py_ssize_t val;
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000199#endif
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000200
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000201 if (op == NULL) {
202 PyErr_SetString(PyExc_TypeError, "an integer is required");
203 return -1;
204 }
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000205
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000206 if (PyInt_Check(op))
207 return PyInt_AS_LONG((PyIntObject*) op);
208 if (PyLong_Check(op))
209 return _PyLong_AsSsize_t(op);
Thomas Woutersb1410fb2006-02-15 23:08:56 +0000210#if SIZEOF_SIZE_T == SIZEOF_LONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000211 return PyInt_AsLong(op);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000212#else
213
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000214 if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
215 (nb->nb_int == NULL && nb->nb_long == 0)) {
216 PyErr_SetString(PyExc_TypeError, "an integer is required");
217 return -1;
218 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000219
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 if (nb->nb_long != 0)
221 io = (PyIntObject*) (*nb->nb_long) (op);
222 else
223 io = (PyIntObject*) (*nb->nb_int) (op);
224 if (io == NULL)
225 return -1;
226 if (!PyInt_Check(io)) {
227 if (PyLong_Check(io)) {
228 /* got a long? => retry int conversion */
229 val = _PyLong_AsSsize_t((PyObject *)io);
230 Py_DECREF(io);
231 if ((val == -1) && PyErr_Occurred())
232 return -1;
233 return val;
234 }
235 else
236 {
237 Py_DECREF(io);
238 PyErr_SetString(PyExc_TypeError,
239 "__int__ method should return an integer");
240 return -1;
241 }
242 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 val = PyInt_AS_LONG(io);
245 Py_DECREF(io);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000246
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000247 return val;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248#endif
249}
250
Thomas Hellera4ea6032003-04-17 18:55:45 +0000251unsigned long
252PyInt_AsUnsignedLongMask(register PyObject *op)
253{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 PyNumberMethods *nb;
255 PyIntObject *io;
256 unsigned long val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000257
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 if (op && PyInt_Check(op))
259 return PyInt_AS_LONG((PyIntObject*) op);
260 if (op && PyLong_Check(op))
261 return PyLong_AsUnsignedLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000262
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000263 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
264 nb->nb_int == NULL) {
265 PyErr_SetString(PyExc_TypeError, "an integer is required");
266 return (unsigned long)-1;
267 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000268
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000269 io = (PyIntObject*) (*nb->nb_int) (op);
270 if (io == NULL)
271 return (unsigned long)-1;
272 if (!PyInt_Check(io)) {
273 if (PyLong_Check(io)) {
274 val = PyLong_AsUnsignedLongMask((PyObject *)io);
275 Py_DECREF(io);
276 if (PyErr_Occurred())
277 return (unsigned long)-1;
278 return val;
279 }
280 else
281 {
282 Py_DECREF(io);
283 PyErr_SetString(PyExc_TypeError,
284 "__int__ method should return an integer");
285 return (unsigned long)-1;
286 }
287 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000288
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 val = PyInt_AS_LONG(io);
290 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000293}
294
295#ifdef HAVE_LONG_LONG
296unsigned PY_LONG_LONG
297PyInt_AsUnsignedLongLongMask(register PyObject *op)
298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 PyNumberMethods *nb;
300 PyIntObject *io;
301 unsigned PY_LONG_LONG val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 if (op && PyInt_Check(op))
304 return PyInt_AS_LONG((PyIntObject*) op);
305 if (op && PyLong_Check(op))
306 return PyLong_AsUnsignedLongLongMask(op);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000307
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000308 if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
309 nb->nb_int == NULL) {
310 PyErr_SetString(PyExc_TypeError, "an integer is required");
311 return (unsigned PY_LONG_LONG)-1;
312 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000313
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000314 io = (PyIntObject*) (*nb->nb_int) (op);
315 if (io == NULL)
316 return (unsigned PY_LONG_LONG)-1;
317 if (!PyInt_Check(io)) {
318 if (PyLong_Check(io)) {
319 val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
320 Py_DECREF(io);
321 if (PyErr_Occurred())
322 return (unsigned PY_LONG_LONG)-1;
323 return val;
324 }
325 else
326 {
327 Py_DECREF(io);
328 PyErr_SetString(PyExc_TypeError,
329 "__int__ method should return an integer");
330 return (unsigned PY_LONG_LONG)-1;
331 }
332 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000333
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000334 val = PyInt_AS_LONG(io);
335 Py_DECREF(io);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000336
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 return val;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000338}
339#endif
340
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000341PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342PyInt_FromString(char *s, char **pend, int base)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000343{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000344 char *end;
345 long x;
346 Py_ssize_t slen;
347 PyObject *sobj, *srepr;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000348
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 if ((base != 0 && base < 2) || base > 36) {
350 PyErr_SetString(PyExc_ValueError,
351 "int() base must be >= 2 and <= 36");
352 return NULL;
353 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000354
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000355 while (*s && isspace(Py_CHARMASK(*s)))
356 s++;
357 errno = 0;
358 if (base == 0 && s[0] == '0') {
359 x = (long) PyOS_strtoul(s, &end, base);
360 if (x < 0)
361 return PyLong_FromString(s, pend, base);
362 }
363 else
364 x = PyOS_strtol(s, &end, base);
365 if (end == s || !isalnum(Py_CHARMASK(end[-1])))
366 goto bad;
367 while (*end && isspace(Py_CHARMASK(*end)))
368 end++;
369 if (*end != '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000370 bad:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000371 slen = strlen(s) < 200 ? strlen(s) : 200;
372 sobj = PyString_FromStringAndSize(s, slen);
373 if (sobj == NULL)
374 return NULL;
375 srepr = PyObject_Repr(sobj);
376 Py_DECREF(sobj);
377 if (srepr == NULL)
378 return NULL;
379 PyErr_Format(PyExc_ValueError,
380 "invalid literal for int() with base %d: %s",
381 base, PyString_AS_STRING(srepr));
382 Py_DECREF(srepr);
383 return NULL;
384 }
385 else if (errno != 0)
386 return PyLong_FromString(s, pend, base);
387 if (pend)
388 *pend = end;
389 return PyInt_FromLong(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000390}
391
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000392#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000393PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000394PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +0000395{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000396 PyObject *result;
397 char *buffer = (char *)PyMem_MALLOC(length+1);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000398
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000399 if (buffer == NULL)
400 return PyErr_NoMemory();
Walter Dörwald07e14762002-11-06 16:15:14 +0000401
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
403 PyMem_FREE(buffer);
404 return NULL;
405 }
406 result = PyInt_FromString(buffer, NULL, base);
407 PyMem_FREE(buffer);
408 return result;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000409}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000410#endif
Guido van Rossum9e896b32000-04-05 20:11:21 +0000411
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412/* Methods */
413
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000414/* Integers are seen as the "smallest" of all numeric types and thus
415 don't have any knowledge about conversion of other types to
416 integers. */
417
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418#define CONVERT_TO_LONG(obj, lng) \
419 if (PyInt_Check(obj)) { \
420 lng = PyInt_AS_LONG(obj); \
421 } \
422 else { \
423 Py_INCREF(Py_NotImplemented); \
424 return Py_NotImplemented; \
425 }
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000426
Guido van Rossum719f5fa1992-03-27 17:31:02 +0000427/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000428static int
Fred Drakea2f55112000-07-09 15:16:51 +0000429int_print(PyIntObject *v, FILE *fp, int flags)
430 /* flags -- not used but required by interface */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 long int_val = v->ob_ival;
433 Py_BEGIN_ALLOW_THREADS
434 fprintf(fp, "%ld", int_val);
435 Py_END_ALLOW_THREADS
436 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437}
438
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439static int
Fred Drakea2f55112000-07-09 15:16:51 +0000440int_compare(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000442 register long i = v->ob_ival;
443 register long j = w->ob_ival;
444 return (i < j) ? -1 : (i > j) ? 1 : 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445}
446
Guido van Rossum9bfef441993-03-29 10:43:31 +0000447static long
Fred Drakea2f55112000-07-09 15:16:51 +0000448int_hash(PyIntObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000450 /* XXX If this is changed, you also need to change the way
451 Python's long, float and complex types are hashed. */
452 long x = v -> ob_ival;
453 if (x == -1)
454 x = -2;
455 return x;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000456}
457
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000459int_add(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000461 register long a, b, x;
462 CONVERT_TO_LONG(v, a);
463 CONVERT_TO_LONG(w, b);
464 /* casts in the line below avoid undefined behaviour on overflow */
465 x = (long)((unsigned long)a + b);
466 if ((x^a) >= 0 || (x^b) >= 0)
467 return PyInt_FromLong(x);
468 return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469}
470
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000472int_sub(PyIntObject *v, PyIntObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 register long a, b, x;
475 CONVERT_TO_LONG(v, a);
476 CONVERT_TO_LONG(w, b);
477 /* casts in the line below avoid undefined behaviour on overflow */
478 x = (long)((unsigned long)a - b);
479 if ((x^a) >= 0 || (x^~b) >= 0)
480 return PyInt_FromLong(x);
481 return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
482 (PyObject *)w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483}
484
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000485/*
Tim Petersa3c01ce2001-12-04 23:05:10 +0000486Integer overflow checking for * is painful: Python tried a couple ways, but
487they didn't work on all platforms, or failed in endcases (a product of
488-sys.maxint-1 has been a particular pain).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000489
Tim Petersa3c01ce2001-12-04 23:05:10 +0000490Here's another way:
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000491
Tim Petersa3c01ce2001-12-04 23:05:10 +0000492The native long product x*y is either exactly right or *way* off, being
493just the last n bits of the true product, where n is the number of bits
494in a long (the delivered product is the true product plus i*2**n for
495some integer i).
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000496
Tim Petersa3c01ce2001-12-04 23:05:10 +0000497The native double product (double)x * (double)y is subject to three
498rounding errors: on a sizeof(long)==8 box, each cast to double can lose
499info, and even on a sizeof(long)==4 box, the multiplication can lose info.
500But, unlike the native long product, it's not in *range* trouble: even
501if sizeof(long)==32 (256-bit longs), the product easily fits in the
502dynamic range of a double. So the leading 50 (or so) bits of the double
503product are correct.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000504
Tim Petersa3c01ce2001-12-04 23:05:10 +0000505We check these two ways against each other, and declare victory if they're
506approximately the same. Else, because the native long product is the only
507one that can lose catastrophic amounts of information, it's the native long
508product that must have overflowed.
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000509*/
510
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511static PyObject *
Neil Schemenauer139e72a2001-01-04 01:45:33 +0000512int_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000514 long a, b;
515 long longprod; /* a*b in native long arithmetic */
516 double doubled_longprod; /* (double)longprod */
517 double doubleprod; /* (double)a * (double)b */
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 CONVERT_TO_LONG(v, a);
520 CONVERT_TO_LONG(w, b);
521 /* casts in the next line avoid undefined behaviour on overflow */
522 longprod = (long)((unsigned long)a * b);
523 doubleprod = (double)a * (double)b;
524 doubled_longprod = (double)longprod;
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000525
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 /* Fast path for normal case: small multiplicands, and no info
527 is lost in either method. */
528 if (doubled_longprod == doubleprod)
529 return PyInt_FromLong(longprod);
Guido van Rossumbf8c0e31994-08-29 12:48:32 +0000530
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000531 /* Somebody somewhere lost info. Close enough, or way off? Note
532 that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
533 The difference either is or isn't significant compared to the
534 true value (of which doubleprod is a good approximation).
535 */
536 {
537 const double diff = doubled_longprod - doubleprod;
538 const double absdiff = diff >= 0.0 ? diff : -diff;
539 const double absprod = doubleprod >= 0.0 ? doubleprod :
540 -doubleprod;
541 /* absdiff/absprod <= 1/32 iff
542 32 * absdiff <= absprod -- 5 good bits is "close enough" */
543 if (32.0 * absdiff <= absprod)
544 return PyInt_FromLong(longprod);
545 else
546 return PyLong_Type.tp_as_number->nb_multiply(v, w);
547 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548}
549
Armin Rigo7ccbca92006-10-04 12:17:45 +0000550/* Integer overflow checking for unary negation: on a 2's-complement
551 * box, -x overflows iff x is the most negative long. In this case we
552 * get -x == x. However, -x is undefined (by C) if x /is/ the most
553 * negative long (it's a signed overflow case), and some compilers care.
554 * So we cast x to unsigned long first. However, then other compilers
555 * warn about applying unary minus to an unsigned operand. Hence the
556 * weird "0-".
557 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000558#define UNARY_NEG_WOULD_OVERFLOW(x) \
559 ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
Armin Rigo7ccbca92006-10-04 12:17:45 +0000560
Guido van Rossume27f7952001-08-23 02:59:04 +0000561/* Return type of i_divmod */
562enum divmod_result {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 DIVMOD_OK, /* Correct result */
564 DIVMOD_OVERFLOW, /* Overflow, try again using longs */
565 DIVMOD_ERROR /* Exception raised */
Guido van Rossume27f7952001-08-23 02:59:04 +0000566};
567
568static enum divmod_result
Tim Peters1dad6a82001-06-18 19:21:11 +0000569i_divmod(register long x, register long y,
Fred Drakea2f55112000-07-09 15:16:51 +0000570 long *p_xdivy, long *p_xmody)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000571{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000572 long xdivy, xmody;
Tim Petersa3c01ce2001-12-04 23:05:10 +0000573
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 if (y == 0) {
575 PyErr_SetString(PyExc_ZeroDivisionError,
576 "integer division or modulo by zero");
577 return DIVMOD_ERROR;
578 }
579 /* (-sys.maxint-1)/-1 is the only overflow case. */
580 if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
581 return DIVMOD_OVERFLOW;
582 xdivy = x / y;
583 /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
584 * for x and y with differing signs. (This is unusual
585 * behaviour, and C99 prohibits it, but it's allowed by C89;
586 * for an example of overflow, take x = LONG_MIN, y = 5 or x =
587 * LONG_MAX, y = -5.) However, x - xdivy*y is always
588 * representable as a long, since it lies strictly between
589 * -abs(y) and abs(y). We add casts to avoid intermediate
590 * overflow.
591 */
592 xmody = (long)(x - (unsigned long)xdivy * y);
593 /* If the signs of x and y differ, and the remainder is non-0,
594 * C89 doesn't define whether xdivy is now the floor or the
595 * ceiling of the infinitely precise quotient. We want the floor,
596 * and we have it iff the remainder's sign matches y's.
597 */
598 if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
599 xmody += y;
600 --xdivy;
601 assert(xmody && ((y ^ xmody) >= 0));
602 }
603 *p_xdivy = xdivy;
604 *p_xmody = xmody;
605 return DIVMOD_OK;
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000606}
607
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000609int_div(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000610{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000611 long xi, yi;
612 long d, m;
613 CONVERT_TO_LONG(x, xi);
614 CONVERT_TO_LONG(y, yi);
615 switch (i_divmod(xi, yi, &d, &m)) {
616 case DIVMOD_OK:
617 return PyInt_FromLong(d);
618 case DIVMOD_OVERFLOW:
619 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
620 (PyObject *)y);
621 default:
622 return NULL;
623 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000624}
625
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000627int_classic_div(PyIntObject *x, PyIntObject *y)
628{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000629 long xi, yi;
630 long d, m;
631 CONVERT_TO_LONG(x, xi);
632 CONVERT_TO_LONG(y, yi);
633 if (Py_DivisionWarningFlag &&
634 PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
635 return NULL;
636 switch (i_divmod(xi, yi, &d, &m)) {
637 case DIVMOD_OK:
638 return PyInt_FromLong(d);
639 case DIVMOD_OVERFLOW:
640 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
641 (PyObject *)y);
642 default:
643 return NULL;
644 }
Guido van Rossum393661d2001-08-31 17:40:15 +0000645}
646
647static PyObject *
Mark Dickinson46572832009-12-27 14:55:57 +0000648int_true_divide(PyIntObject *x, PyIntObject *y)
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000649{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000650 long xi, yi;
651 /* If they aren't both ints, give someone else a chance. In
652 particular, this lets int/long get handled by longs, which
653 underflows to 0 gracefully if the long is too big to convert
654 to float. */
655 CONVERT_TO_LONG(x, xi);
656 CONVERT_TO_LONG(y, yi);
657 if (yi == 0) {
658 PyErr_SetString(PyExc_ZeroDivisionError,
659 "division by zero");
660 return NULL;
661 }
662 if (xi == 0)
663 return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
Mark Dickinson46572832009-12-27 14:55:57 +0000664
665#define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG)
666#if DBL_MANT_DIG < WIDTH_OF_ULONG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000667 if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
668 (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
669 /* Large x or y. Use long integer arithmetic. */
670 return PyLong_Type.tp_as_number->nb_true_divide(
671 (PyObject *)x, (PyObject *)y);
672 else
Mark Dickinson46572832009-12-27 14:55:57 +0000673#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 /* Both ints can be exactly represented as doubles. Do a
675 floating-point division. */
676 return PyFloat_FromDouble((double)xi / (double)yi);
Tim Peters9c1d7fd2001-09-04 05:52:47 +0000677}
678
679static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000680int_mod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 long xi, yi;
683 long d, m;
684 CONVERT_TO_LONG(x, xi);
685 CONVERT_TO_LONG(y, yi);
686 switch (i_divmod(xi, yi, &d, &m)) {
687 case DIVMOD_OK:
688 return PyInt_FromLong(m);
689 case DIVMOD_OVERFLOW:
690 return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
691 (PyObject *)y);
692 default:
693 return NULL;
694 }
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000695}
696
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000698int_divmod(PyIntObject *x, PyIntObject *y)
Guido van Rossum2b16a6f1992-01-19 16:28:51 +0000699{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000700 long xi, yi;
701 long d, m;
702 CONVERT_TO_LONG(x, xi);
703 CONVERT_TO_LONG(y, yi);
704 switch (i_divmod(xi, yi, &d, &m)) {
705 case DIVMOD_OK:
706 return Py_BuildValue("(ll)", d, m);
707 case DIVMOD_OVERFLOW:
708 return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
709 (PyObject *)y);
710 default:
711 return NULL;
712 }
Guido van Rossum00466951991-05-05 20:08:27 +0000713}
714
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000715static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000716int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000718 register long iv, iw, iz=0, ix, temp, prev;
719 CONVERT_TO_LONG(v, iv);
720 CONVERT_TO_LONG(w, iw);
721 if (iw < 0) {
722 if ((PyObject *)z != Py_None) {
723 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
724 "cannot be negative when 3rd argument specified");
725 return NULL;
726 }
727 /* Return a float. This works because we know that
728 this calls float_pow() which converts its
729 arguments to double. */
730 return PyFloat_Type.tp_as_number->nb_power(
731 (PyObject *)v, (PyObject *)w, (PyObject *)z);
732 }
733 if ((PyObject *)z != Py_None) {
734 CONVERT_TO_LONG(z, iz);
735 if (iz == 0) {
736 PyErr_SetString(PyExc_ValueError,
737 "pow() 3rd argument cannot be 0");
738 return NULL;
739 }
740 }
741 /*
742 * XXX: The original exponentiation code stopped looping
743 * when temp hit zero; this code will continue onwards
744 * unnecessarily, but at least it won't cause any errors.
745 * Hopefully the speed improvement from the fast exponentiation
746 * will compensate for the slight inefficiency.
747 * XXX: Better handling of overflows is desperately needed.
748 */
749 temp = iv;
750 ix = 1;
751 while (iw > 0) {
752 prev = ix; /* Save value for overflow check */
753 if (iw & 1) {
754 ix = ix*temp;
755 if (temp == 0)
756 break; /* Avoid ix / 0 */
757 if (ix / temp != prev) {
758 return PyLong_Type.tp_as_number->nb_power(
759 (PyObject *)v,
760 (PyObject *)w,
761 (PyObject *)z);
762 }
763 }
764 iw >>= 1; /* Shift exponent down by 1 bit */
765 if (iw==0) break;
766 prev = temp;
767 temp *= temp; /* Square the value of temp */
768 if (prev != 0 && temp / prev != prev) {
769 return PyLong_Type.tp_as_number->nb_power(
770 (PyObject *)v, (PyObject *)w, (PyObject *)z);
771 }
772 if (iz) {
773 /* If we did a multiplication, perform a modulo */
774 ix = ix % iz;
775 temp = temp % iz;
776 }
777 }
778 if (iz) {
779 long div, mod;
780 switch (i_divmod(ix, iz, &div, &mod)) {
781 case DIVMOD_OK:
782 ix = mod;
783 break;
784 case DIVMOD_OVERFLOW:
785 return PyLong_Type.tp_as_number->nb_power(
786 (PyObject *)v, (PyObject *)w, (PyObject *)z);
787 default:
788 return NULL;
789 }
790 }
791 return PyInt_FromLong(ix);
Tim Petersa3c01ce2001-12-04 23:05:10 +0000792}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000793
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000795int_neg(PyIntObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 register long a;
798 a = v->ob_ival;
799 /* check for overflow */
800 if (UNARY_NEG_WOULD_OVERFLOW(a)) {
801 PyObject *o = PyLong_FromLong(a);
802 if (o != NULL) {
803 PyObject *result = PyNumber_Negative(o);
804 Py_DECREF(o);
805 return result;
806 }
807 return NULL;
808 }
809 return PyInt_FromLong(-a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000813int_abs(PyIntObject *v)
Guido van Rossum00466951991-05-05 20:08:27 +0000814{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 if (v->ob_ival >= 0)
816 return int_int(v);
817 else
818 return int_neg(v);
Guido van Rossum00466951991-05-05 20:08:27 +0000819}
820
Guido van Rossum0bff0151991-05-14 12:05:32 +0000821static int
Fred Drakea2f55112000-07-09 15:16:51 +0000822int_nonzero(PyIntObject *v)
Guido van Rossum0bff0151991-05-14 12:05:32 +0000823{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 return v->ob_ival != 0;
Guido van Rossum0bff0151991-05-14 12:05:32 +0000825}
826
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000827static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000828int_invert(PyIntObject *v)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000829{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000830 return PyInt_FromLong(~v->ob_ival);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000831}
832
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000833static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000834int_lshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000835{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000836 long a, b, c;
837 PyObject *vv, *ww, *result;
Raymond Hettingera006c372004-06-26 23:22:57 +0000838
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000839 CONVERT_TO_LONG(v, a);
840 CONVERT_TO_LONG(w, b);
841 if (b < 0) {
842 PyErr_SetString(PyExc_ValueError, "negative shift count");
843 return NULL;
844 }
845 if (a == 0 || b == 0)
846 return int_int(v);
847 if (b >= LONG_BIT) {
848 vv = PyLong_FromLong(PyInt_AS_LONG(v));
849 if (vv == NULL)
850 return NULL;
851 ww = PyLong_FromLong(PyInt_AS_LONG(w));
852 if (ww == NULL) {
853 Py_DECREF(vv);
854 return NULL;
855 }
856 result = PyNumber_Lshift(vv, ww);
857 Py_DECREF(vv);
858 Py_DECREF(ww);
859 return result;
860 }
861 c = a << b;
862 if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
863 vv = PyLong_FromLong(PyInt_AS_LONG(v));
864 if (vv == NULL)
865 return NULL;
866 ww = PyLong_FromLong(PyInt_AS_LONG(w));
867 if (ww == NULL) {
868 Py_DECREF(vv);
869 return NULL;
870 }
871 result = PyNumber_Lshift(vv, ww);
872 Py_DECREF(vv);
873 Py_DECREF(ww);
874 return result;
875 }
876 return PyInt_FromLong(c);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000877}
878
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000880int_rshift(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000881{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 register long a, b;
883 CONVERT_TO_LONG(v, a);
884 CONVERT_TO_LONG(w, b);
885 if (b < 0) {
886 PyErr_SetString(PyExc_ValueError, "negative shift count");
887 return NULL;
888 }
889 if (a == 0 || b == 0)
890 return int_int(v);
891 if (b >= LONG_BIT) {
892 if (a < 0)
893 a = -1;
894 else
895 a = 0;
896 }
897 else {
898 a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
899 }
900 return PyInt_FromLong(a);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000901}
902
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000903static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000904int_and(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000905{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 register long a, b;
907 CONVERT_TO_LONG(v, a);
908 CONVERT_TO_LONG(w, b);
909 return PyInt_FromLong(a & b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000910}
911
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000912static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000913int_xor(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000914{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 register long a, b;
916 CONVERT_TO_LONG(v, a);
917 CONVERT_TO_LONG(w, b);
918 return PyInt_FromLong(a ^ b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000919}
920
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000921static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000922int_or(PyIntObject *v, PyIntObject *w)
Guido van Rossum7928cd71991-10-24 14:59:31 +0000923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 register long a, b;
925 CONVERT_TO_LONG(v, a);
926 CONVERT_TO_LONG(w, b);
927 return PyInt_FromLong(a | b);
Guido van Rossum7928cd71991-10-24 14:59:31 +0000928}
929
Guido van Rossum1952e382001-09-19 01:25:16 +0000930static int
931int_coerce(PyObject **pv, PyObject **pw)
932{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 if (PyInt_Check(*pw)) {
934 Py_INCREF(*pv);
935 Py_INCREF(*pw);
936 return 0;
937 }
938 return 1; /* Can't do it */
Guido van Rossum1952e382001-09-19 01:25:16 +0000939}
940
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000942int_int(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000944 if (PyInt_CheckExact(v))
945 Py_INCREF(v);
946 else
947 v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
948 return (PyObject *)v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000949}
950
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000952int_long(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000953{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000954 return PyLong_FromLong((v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000955}
956
Mark Dickinson6736cf82009-04-20 21:13:33 +0000957static const unsigned char BitLengthTable[32] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000958 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
959 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson6736cf82009-04-20 21:13:33 +0000960};
961
962static int
963bits_in_ulong(unsigned long d)
964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000965 int d_bits = 0;
966 while (d >= 32) {
967 d_bits += 6;
968 d >>= 6;
969 }
970 d_bits += (int)BitLengthTable[d];
971 return d_bits;
Mark Dickinson6736cf82009-04-20 21:13:33 +0000972}
973
974#if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG
975/* Every Python int can be exactly represented as a float. */
976
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000977static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000978int_float(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000979{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000980 return PyFloat_FromDouble((double)(v -> ob_ival));
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000981}
982
Mark Dickinson6736cf82009-04-20 21:13:33 +0000983#else
984/* Here not all Python ints are exactly representable as floats, so we may
985 have to round. We do this manually, since the C standards don't specify
986 whether converting an integer to a float rounds up or down */
987
988static PyObject *
989int_float(PyIntObject *v)
990{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 unsigned long abs_ival, lsb;
992 int round_up;
Mark Dickinson6736cf82009-04-20 21:13:33 +0000993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 if (v->ob_ival < 0)
995 abs_ival = 0U-(unsigned long)v->ob_ival;
996 else
997 abs_ival = (unsigned long)v->ob_ival;
998 if (abs_ival < (1L << DBL_MANT_DIG))
999 /* small integer; no need to round */
1000 return PyFloat_FromDouble((double)v->ob_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001002 /* Round abs_ival to MANT_DIG significant bits, using the
1003 round-half-to-even rule. abs_ival & lsb picks out the 'rounding'
1004 bit: the first bit after the most significant MANT_DIG bits of
1005 abs_ival. We round up if this bit is set, provided that either:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001007 (1) abs_ival isn't exactly halfway between two floats, in which
1008 case at least one of the bits following the rounding bit must be
1009 set; i.e., abs_ival & lsb-1 != 0, or:
Mark Dickinson6736cf82009-04-20 21:13:33 +00001010
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 (2) the resulting rounded value has least significant bit 0; or
1012 in other words the bit above the rounding bit is set (this is the
1013 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
Mark Dickinson6736cf82009-04-20 21:13:33 +00001014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
Mark Dickinson6736cf82009-04-20 21:13:33 +00001016
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
1018 round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
1019 abs_ival &= -2*lsb;
1020 if (round_up)
1021 abs_ival += 2*lsb;
1022 return PyFloat_FromDouble(v->ob_ival < 0 ?
1023 -(double)abs_ival :
1024 (double)abs_ival);
Mark Dickinson6736cf82009-04-20 21:13:33 +00001025}
1026
1027#endif
1028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001029static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001030int_oct(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001031{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 return _PyInt_Format(v, 8, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001033}
1034
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001035static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001036int_hex(PyIntObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001037{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 return _PyInt_Format(v, 16, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001039}
1040
Jeremy Hylton938ace62002-07-17 16:30:39 +00001041static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001042int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1043
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044static PyObject *
1045int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1046{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 PyObject *x = NULL;
1048 int base = -909;
1049 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 if (type != &PyInt_Type)
1052 return int_subtype_new(type, args, kwds); /* Wimp out */
1053 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
1054 &x, &base))
1055 return NULL;
1056 if (x == NULL)
1057 return PyInt_FromLong(0L);
1058 if (base == -909)
1059 return PyNumber_Int(x);
1060 if (PyString_Check(x)) {
1061 /* Since PyInt_FromString doesn't have a length parameter,
1062 * check here for possible NULs in the string. */
1063 char *string = PyString_AS_STRING(x);
1064 if (strlen(string) != PyString_Size(x)) {
1065 /* create a repr() of the input string,
1066 * just like PyInt_FromString does */
1067 PyObject *srepr;
1068 srepr = PyObject_Repr(x);
1069 if (srepr == NULL)
1070 return NULL;
1071 PyErr_Format(PyExc_ValueError,
1072 "invalid literal for int() with base %d: %s",
1073 base, PyString_AS_STRING(srepr));
1074 Py_DECREF(srepr);
1075 return NULL;
1076 }
1077 return PyInt_FromString(string, NULL, base);
1078 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001079#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 if (PyUnicode_Check(x))
1081 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
1082 PyUnicode_GET_SIZE(x),
1083 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001084#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001085 PyErr_SetString(PyExc_TypeError,
1086 "int() can't convert non-string with explicit base");
1087 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088}
1089
Guido van Rossumbef14172001-08-29 15:47:46 +00001090/* Wimpy, slow approach to tp_new calls for subtypes of int:
1091 first create a regular int from whatever arguments we got,
1092 then allocate a subtype instance and initialize its ob_ival
1093 from the regular int. The regular int is then thrown away.
1094*/
1095static PyObject *
1096int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1097{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001098 PyObject *tmp, *newobj;
1099 long ival;
Guido van Rossumbef14172001-08-29 15:47:46 +00001100
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001101 assert(PyType_IsSubtype(type, &PyInt_Type));
1102 tmp = int_new(&PyInt_Type, args, kwds);
1103 if (tmp == NULL)
1104 return NULL;
1105 if (!PyInt_Check(tmp)) {
1106 ival = PyLong_AsLong(tmp);
1107 if (ival == -1 && PyErr_Occurred()) {
1108 Py_DECREF(tmp);
1109 return NULL;
1110 }
1111 } else {
1112 ival = ((PyIntObject *)tmp)->ob_ival;
1113 }
Neal Norwitzde8b94c2003-02-10 02:12:43 +00001114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 newobj = type->tp_alloc(type, 0);
1116 if (newobj == NULL) {
1117 Py_DECREF(tmp);
1118 return NULL;
1119 }
1120 ((PyIntObject *)newobj)->ob_ival = ival;
1121 Py_DECREF(tmp);
1122 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001123}
1124
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001125static PyObject *
1126int_getnewargs(PyIntObject *v)
1127{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 return Py_BuildValue("(l)", v->ob_ival);
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001129}
1130
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001131static PyObject *
Mark Dickinson85e269b2009-05-03 20:39:06 +00001132int_get0(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001133 return PyInt_FromLong(0L);
Mark Dickinson85e269b2009-05-03 20:39:06 +00001134}
1135
1136static PyObject *
1137int_get1(PyIntObject *v, void *context) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 return PyInt_FromLong(1L);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001139}
1140
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001141/* Convert an integer to a decimal string. On many platforms, this
1142 will be significantly faster than the general arbitrary-base
1143 conversion machinery in _PyInt_Format, thanks to optimization
1144 opportunities offered by division by a compile-time constant. */
1145static PyObject *
1146int_to_decimal_string(PyIntObject *v) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
1148 long n = v->ob_ival;
1149 unsigned long absn;
1150 p = bufend = buf + sizeof(buf);
1151 absn = n < 0 ? 0UL - n : n;
1152 do {
1153 *--p = '0' + (char)(absn % 10);
1154 absn /= 10;
1155 } while (absn);
1156 if (n < 0)
1157 *--p = '-';
1158 return PyString_FromStringAndSize(p, bufend - p);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001159}
1160
Eric Smith5e527eb2008-02-10 01:36:53 +00001161/* Convert an integer to the given base. Returns a string.
1162 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.
1163 If newstyle is zero, then use the pre-2.6 behavior of octal having
1164 a leading "0" */
1165PyAPI_FUNC(PyObject*)
1166_PyInt_Format(PyIntObject *v, int base, int newstyle)
1167{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 /* There are no doubt many, many ways to optimize this, using code
1169 similar to _PyLong_Format */
1170 long n = v->ob_ival;
1171 int negative = n < 0;
1172 int is_zero = n == 0;
Eric Smith5e527eb2008-02-10 01:36:53 +00001173
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001174 /* For the reasoning behind this size, see
1175 http://c-faq.com/misc/hexio.html. Then, add a few bytes for
1176 the possible sign and prefix "0[box]" */
1177 char buf[sizeof(n)*CHAR_BIT+6];
Eric Smith5e527eb2008-02-10 01:36:53 +00001178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 /* Start by pointing to the end of the buffer. We fill in from
1180 the back forward. */
1181 char* p = &buf[sizeof(buf)];
Eric Smith5e527eb2008-02-10 01:36:53 +00001182
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 assert(base >= 2 && base <= 36);
Eric Smith5e527eb2008-02-10 01:36:53 +00001184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001185 /* Special case base 10, for speed */
1186 if (base == 10)
1187 return int_to_decimal_string(v);
Mark Dickinson4b9d4732009-09-27 16:05:21 +00001188
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001189 do {
1190 /* I'd use i_divmod, except it doesn't produce the results
1191 I want when n is negative. So just duplicate the salient
1192 part here. */
1193 long div = n / base;
1194 long mod = n - div * base;
Eric Smith5e527eb2008-02-10 01:36:53 +00001195
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001196 /* convert abs(mod) to the right character in [0-9, a-z] */
1197 char cdigit = (char)(mod < 0 ? -mod : mod);
1198 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1199 *--p = cdigit;
Eric Smith5e527eb2008-02-10 01:36:53 +00001200
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001201 n = div;
1202 } while(n);
Eric Smith5e527eb2008-02-10 01:36:53 +00001203
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001204 if (base == 2) {
1205 *--p = 'b';
1206 *--p = '0';
1207 }
1208 else if (base == 8) {
1209 if (newstyle) {
1210 *--p = 'o';
1211 *--p = '0';
1212 }
1213 else
1214 if (!is_zero)
1215 *--p = '0';
1216 }
1217 else if (base == 16) {
1218 *--p = 'x';
1219 *--p = '0';
1220 }
1221 else {
1222 *--p = '#';
1223 *--p = '0' + base%10;
1224 if (base > 10)
1225 *--p = '0' + base/10;
1226 }
1227 if (negative)
1228 *--p = '-';
Eric Smith5e527eb2008-02-10 01:36:53 +00001229
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
Eric Smith5e527eb2008-02-10 01:36:53 +00001231}
1232
Eric Smitha9f7d622008-02-17 19:46:49 +00001233static PyObject *
1234int__format__(PyObject *self, PyObject *args)
1235{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001236 PyObject *format_spec;
Eric Smitha9f7d622008-02-17 19:46:49 +00001237
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001238 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1239 return NULL;
1240 if (PyBytes_Check(format_spec))
1241 return _PyInt_FormatAdvanced(self,
1242 PyBytes_AS_STRING(format_spec),
1243 PyBytes_GET_SIZE(format_spec));
1244 if (PyUnicode_Check(format_spec)) {
1245 /* Convert format_spec to a str */
1246 PyObject *result;
1247 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00001248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001249 if (str_spec == NULL)
1250 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001251
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001252 result = _PyInt_FormatAdvanced(self,
1253 PyBytes_AS_STRING(str_spec),
1254 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00001255
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001256 Py_DECREF(str_spec);
1257 return result;
1258 }
1259 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1260 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00001261}
1262
Mark Dickinson1a707982008-12-17 16:14:37 +00001263static PyObject *
1264int_bit_length(PyIntObject *v)
1265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001266 unsigned long n;
Mark Dickinson1a707982008-12-17 16:14:37 +00001267
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001268 if (v->ob_ival < 0)
1269 /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
1270 n = 0U-(unsigned long)v->ob_ival;
1271 else
1272 n = (unsigned long)v->ob_ival;
Mark Dickinson1a707982008-12-17 16:14:37 +00001273
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001274 return PyInt_FromLong(bits_in_ulong(n));
Mark Dickinson1a707982008-12-17 16:14:37 +00001275}
1276
1277PyDoc_STRVAR(int_bit_length_doc,
1278"int.bit_length() -> int\n\
1279\n\
1280Number of bits necessary to represent self in binary.\n\
1281>>> bin(37)\n\
1282'0b100101'\n\
1283>>> (37).bit_length()\n\
12846");
1285
Christian Heimes6f341092008-04-18 23:13:07 +00001286#if 0
1287static PyObject *
1288int_is_finite(PyObject *v)
1289{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001290 Py_RETURN_TRUE;
Christian Heimes6f341092008-04-18 23:13:07 +00001291}
1292#endif
1293
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001294static PyMethodDef int_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001295 {"conjugate", (PyCFunction)int_int, METH_NOARGS,
1296 "Returns self, the complex conjugate of any int."},
1297 {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
1298 int_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00001299#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
1301 "Returns always True."},
Christian Heimes6f341092008-04-18 23:13:07 +00001302#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001303 {"__trunc__", (PyCFunction)int_int, METH_NOARGS,
1304 "Truncating an Integral returns itself."},
1305 {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
1306 {"__format__", (PyCFunction)int__format__, METH_VARARGS},
1307 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001308};
1309
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001310static PyGetSetDef int_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 {"real",
1312 (getter)int_int, (setter)NULL,
1313 "the real part of a complex number",
1314 NULL},
1315 {"imag",
1316 (getter)int_get0, (setter)NULL,
1317 "the imaginary part of a complex number",
1318 NULL},
1319 {"numerator",
1320 (getter)int_int, (setter)NULL,
1321 "the numerator of a rational number in lowest terms",
1322 NULL},
1323 {"denominator",
1324 (getter)int_get1, (setter)NULL,
1325 "the denominator of a rational number in lowest terms",
1326 NULL},
1327 {NULL} /* Sentinel */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001328};
1329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001330PyDoc_STRVAR(int_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331"int(x[, base]) -> integer\n\
1332\n\
1333Convert a string or number to an integer, if possible. A floating point\n\
1334argument will be truncated towards zero (this does not include a string\n\
1335representation of a floating point number!) When converting a string, use\n\
1336the optional base. It is an error to supply a base when converting a\n\
Gustavo Niemeyer37e65022007-01-10 16:15:48 +00001337non-string. If base is zero, the proper base is guessed based on the\n\
Gustavo Niemeyera443bc82007-01-10 16:13:40 +00001338string content. If the argument is outside the integer range a\n\
1339long object will be returned instead.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001341static PyNumberMethods int_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001342 (binaryfunc)int_add, /*nb_add*/
1343 (binaryfunc)int_sub, /*nb_subtract*/
1344 (binaryfunc)int_mul, /*nb_multiply*/
1345 (binaryfunc)int_classic_div, /*nb_divide*/
1346 (binaryfunc)int_mod, /*nb_remainder*/
1347 (binaryfunc)int_divmod, /*nb_divmod*/
1348 (ternaryfunc)int_pow, /*nb_power*/
1349 (unaryfunc)int_neg, /*nb_negative*/
1350 (unaryfunc)int_int, /*nb_positive*/
1351 (unaryfunc)int_abs, /*nb_absolute*/
1352 (inquiry)int_nonzero, /*nb_nonzero*/
1353 (unaryfunc)int_invert, /*nb_invert*/
1354 (binaryfunc)int_lshift, /*nb_lshift*/
1355 (binaryfunc)int_rshift, /*nb_rshift*/
1356 (binaryfunc)int_and, /*nb_and*/
1357 (binaryfunc)int_xor, /*nb_xor*/
1358 (binaryfunc)int_or, /*nb_or*/
1359 int_coerce, /*nb_coerce*/
1360 (unaryfunc)int_int, /*nb_int*/
1361 (unaryfunc)int_long, /*nb_long*/
1362 (unaryfunc)int_float, /*nb_float*/
1363 (unaryfunc)int_oct, /*nb_oct*/
1364 (unaryfunc)int_hex, /*nb_hex*/
1365 0, /*nb_inplace_add*/
1366 0, /*nb_inplace_subtract*/
1367 0, /*nb_inplace_multiply*/
1368 0, /*nb_inplace_divide*/
1369 0, /*nb_inplace_remainder*/
1370 0, /*nb_inplace_power*/
1371 0, /*nb_inplace_lshift*/
1372 0, /*nb_inplace_rshift*/
1373 0, /*nb_inplace_and*/
1374 0, /*nb_inplace_xor*/
1375 0, /*nb_inplace_or*/
1376 (binaryfunc)int_div, /* nb_floor_divide */
1377 (binaryfunc)int_true_divide, /* nb_true_divide */
1378 0, /* nb_inplace_floor_divide */
1379 0, /* nb_inplace_true_divide */
1380 (unaryfunc)int_int, /* nb_index */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001381};
1382
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001383PyTypeObject PyInt_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001384 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1385 "int",
1386 sizeof(PyIntObject),
1387 0,
1388 (destructor)int_dealloc, /* tp_dealloc */
1389 (printfunc)int_print, /* tp_print */
1390 0, /* tp_getattr */
1391 0, /* tp_setattr */
1392 (cmpfunc)int_compare, /* tp_compare */
1393 (reprfunc)int_to_decimal_string, /* tp_repr */
1394 &int_as_number, /* tp_as_number */
1395 0, /* tp_as_sequence */
1396 0, /* tp_as_mapping */
1397 (hashfunc)int_hash, /* tp_hash */
1398 0, /* tp_call */
1399 (reprfunc)int_to_decimal_string, /* tp_str */
1400 PyObject_GenericGetAttr, /* tp_getattro */
1401 0, /* tp_setattro */
1402 0, /* tp_as_buffer */
1403 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1404 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
1405 int_doc, /* tp_doc */
1406 0, /* tp_traverse */
1407 0, /* tp_clear */
1408 0, /* tp_richcompare */
1409 0, /* tp_weaklistoffset */
1410 0, /* tp_iter */
1411 0, /* tp_iternext */
1412 int_methods, /* tp_methods */
1413 0, /* tp_members */
1414 int_getset, /* tp_getset */
1415 0, /* tp_base */
1416 0, /* tp_dict */
1417 0, /* tp_descr_get */
1418 0, /* tp_descr_set */
1419 0, /* tp_dictoffset */
1420 0, /* tp_init */
1421 0, /* tp_alloc */
1422 int_new, /* tp_new */
1423 (freefunc)int_free, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001424};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001425
Neal Norwitzc91ed402002-12-30 22:29:22 +00001426int
Neal Norwitzb2501f42002-12-31 03:42:13 +00001427_PyInt_Init(void)
Neal Norwitzc91ed402002-12-30 22:29:22 +00001428{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001429 PyIntObject *v;
1430 int ival;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001431#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001432 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
1433 if (!free_list && (free_list = fill_free_list()) == NULL)
1434 return 0;
1435 /* PyObject_New is inlined */
1436 v = free_list;
1437 free_list = (PyIntObject *)Py_TYPE(v);
1438 PyObject_INIT(v, &PyInt_Type);
1439 v->ob_ival = ival;
1440 small_ints[ival + NSMALLNEGINTS] = v;
1441 }
Neal Norwitzc91ed402002-12-30 22:29:22 +00001442#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 return 1;
Neal Norwitzc91ed402002-12-30 22:29:22 +00001444}
1445
Gregory P. Smith2fe77062008-07-06 03:35:58 +00001446int
1447PyInt_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001448{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 PyIntObject *p;
1450 PyIntBlock *list, *next;
1451 int i;
1452 int u; /* remaining unfreed ints per block */
1453 int freelist_size = 0;
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 list = block_list;
1456 block_list = NULL;
1457 free_list = NULL;
1458 while (list != NULL) {
1459 u = 0;
1460 for (i = 0, p = &list->objects[0];
1461 i < N_INTOBJECTS;
1462 i++, p++) {
1463 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1464 u++;
1465 }
1466 next = list->next;
1467 if (u) {
1468 list->next = block_list;
1469 block_list = list;
1470 for (i = 0, p = &list->objects[0];
1471 i < N_INTOBJECTS;
1472 i++, p++) {
1473 if (!PyInt_CheckExact(p) ||
1474 p->ob_refcnt == 0) {
1475 Py_TYPE(p) = (struct _typeobject *)
1476 free_list;
1477 free_list = p;
1478 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001479#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 else if (-NSMALLNEGINTS <= p->ob_ival &&
1481 p->ob_ival < NSMALLPOSINTS &&
1482 small_ints[p->ob_ival +
1483 NSMALLNEGINTS] == NULL) {
1484 Py_INCREF(p);
1485 small_ints[p->ob_ival +
1486 NSMALLNEGINTS] = p;
1487 }
Guido van Rossum51288bc1999-03-19 20:30:39 +00001488#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001489 }
1490 }
1491 else {
1492 PyMem_FREE(list);
1493 }
1494 freelist_size += u;
1495 list = next;
1496 }
Christian Heimes422051a2008-02-04 18:00:12 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 return freelist_size;
Christian Heimes422051a2008-02-04 18:00:12 +00001499}
1500
1501void
1502PyInt_Fini(void)
1503{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 PyIntObject *p;
1505 PyIntBlock *list;
1506 int i;
1507 int u; /* total unfreed ints per block */
Christian Heimes422051a2008-02-04 18:00:12 +00001508
1509#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001510 PyIntObject **q;
Christian Heimes422051a2008-02-04 18:00:12 +00001511
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001512 i = NSMALLNEGINTS + NSMALLPOSINTS;
1513 q = small_ints;
1514 while (--i >= 0) {
1515 Py_XDECREF(*q);
1516 *q++ = NULL;
1517 }
Christian Heimes422051a2008-02-04 18:00:12 +00001518#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001519 u = PyInt_ClearFreeList();
1520 if (!Py_VerboseFlag)
1521 return;
1522 fprintf(stderr, "# cleanup ints");
1523 if (!u) {
1524 fprintf(stderr, "\n");
1525 }
1526 else {
1527 fprintf(stderr,
1528 ": %d unfreed int%s\n",
1529 u, u == 1 ? "" : "s");
1530 }
1531 if (Py_VerboseFlag > 1) {
1532 list = block_list;
1533 while (list != NULL) {
1534 for (i = 0, p = &list->objects[0];
1535 i < N_INTOBJECTS;
1536 i++, p++) {
1537 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
1538 /* XXX(twouters) cast refcount to
1539 long until %zd is universally
1540 available
1541 */
1542 fprintf(stderr,
1543 "# <int at %p, refcnt=%ld, val=%ld>\n",
1544 p, (long)p->ob_refcnt,
1545 p->ob_ival);
1546 }
1547 list = list->next;
1548 }
1549 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001550}