blob: 4024491f133736ab9a0993941d7f3af982bfed84 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000437/* Get a Py_ssize_t from a long int object.
438 Returns -1 and sets an error condition if overflow occurs. */
439
440Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register PyLongObject *v;
443 size_t x, prev;
444 Py_ssize_t i;
445 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (vv == NULL) {
448 PyErr_BadInternalCall();
449 return -1;
450 }
451 if (!PyLong_Check(vv)) {
452 PyErr_SetString(PyExc_TypeError, "an integer is required");
453 return -1;
454 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 v = (PyLongObject *)vv;
457 i = Py_SIZE(v);
458 switch (i) {
459 case -1: return -(sdigit)v->ob_digit[0];
460 case 0: return 0;
461 case 1: return v->ob_digit[0];
462 }
463 sign = 1;
464 x = 0;
465 if (i < 0) {
466 sign = -1;
467 i = -(i);
468 }
469 while (--i >= 0) {
470 prev = x;
471 x = (x << PyLong_SHIFT) | v->ob_digit[i];
472 if ((x >> PyLong_SHIFT) != prev)
473 goto overflow;
474 }
475 /* Haven't lost any bits, but casting to a signed type requires
476 * extra care (see comment above).
477 */
478 if (x <= (size_t)PY_SSIZE_T_MAX) {
479 return (Py_ssize_t)x * sign;
480 }
481 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
482 return PY_SSIZE_T_MIN;
483 }
484 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485
Mark Dickinson22b20182010-05-10 21:27:53 +0000486 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C ssize_t");
489 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490}
491
Guido van Rossumd8c80482002-08-13 00:24:58 +0000492/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 Returns -1 and sets an error condition if overflow occurs. */
494
495unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000496PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 register PyLongObject *v;
499 unsigned long x, prev;
500 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (vv == NULL) {
503 PyErr_BadInternalCall();
504 return (unsigned long)-1;
505 }
506 if (!PyLong_Check(vv)) {
507 PyErr_SetString(PyExc_TypeError, "an integer is required");
508 return (unsigned long)-1;
509 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 v = (PyLongObject *)vv;
512 i = Py_SIZE(v);
513 x = 0;
514 if (i < 0) {
515 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000516 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return (unsigned long) -1;
518 }
519 switch (i) {
520 case 0: return 0;
521 case 1: return v->ob_digit[0];
522 }
523 while (--i >= 0) {
524 prev = x;
525 x = (x << PyLong_SHIFT) | v->ob_digit[i];
526 if ((x >> PyLong_SHIFT) != prev) {
527 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000528 "python int too large to convert "
529 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 }
533 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534}
535
Stefan Krahb77c6c62011-09-12 16:22:47 +0200536/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
537 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
539size_t
540PyLong_AsSize_t(PyObject *vv)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 register PyLongObject *v;
543 size_t x, prev;
544 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (vv == NULL) {
547 PyErr_BadInternalCall();
548 return (size_t) -1;
549 }
550 if (!PyLong_Check(vv)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return (size_t)-1;
553 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 v = (PyLongObject *)vv;
556 i = Py_SIZE(v);
557 x = 0;
558 if (i < 0) {
559 PyErr_SetString(PyExc_OverflowError,
560 "can't convert negative value to size_t");
561 return (size_t) -1;
562 }
563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
567 while (--i >= 0) {
568 prev = x;
569 x = (x << PyLong_SHIFT) | v->ob_digit[i];
570 if ((x >> PyLong_SHIFT) != prev) {
571 PyErr_SetString(PyExc_OverflowError,
572 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200573 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
576 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000577}
578
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579/* Get a C unsigned long int from a long int object, ignoring the high bits.
580 Returns -1 and sets an error condition if an error occurs. */
581
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582static unsigned long
583_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 register PyLongObject *v;
586 unsigned long x;
587 Py_ssize_t i;
588 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (vv == NULL || !PyLong_Check(vv)) {
591 PyErr_BadInternalCall();
592 return (unsigned long) -1;
593 }
594 v = (PyLongObject *)vv;
595 i = Py_SIZE(v);
596 switch (i) {
597 case 0: return 0;
598 case 1: return v->ob_digit[0];
599 }
600 sign = 1;
601 x = 0;
602 if (i < 0) {
603 sign = -1;
604 i = -i;
605 }
606 while (--i >= 0) {
607 x = (x << PyLong_SHIFT) | v->ob_digit[i];
608 }
609 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000610}
611
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612unsigned long
613PyLong_AsUnsignedLongMask(register PyObject *op)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyNumberMethods *nb;
616 PyLongObject *lo;
617 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op && PyLong_Check(op))
620 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
623 nb->nb_int == NULL) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (unsigned long)-1;
626 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 lo = (PyLongObject*) (*nb->nb_int) (op);
629 if (lo == NULL)
630 return (unsigned long)-1;
631 if (PyLong_Check(lo)) {
632 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
633 Py_DECREF(lo);
634 if (PyErr_Occurred())
635 return (unsigned long)-1;
636 return val;
637 }
638 else
639 {
640 Py_DECREF(lo);
641 PyErr_SetString(PyExc_TypeError,
642 "nb_int should return int object");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645}
646
Tim Peters5b8132f2003-01-31 15:52:05 +0000647int
648_PyLong_Sign(PyObject *vv)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 assert(v != NULL);
653 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000656}
657
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658size_t
659_PyLong_NumBits(PyObject *vv)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *v = (PyLongObject *)vv;
662 size_t result = 0;
663 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
667 ndigits = ABS(Py_SIZE(v));
668 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
669 if (ndigits > 0) {
670 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100671 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100673 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 do {
675 ++result;
676 if (result == 0)
677 goto Overflow;
678 msd >>= 1;
679 } while (msd);
680 }
681 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682
Mark Dickinson22b20182010-05-10 21:27:53 +0000683 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
685 "to express in a platform size_t");
686 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000687}
688
Tim Peters2a9b3672001-06-11 21:23:58 +0000689PyObject *
690_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000692{
Mark Dickinson22b20182010-05-10 21:27:53 +0000693 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int incr; /* direction to move pstartbyte */
695 const unsigned char* pendbyte; /* MSB of bytes */
696 size_t numsignificantbytes; /* number of bytes that matter */
697 Py_ssize_t ndigits; /* number of Python long digits */
698 PyLongObject* v; /* result */
699 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (n == 0)
702 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (little_endian) {
705 pstartbyte = bytes;
706 pendbyte = bytes + n - 1;
707 incr = 1;
708 }
709 else {
710 pstartbyte = bytes + n - 1;
711 pendbyte = bytes;
712 incr = -1;
713 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (is_signed)
716 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200719 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 is positive, and leading 0xff bytes if negative. */
721 {
722 size_t i;
723 const unsigned char* p = pendbyte;
724 const int pincr = -incr; /* search MSB to LSB */
725 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 for (i = 0; i < n; ++i, p += pincr) {
728 if (*p != insignficant)
729 break;
730 }
731 numsignificantbytes = n - i;
732 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
733 actually has 2 significant bytes. OTOH, 0xff0001 ==
734 -0x00ffff, so we wouldn't *need* to bump it there; but we
735 do for 0xffff = -0x0001. To be safe without bothering to
736 check every case, bump it regardless. */
737 if (is_signed && numsignificantbytes < n)
738 ++numsignificantbytes;
739 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* How many Python long digits do we need? We have
742 8*numsignificantbytes bits, and each Python long digit has
743 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
744 /* catch overflow before it happens */
745 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
746 PyErr_SetString(PyExc_OverflowError,
747 "byte array too long to convert to int");
748 return NULL;
749 }
750 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
751 v = _PyLong_New(ndigits);
752 if (v == NULL)
753 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Copy the bits over. The tricky parts are computing 2's-comp on
756 the fly for signed numbers, and dealing with the mismatch between
757 8-bit bytes and (probably) 15-bit Python digits.*/
758 {
759 size_t i;
760 twodigits carry = 1; /* for 2's-comp calculation */
761 twodigits accum = 0; /* sliding register */
762 unsigned int accumbits = 0; /* number of bits in accum */
763 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
766 twodigits thisbyte = *p;
767 /* Compute correction for 2's comp, if needed. */
768 if (is_signed) {
769 thisbyte = (0xff ^ thisbyte) + carry;
770 carry = thisbyte >> 8;
771 thisbyte &= 0xff;
772 }
773 /* Because we're going LSB to MSB, thisbyte is
774 more significant than what's already in accum,
775 so needs to be prepended to accum. */
776 accum |= (twodigits)thisbyte << accumbits;
777 accumbits += 8;
778 if (accumbits >= PyLong_SHIFT) {
779 /* There's enough to fill a Python digit. */
780 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000781 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 ++idigit;
783 accum >>= PyLong_SHIFT;
784 accumbits -= PyLong_SHIFT;
785 assert(accumbits < PyLong_SHIFT);
786 }
787 }
788 assert(accumbits < PyLong_SHIFT);
789 if (accumbits) {
790 assert(idigit < ndigits);
791 v->ob_digit[idigit] = (digit)accum;
792 ++idigit;
793 }
794 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 Py_SIZE(v) = is_signed ? -idigit : idigit;
797 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000798}
799
800int
801_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 unsigned char* bytes, size_t n,
803 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000806 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000808 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
810 digit carry; /* for computing 2's-comp */
811 size_t j; /* # bytes filled */
812 unsigned char* p; /* pointer to next byte in bytes */
813 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (Py_SIZE(v) < 0) {
818 ndigits = -(Py_SIZE(v));
819 if (!is_signed) {
820 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000821 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return -1;
823 }
824 do_twos_comp = 1;
825 }
826 else {
827 ndigits = Py_SIZE(v);
828 do_twos_comp = 0;
829 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (little_endian) {
832 p = bytes;
833 pincr = 1;
834 }
835 else {
836 p = bytes + n - 1;
837 pincr = -1;
838 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Copy over all the Python digits.
841 It's crucial that every Python digit except for the MSD contribute
842 exactly PyLong_SHIFT bits to the total, so first assert that the long is
843 normalized. */
844 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
845 j = 0;
846 accum = 0;
847 accumbits = 0;
848 carry = do_twos_comp ? 1 : 0;
849 for (i = 0; i < ndigits; ++i) {
850 digit thisdigit = v->ob_digit[i];
851 if (do_twos_comp) {
852 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
853 carry = thisdigit >> PyLong_SHIFT;
854 thisdigit &= PyLong_MASK;
855 }
856 /* Because we're going LSB to MSB, thisdigit is more
857 significant than what's already in accum, so needs to be
858 prepended to accum. */
859 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* The most-significant digit may be (probably is) at least
862 partly empty. */
863 if (i == ndigits - 1) {
864 /* Count # of sign bits -- they needn't be stored,
865 * although for signed conversion we need later to
866 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000867 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 while (s != 0) {
869 s >>= 1;
870 accumbits++;
871 }
872 }
873 else
874 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Store as many bytes as possible. */
877 while (accumbits >= 8) {
878 if (j >= n)
879 goto Overflow;
880 ++j;
881 *p = (unsigned char)(accum & 0xff);
882 p += pincr;
883 accumbits -= 8;
884 accum >>= 8;
885 }
886 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Store the straggler (if any). */
889 assert(accumbits < 8);
890 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
891 if (accumbits > 0) {
892 if (j >= n)
893 goto Overflow;
894 ++j;
895 if (do_twos_comp) {
896 /* Fill leading bits of the byte with sign bits
897 (appropriately pretending that the long had an
898 infinite supply of sign bits). */
899 accum |= (~(twodigits)0) << accumbits;
900 }
901 *p = (unsigned char)(accum & 0xff);
902 p += pincr;
903 }
904 else if (j == n && n > 0 && is_signed) {
905 /* The main loop filled the byte array exactly, so the code
906 just above didn't get to ensure there's a sign bit, and the
907 loop below wouldn't add one either. Make sure a sign bit
908 exists. */
909 unsigned char msb = *(p - pincr);
910 int sign_bit_set = msb >= 0x80;
911 assert(accumbits == 0);
912 if (sign_bit_set == do_twos_comp)
913 return 0;
914 else
915 goto Overflow;
916 }
Tim Peters05607ad2001-06-13 21:01:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Fill remaining bytes with copies of the sign bit. */
919 {
920 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
921 for ( ; j < n; ++j, p += pincr)
922 *p = signbyte;
923 }
Tim Peters05607ad2001-06-13 21:01:27 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000926
Mark Dickinson22b20182010-05-10 21:27:53 +0000927 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
929 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000930
Tim Peters2a9b3672001-06-11 21:23:58 +0000931}
932
Mark Dickinson8d48b432011-10-23 20:47:14 +0100933/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000934
935PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000936PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000937{
Mark Dickinson91044792012-10-18 19:21:43 +0100938#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100939 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
940#else
941
Tim Peters70128a12001-06-16 08:48:40 +0000942#ifndef HAVE_LONG_LONG
943# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
944#endif
945#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000946# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000947#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100949#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000950
Guido van Rossum78694d91998-09-18 14:14:13 +0000951}
952
Mark Dickinson8d48b432011-10-23 20:47:14 +0100953/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000954
955void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000956PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000957{
Tim Peters70128a12001-06-16 08:48:40 +0000958#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
962 x = PyLong_AsLong(vv);
963 else
964 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000965#else
Tim Peters70128a12001-06-16 08:48:40 +0000966
967#ifndef HAVE_LONG_LONG
968# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
969#endif
970#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000971# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000972#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
976 x = PyLong_AsLongLong(vv);
977 else
978 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000979
980#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (x == -1 && PyErr_Occurred())
983 return NULL;
984 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000985}
986
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000987#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000988
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000990 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000991 */
992
Mark Dickinson22b20182010-05-10 21:27:53 +0000993#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000994
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996
997PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000998PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyLongObject *v;
1001 unsigned PY_LONG_LONG abs_ival;
1002 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1003 int ndigits = 0;
1004 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 CHECK_SMALL_INT(ival);
1007 if (ival < 0) {
1008 /* avoid signed overflow on negation; see comments
1009 in PyLong_FromLong above. */
1010 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1011 negative = 1;
1012 }
1013 else {
1014 abs_ival = (unsigned PY_LONG_LONG)ival;
1015 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Count the number of Python digits.
1018 We used to pick 5 ("big enough for anything"), but that's a
1019 waste of time and space given that 5*15 = 75 bits are rarely
1020 needed. */
1021 t = abs_ival;
1022 while (t) {
1023 ++ndigits;
1024 t >>= PyLong_SHIFT;
1025 }
1026 v = _PyLong_New(ndigits);
1027 if (v != NULL) {
1028 digit *p = v->ob_digit;
1029 Py_SIZE(v) = negative ? -ndigits : ndigits;
1030 t = abs_ival;
1031 while (t) {
1032 *p++ = (digit)(t & PyLong_MASK);
1033 t >>= PyLong_SHIFT;
1034 }
1035 }
1036 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037}
1038
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyLongObject *v;
1045 unsigned PY_LONG_LONG t;
1046 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (ival < PyLong_BASE)
1049 return PyLong_FromLong((long)ival);
1050 /* Count the number of Python digits. */
1051 t = (unsigned PY_LONG_LONG)ival;
1052 while (t) {
1053 ++ndigits;
1054 t >>= PyLong_SHIFT;
1055 }
1056 v = _PyLong_New(ndigits);
1057 if (v != NULL) {
1058 digit *p = v->ob_digit;
1059 Py_SIZE(v) = ndigits;
1060 while (ival) {
1061 *p++ = (digit)(ival & PyLong_MASK);
1062 ival >>= PyLong_SHIFT;
1063 }
1064 }
1065 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066}
1067
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068/* Create a new long int object from a C Py_ssize_t. */
1069
1070PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001071PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyLongObject *v;
1074 size_t abs_ival;
1075 size_t t; /* unsigned so >> doesn't propagate sign bit */
1076 int ndigits = 0;
1077 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 CHECK_SMALL_INT(ival);
1080 if (ival < 0) {
1081 /* avoid signed overflow when ival = SIZE_T_MIN */
1082 abs_ival = (size_t)(-1-ival)+1;
1083 negative = 1;
1084 }
1085 else {
1086 abs_ival = (size_t)ival;
1087 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* Count the number of Python digits. */
1090 t = abs_ival;
1091 while (t) {
1092 ++ndigits;
1093 t >>= PyLong_SHIFT;
1094 }
1095 v = _PyLong_New(ndigits);
1096 if (v != NULL) {
1097 digit *p = v->ob_digit;
1098 Py_SIZE(v) = negative ? -ndigits : ndigits;
1099 t = abs_ival;
1100 while (t) {
1101 *p++ = (digit)(t & PyLong_MASK);
1102 t >>= PyLong_SHIFT;
1103 }
1104 }
1105 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106}
1107
1108/* Create a new long int object from a C size_t. */
1109
1110PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001111PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyLongObject *v;
1114 size_t t;
1115 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (ival < PyLong_BASE)
1118 return PyLong_FromLong((long)ival);
1119 /* Count the number of Python digits. */
1120 t = ival;
1121 while (t) {
1122 ++ndigits;
1123 t >>= PyLong_SHIFT;
1124 }
1125 v = _PyLong_New(ndigits);
1126 if (v != NULL) {
1127 digit *p = v->ob_digit;
1128 Py_SIZE(v) = ndigits;
1129 while (ival) {
1130 *p++ = (digit)(ival & PyLong_MASK);
1131 ival >>= PyLong_SHIFT;
1132 }
1133 }
1134 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135}
1136
Mark Dickinson8d48b432011-10-23 20:47:14 +01001137/* Get a C long long int from a long int object or any object that has an
1138 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001139
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001140PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001141PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyLongObject *v;
1144 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (vv == NULL) {
1148 PyErr_BadInternalCall();
1149 return -1;
1150 }
1151 if (!PyLong_Check(vv)) {
1152 PyNumberMethods *nb;
1153 PyObject *io;
1154 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1155 nb->nb_int == NULL) {
1156 PyErr_SetString(PyExc_TypeError, "an integer is required");
1157 return -1;
1158 }
1159 io = (*nb->nb_int) (vv);
1160 if (io == NULL)
1161 return -1;
1162 if (PyLong_Check(io)) {
1163 bytes = PyLong_AsLongLong(io);
1164 Py_DECREF(io);
1165 return bytes;
1166 }
1167 Py_DECREF(io);
1168 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1169 return -1;
1170 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 v = (PyLongObject*)vv;
1173 switch(Py_SIZE(v)) {
1174 case -1: return -(sdigit)v->ob_digit[0];
1175 case 0: return 0;
1176 case 1: return v->ob_digit[0];
1177 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001178 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001179 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1182 if (res < 0)
1183 return (PY_LONG_LONG)-1;
1184 else
1185 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001186}
1187
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001188/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001189 Return -1 and set an error if overflow occurs. */
1190
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001191unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001192PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyLongObject *v;
1195 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001197
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001198 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyErr_BadInternalCall();
1200 return (unsigned PY_LONG_LONG)-1;
1201 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001202 if (!PyLong_Check(vv)) {
1203 PyErr_SetString(PyExc_TypeError, "an integer is required");
1204 return (unsigned PY_LONG_LONG)-1;
1205 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 v = (PyLongObject*)vv;
1208 switch(Py_SIZE(v)) {
1209 case 0: return 0;
1210 case 1: return v->ob_digit[0];
1211 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001212
Mark Dickinson22b20182010-05-10 21:27:53 +00001213 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001214 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1217 if (res < 0)
1218 return (unsigned PY_LONG_LONG)res;
1219 else
1220 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001221}
Tim Petersd1a7da62001-06-13 00:35:57 +00001222
Thomas Hellera4ea6032003-04-17 18:55:45 +00001223/* Get a C unsigned long int from a long int object, ignoring the high bits.
1224 Returns -1 and sets an error condition if an error occurs. */
1225
Guido van Rossumddefaf32007-01-14 03:31:43 +00001226static unsigned PY_LONG_LONG
1227_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 register PyLongObject *v;
1230 unsigned PY_LONG_LONG x;
1231 Py_ssize_t i;
1232 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (vv == NULL || !PyLong_Check(vv)) {
1235 PyErr_BadInternalCall();
1236 return (unsigned long) -1;
1237 }
1238 v = (PyLongObject *)vv;
1239 switch(Py_SIZE(v)) {
1240 case 0: return 0;
1241 case 1: return v->ob_digit[0];
1242 }
1243 i = Py_SIZE(v);
1244 sign = 1;
1245 x = 0;
1246 if (i < 0) {
1247 sign = -1;
1248 i = -i;
1249 }
1250 while (--i >= 0) {
1251 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1252 }
1253 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001254}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001255
1256unsigned PY_LONG_LONG
1257PyLong_AsUnsignedLongLongMask(register PyObject *op)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyNumberMethods *nb;
1260 PyLongObject *lo;
1261 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (op && PyLong_Check(op))
1264 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1267 nb->nb_int == NULL) {
1268 PyErr_SetString(PyExc_TypeError, "an integer is required");
1269 return (unsigned PY_LONG_LONG)-1;
1270 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 lo = (PyLongObject*) (*nb->nb_int) (op);
1273 if (lo == NULL)
1274 return (unsigned PY_LONG_LONG)-1;
1275 if (PyLong_Check(lo)) {
1276 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1277 Py_DECREF(lo);
1278 if (PyErr_Occurred())
1279 return (unsigned PY_LONG_LONG)-1;
1280 return val;
1281 }
1282 else
1283 {
1284 Py_DECREF(lo);
1285 PyErr_SetString(PyExc_TypeError,
1286 "nb_int should return int object");
1287 return (unsigned PY_LONG_LONG)-1;
1288 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289}
Tim Petersd1a7da62001-06-13 00:35:57 +00001290
Mark Dickinson8d48b432011-10-23 20:47:14 +01001291/* Get a C long long int from a long int object or any object that has an
1292 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001293
Mark Dickinson8d48b432011-10-23 20:47:14 +01001294 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1295 the result. Otherwise *overflow is 0.
1296
1297 For other errors (e.g., TypeError), return -1 and set an error condition.
1298 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001299*/
1300
1301PY_LONG_LONG
1302PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* This version by Tim Peters */
1305 register PyLongObject *v;
1306 unsigned PY_LONG_LONG x, prev;
1307 PY_LONG_LONG res;
1308 Py_ssize_t i;
1309 int sign;
1310 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 *overflow = 0;
1313 if (vv == NULL) {
1314 PyErr_BadInternalCall();
1315 return -1;
1316 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (!PyLong_Check(vv)) {
1319 PyNumberMethods *nb;
1320 nb = vv->ob_type->tp_as_number;
1321 if (nb == NULL || nb->nb_int == NULL) {
1322 PyErr_SetString(PyExc_TypeError,
1323 "an integer is required");
1324 return -1;
1325 }
1326 vv = (*nb->nb_int) (vv);
1327 if (vv == NULL)
1328 return -1;
1329 do_decref = 1;
1330 if (!PyLong_Check(vv)) {
1331 Py_DECREF(vv);
1332 PyErr_SetString(PyExc_TypeError,
1333 "nb_int should return int object");
1334 return -1;
1335 }
1336 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 res = -1;
1339 v = (PyLongObject *)vv;
1340 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 switch (i) {
1343 case -1:
1344 res = -(sdigit)v->ob_digit[0];
1345 break;
1346 case 0:
1347 res = 0;
1348 break;
1349 case 1:
1350 res = v->ob_digit[0];
1351 break;
1352 default:
1353 sign = 1;
1354 x = 0;
1355 if (i < 0) {
1356 sign = -1;
1357 i = -(i);
1358 }
1359 while (--i >= 0) {
1360 prev = x;
1361 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1362 if ((x >> PyLong_SHIFT) != prev) {
1363 *overflow = sign;
1364 goto exit;
1365 }
1366 }
1367 /* Haven't lost any bits, but casting to long requires extra
1368 * care (see comment above).
1369 */
1370 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1371 res = (PY_LONG_LONG)x * sign;
1372 }
1373 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1374 res = PY_LLONG_MIN;
1375 }
1376 else {
1377 *overflow = sign;
1378 /* res is already set to -1 */
1379 }
1380 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001381 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (do_decref) {
1383 Py_DECREF(vv);
1384 }
1385 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001386}
1387
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001388#endif /* HAVE_LONG_LONG */
1389
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001390#define CHECK_BINOP(v,w) \
1391 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001392 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1393 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001394 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001395
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001396/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1397 2**k if d is nonzero, else 0. */
1398
1399static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1401 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001402};
1403
1404static int
1405bits_in_digit(digit d)
1406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 int d_bits = 0;
1408 while (d >= 32) {
1409 d_bits += 6;
1410 d >>= 6;
1411 }
1412 d_bits += (int)BitLengthTable[d];
1413 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001414}
1415
Tim Peters877a2122002-08-12 05:09:36 +00001416/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1417 * is modified in place, by adding y to it. Carries are propagated as far as
1418 * x[m-1], and the remaining carry (0 or 1) is returned.
1419 */
1420static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001421v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 Py_ssize_t i;
1424 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 assert(m >= n);
1427 for (i = 0; i < n; ++i) {
1428 carry += x[i] + y[i];
1429 x[i] = carry & PyLong_MASK;
1430 carry >>= PyLong_SHIFT;
1431 assert((carry & 1) == carry);
1432 }
1433 for (; carry && i < m; ++i) {
1434 carry += x[i];
1435 x[i] = carry & PyLong_MASK;
1436 carry >>= PyLong_SHIFT;
1437 assert((carry & 1) == carry);
1438 }
1439 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001440}
1441
1442/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1443 * is modified in place, by subtracting y from it. Borrows are propagated as
1444 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1445 */
1446static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001447v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Py_ssize_t i;
1450 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 assert(m >= n);
1453 for (i = 0; i < n; ++i) {
1454 borrow = x[i] - y[i] - borrow;
1455 x[i] = borrow & PyLong_MASK;
1456 borrow >>= PyLong_SHIFT;
1457 borrow &= 1; /* keep only 1 sign bit */
1458 }
1459 for (; borrow && i < m; ++i) {
1460 borrow = x[i] - borrow;
1461 x[i] = borrow & PyLong_MASK;
1462 borrow >>= PyLong_SHIFT;
1463 borrow &= 1;
1464 }
1465 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001466}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001467
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001468/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1469 * result in z[0:m], and return the d bits shifted out of the top.
1470 */
1471static digit
1472v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 Py_ssize_t i;
1475 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 assert(0 <= d && d < PyLong_SHIFT);
1478 for (i=0; i < m; i++) {
1479 twodigits acc = (twodigits)a[i] << d | carry;
1480 z[i] = (digit)acc & PyLong_MASK;
1481 carry = (digit)(acc >> PyLong_SHIFT);
1482 }
1483 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001484}
1485
1486/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1487 * result in z[0:m], and return the d bits shifted out of the bottom.
1488 */
1489static digit
1490v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_ssize_t i;
1493 digit carry = 0;
1494 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 assert(0 <= d && d < PyLong_SHIFT);
1497 for (i=m; i-- > 0;) {
1498 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1499 carry = (digit)acc & mask;
1500 z[i] = (digit)(acc >> d);
1501 }
1502 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001503}
1504
Tim Peters212e6142001-07-14 12:23:19 +00001505/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1506 in pout, and returning the remainder. pin and pout point at the LSD.
1507 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001508 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001509 immutable. */
1510
1511static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001512inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 assert(n > 0 && n <= PyLong_MASK);
1517 pin += size;
1518 pout += size;
1519 while (--size >= 0) {
1520 digit hi;
1521 rem = (rem << PyLong_SHIFT) | *--pin;
1522 *--pout = hi = (digit)(rem / n);
1523 rem -= (twodigits)hi * n;
1524 }
1525 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001526}
1527
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001528/* Divide a long integer by a digit, returning both the quotient
1529 (as function result) and the remainder (through *prem).
1530 The sign of a is ignored; n should not be zero. */
1531
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001532static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001533divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 const Py_ssize_t size = ABS(Py_SIZE(a));
1536 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(n > 0 && n <= PyLong_MASK);
1539 z = _PyLong_New(size);
1540 if (z == NULL)
1541 return NULL;
1542 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1543 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001544}
1545
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001546/* Convert a long integer to a base 10 string. Returns a new non-shared
1547 string. (Return value is non-shared so that callers can modify the
1548 returned value if necessary.) */
1549
Victor Stinnerd3f08822012-05-29 12:57:52 +02001550static int
1551long_to_decimal_string_internal(PyObject *aa,
1552 PyObject **p_output,
1553 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyLongObject *scratch, *a;
1556 PyObject *str;
1557 Py_ssize_t size, strlen, size_a, i, j;
1558 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001560 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 a = (PyLongObject *)aa;
1563 if (a == NULL || !PyLong_Check(a)) {
1564 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001565 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 }
1567 size_a = ABS(Py_SIZE(a));
1568 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* quick and dirty upper bound for the number of digits
1571 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 But log2(a) < size_a * PyLong_SHIFT, and
1576 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1577 > 3 * _PyLong_DECIMAL_SHIFT
1578 */
1579 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1580 PyErr_SetString(PyExc_OverflowError,
1581 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001582 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 }
1584 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1585 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1586 scratch = _PyLong_New(size);
1587 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001588 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* convert array of base _PyLong_BASE digits in pin to an array of
1591 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1592 Volume 2 (3rd edn), section 4.4, Method 1b). */
1593 pin = a->ob_digit;
1594 pout = scratch->ob_digit;
1595 size = 0;
1596 for (i = size_a; --i >= 0; ) {
1597 digit hi = pin[i];
1598 for (j = 0; j < size; j++) {
1599 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1600 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1601 pout[j] = (digit)(z - (twodigits)hi *
1602 _PyLong_DECIMAL_BASE);
1603 }
1604 while (hi) {
1605 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1606 hi /= _PyLong_DECIMAL_BASE;
1607 }
1608 /* check for keyboard interrupt */
1609 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001610 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001611 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001612 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 }
1614 /* pout should have at least one digit, so that the case when a = 0
1615 works correctly */
1616 if (size == 0)
1617 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 /* calculate exact length of output string, and allocate */
1620 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1621 tenpow = 10;
1622 rem = pout[size-1];
1623 while (rem >= tenpow) {
1624 tenpow *= 10;
1625 strlen++;
1626 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001627 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001628 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1629 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001630 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001631 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001632 kind = writer->kind;
1633 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001635 else {
1636 str = PyUnicode_New(strlen, '9');
1637 if (str == NULL) {
1638 Py_DECREF(scratch);
1639 return -1;
1640 }
1641 kind = PyUnicode_KIND(str);
1642 }
1643
1644#define WRITE_DIGITS(TYPE) \
1645 do { \
1646 if (writer) \
1647 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1648 else \
1649 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1650 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001651 /* pout[0] through pout[size-2] contribute exactly \
1652 _PyLong_DECIMAL_SHIFT digits each */ \
1653 for (i=0; i < size - 1; i++) { \
1654 rem = pout[i]; \
1655 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1656 *--p = '0' + rem % 10; \
1657 rem /= 10; \
1658 } \
1659 } \
1660 /* pout[size-1]: always produce at least one decimal digit */ \
1661 rem = pout[i]; \
1662 do { \
1663 *--p = '0' + rem % 10; \
1664 rem /= 10; \
1665 } while (rem != 0); \
1666 \
1667 /* and sign */ \
1668 if (negative) \
1669 *--p = '-'; \
1670 \
1671 /* check we've counted correctly */ \
1672 if (writer) \
1673 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1674 else \
1675 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1676 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001679 if (kind == PyUnicode_1BYTE_KIND) {
1680 Py_UCS1 *p;
1681 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001683 else if (kind == PyUnicode_2BYTE_KIND) {
1684 Py_UCS2 *p;
1685 WRITE_DIGITS(Py_UCS2);
1686 }
1687 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001688 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001689 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001690 WRITE_DIGITS(Py_UCS4);
1691 }
1692#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001695 if (writer) {
1696 writer->pos += strlen;
1697 }
1698 else {
1699 assert(_PyUnicode_CheckConsistency(str, 1));
1700 *p_output = (PyObject *)str;
1701 }
1702 return 0;
1703}
1704
1705static PyObject *
1706long_to_decimal_string(PyObject *aa)
1707{
1708 PyObject *v;
1709 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1710 return NULL;
1711 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001712}
1713
Mark Dickinsoncd068122009-09-18 14:53:08 +00001714/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001715 which should be one of 2, 8 or 16. Return a string object.
1716 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1717 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001718
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719static int
1720long_format_binary(PyObject *aa, int base, int alternate,
1721 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001724 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001725 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001728 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001730
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (a == NULL || !PyLong_Check(a)) {
1733 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001734 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 }
1736 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001737 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* Compute a rough upper bound for the length of the string */
1740 switch (base) {
1741 case 16:
1742 bits = 4;
1743 break;
1744 case 8:
1745 bits = 3;
1746 break;
1747 case 2:
1748 bits = 1;
1749 break;
1750 default:
1751 assert(0); /* shouldn't ever get here */
1752 bits = 0; /* to silence gcc warning */
1753 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001754
Mark Dickinsone2846542012-04-20 21:21:24 +01001755 /* Compute exact length 'sz' of output string. */
1756 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001757 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001758 }
1759 else {
1760 Py_ssize_t size_a_in_bits;
1761 /* Ensure overflow doesn't occur during computation of sz. */
1762 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1763 PyErr_SetString(PyExc_OverflowError,
1764 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001765 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001766 }
1767 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1768 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001769 /* Allow 1 character for a '-' sign. */
1770 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1771 }
1772 if (alternate) {
1773 /* 2 characters for prefix */
1774 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001775 }
1776
Victor Stinnerd3f08822012-05-29 12:57:52 +02001777 if (writer) {
1778 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1779 return -1;
1780 kind = writer->kind;
1781 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 }
1783 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001784 v = PyUnicode_New(sz, 'x');
1785 if (v == NULL)
1786 return -1;
1787 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001789
Victor Stinnerd3f08822012-05-29 12:57:52 +02001790#define WRITE_DIGITS(TYPE) \
1791 do { \
1792 if (writer) \
1793 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1794 else \
1795 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1796 \
1797 if (size_a == 0) { \
1798 *--p = '0'; \
1799 } \
1800 else { \
1801 /* JRH: special case for power-of-2 bases */ \
1802 twodigits accum = 0; \
1803 int accumbits = 0; /* # of bits in accum */ \
1804 Py_ssize_t i; \
1805 for (i = 0; i < size_a; ++i) { \
1806 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1807 accumbits += PyLong_SHIFT; \
1808 assert(accumbits >= bits); \
1809 do { \
1810 char cdigit; \
1811 cdigit = (char)(accum & (base - 1)); \
1812 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1813 *--p = cdigit; \
1814 accumbits -= bits; \
1815 accum >>= bits; \
1816 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1817 } \
1818 } \
1819 \
1820 if (alternate) { \
1821 if (base == 16) \
1822 *--p = 'x'; \
1823 else if (base == 8) \
1824 *--p = 'o'; \
1825 else /* (base == 2) */ \
1826 *--p = 'b'; \
1827 *--p = '0'; \
1828 } \
1829 if (negative) \
1830 *--p = '-'; \
1831 if (writer) \
1832 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1833 else \
1834 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1835 } while (0)
1836
1837 if (kind == PyUnicode_1BYTE_KIND) {
1838 Py_UCS1 *p;
1839 WRITE_DIGITS(Py_UCS1);
1840 }
1841 else if (kind == PyUnicode_2BYTE_KIND) {
1842 Py_UCS2 *p;
1843 WRITE_DIGITS(Py_UCS2);
1844 }
1845 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001846 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001847 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001848 WRITE_DIGITS(Py_UCS4);
1849 }
1850#undef WRITE_DIGITS
1851
1852 if (writer) {
1853 writer->pos += sz;
1854 }
1855 else {
1856 assert(_PyUnicode_CheckConsistency(v, 1));
1857 *p_output = v;
1858 }
1859 return 0;
1860}
1861
1862PyObject *
1863_PyLong_Format(PyObject *obj, int base)
1864{
1865 PyObject *str;
1866 int err;
1867 if (base == 10)
1868 err = long_to_decimal_string_internal(obj, &str, NULL);
1869 else
1870 err = long_format_binary(obj, base, 1, &str, NULL);
1871 if (err == -1)
1872 return NULL;
1873 return str;
1874}
1875
1876int
1877_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1878 PyObject *obj,
1879 int base, int alternate)
1880{
1881 if (base == 10)
1882 return long_to_decimal_string_internal(obj, NULL, writer);
1883 else
1884 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001885}
1886
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887/* Table of digit values for 8-bit string -> integer conversion.
1888 * '0' maps to 0, ..., '9' maps to 9.
1889 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1890 * All other indices map to 37.
1891 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001892 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001893 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001894unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1896 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1897 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1898 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1899 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1900 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1901 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1902 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1903 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1904 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1905 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1906 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1907 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1908 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1909 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1910 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911};
1912
1913/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001914 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1915 * non-digit (which may be *str!). A normalized long is returned.
1916 * The point to this routine is that it takes time linear in the number of
1917 * string characters.
1918 */
1919static PyLongObject *
1920long_from_binary_base(char **str, int base)
1921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 char *p = *str;
1923 char *start = p;
1924 int bits_per_char;
1925 Py_ssize_t n;
1926 PyLongObject *z;
1927 twodigits accum;
1928 int bits_in_accum;
1929 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1932 n = base;
1933 for (bits_per_char = -1; n; ++bits_per_char)
1934 n >>= 1;
1935 /* n <- total # of bits needed, while setting p to end-of-string */
1936 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1937 ++p;
1938 *str = p;
1939 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1940 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1941 if (n / bits_per_char < p - start) {
1942 PyErr_SetString(PyExc_ValueError,
1943 "int string too large to convert");
1944 return NULL;
1945 }
1946 n = n / PyLong_SHIFT;
1947 z = _PyLong_New(n);
1948 if (z == NULL)
1949 return NULL;
1950 /* Read string from right, and fill in long from left; i.e.,
1951 * from least to most significant in both.
1952 */
1953 accum = 0;
1954 bits_in_accum = 0;
1955 pdigit = z->ob_digit;
1956 while (--p >= start) {
1957 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1958 assert(k >= 0 && k < base);
1959 accum |= (twodigits)k << bits_in_accum;
1960 bits_in_accum += bits_per_char;
1961 if (bits_in_accum >= PyLong_SHIFT) {
1962 *pdigit++ = (digit)(accum & PyLong_MASK);
1963 assert(pdigit - z->ob_digit <= n);
1964 accum >>= PyLong_SHIFT;
1965 bits_in_accum -= PyLong_SHIFT;
1966 assert(bits_in_accum < PyLong_SHIFT);
1967 }
1968 }
1969 if (bits_in_accum) {
1970 assert(bits_in_accum <= PyLong_SHIFT);
1971 *pdigit++ = (digit)accum;
1972 assert(pdigit - z->ob_digit <= n);
1973 }
1974 while (pdigit - z->ob_digit < n)
1975 *pdigit++ = 0;
1976 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001977}
1978
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001979PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001980PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 int sign = 1, error_if_nonzero = 0;
1983 char *start, *orig_str = str;
1984 PyLongObject *z = NULL;
1985 PyObject *strobj;
1986 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if ((base != 0 && base < 2) || base > 36) {
1989 PyErr_SetString(PyExc_ValueError,
1990 "int() arg 2 must be >= 2 and <= 36");
1991 return NULL;
1992 }
1993 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1994 str++;
1995 if (*str == '+')
1996 ++str;
1997 else if (*str == '-') {
1998 ++str;
1999 sign = -1;
2000 }
2001 if (base == 0) {
2002 if (str[0] != '0')
2003 base = 10;
2004 else if (str[1] == 'x' || str[1] == 'X')
2005 base = 16;
2006 else if (str[1] == 'o' || str[1] == 'O')
2007 base = 8;
2008 else if (str[1] == 'b' || str[1] == 'B')
2009 base = 2;
2010 else {
2011 /* "old" (C-style) octal literal, now invalid.
2012 it might still be zero though */
2013 error_if_nonzero = 1;
2014 base = 10;
2015 }
2016 }
2017 if (str[0] == '0' &&
2018 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2019 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2020 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2021 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 start = str;
2024 if ((base & (base - 1)) == 0)
2025 z = long_from_binary_base(&str, base);
2026 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002027/***
2028Binary bases can be converted in time linear in the number of digits, because
2029Python's representation base is binary. Other bases (including decimal!) use
2030the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002031
Thomas Wouters477c8d52006-05-27 19:21:47 +00002032First some math: the largest integer that can be expressed in N base-B digits
2033is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2034case number of Python digits needed to hold it is the smallest integer n s.t.
2035
2036 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2037 BASE**n >= B**N [taking logs to base BASE]
2038 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2039
2040The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2041this quickly. A Python long with that much space is reserved near the start,
2042and the result is computed into it.
2043
2044The input string is actually treated as being in base base**i (i.e., i digits
2045are processed at a time), where two more static arrays hold:
2046
2047 convwidth_base[base] = the largest integer i such that base**i <= BASE
2048 convmultmax_base[base] = base ** convwidth_base[base]
2049
2050The first of these is the largest i such that i consecutive input digits
2051must fit in a single Python digit. The second is effectively the input
2052base we're really using.
2053
2054Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2055convmultmax_base[base], the result is "simply"
2056
2057 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2058
2059where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002060
2061Error analysis: as above, the number of Python digits `n` needed is worst-
2062case
2063
2064 n >= N * log(B)/log(BASE)
2065
2066where `N` is the number of input digits in base `B`. This is computed via
2067
2068 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2069
2070below. Two numeric concerns are how much space this can waste, and whether
2071the computed result can be too small. To be concrete, assume BASE = 2**15,
2072which is the default (and it's unlikely anyone changes that).
2073
2074Waste isn't a problem: provided the first input digit isn't 0, the difference
2075between the worst-case input with N digits and the smallest input with N
2076digits is about a factor of B, but B is small compared to BASE so at most
2077one allocated Python digit can remain unused on that count. If
2078N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2079and adding 1 returns a result 1 larger than necessary. However, that can't
2080happen: whenever B is a power of 2, long_from_binary_base() is called
2081instead, and it's impossible for B**i to be an integer power of 2**15 when
2082B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2083an exact integer when B is not a power of 2, since B**i has a prime factor
2084other than 2 in that case, but (2**15)**j's only prime factor is 2).
2085
2086The computed result can be too small if the true value of N*log(B)/log(BASE)
2087is a little bit larger than an exact integer, but due to roundoff errors (in
2088computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2089yields a numeric result a little less than that integer. Unfortunately, "how
2090close can a transcendental function get to an integer over some range?"
2091questions are generally theoretically intractable. Computer analysis via
2092continued fractions is practical: expand log(B)/log(BASE) via continued
2093fractions, giving a sequence i/j of "the best" rational approximations. Then
2094j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2095we can get very close to being in trouble, but very rarely. For example,
209676573 is a denominator in one of the continued-fraction approximations to
2097log(10)/log(2**15), and indeed:
2098
2099 >>> log(10)/log(2**15)*76573
2100 16958.000000654003
2101
2102is very close to an integer. If we were working with IEEE single-precision,
2103rounding errors could kill us. Finding worst cases in IEEE double-precision
2104requires better-than-double-precision log() functions, and Tim didn't bother.
2105Instead the code checks to see whether the allocated space is enough as each
2106new Python digit is added, and copies the whole thing to a larger long if not.
2107This should happen extremely rarely, and in fact I don't have a test case
2108that triggers it(!). Instead the code was tested by artificially allocating
2109just 1 digit at the start, so that the copying code was exercised for every
2110digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002111***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 register twodigits c; /* current input character */
2113 Py_ssize_t size_z;
2114 int i;
2115 int convwidth;
2116 twodigits convmultmax, convmult;
2117 digit *pz, *pzstop;
2118 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 static double log_base_BASE[37] = {0.0e0,};
2121 static int convwidth_base[37] = {0,};
2122 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (log_base_BASE[base] == 0.0) {
2125 twodigits convmax = base;
2126 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127
Mark Dickinson22b20182010-05-10 21:27:53 +00002128 log_base_BASE[base] = (log((double)base) /
2129 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 for (;;) {
2131 twodigits next = convmax * base;
2132 if (next > PyLong_BASE)
2133 break;
2134 convmax = next;
2135 ++i;
2136 }
2137 convmultmax_base[base] = convmax;
2138 assert(i > 0);
2139 convwidth_base[base] = i;
2140 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 /* Find length of the string of numeric characters. */
2143 scan = str;
2144 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2145 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* Create a long object that can contain the largest possible
2148 * integer with this base and length. Note that there's no
2149 * need to initialize z->ob_digit -- no slot is read up before
2150 * being stored into.
2151 */
2152 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2153 /* Uncomment next line to test exceedingly rare copy code */
2154 /* size_z = 1; */
2155 assert(size_z > 0);
2156 z = _PyLong_New(size_z);
2157 if (z == NULL)
2158 return NULL;
2159 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 /* `convwidth` consecutive input digits are treated as a single
2162 * digit in base `convmultmax`.
2163 */
2164 convwidth = convwidth_base[base];
2165 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Work ;-) */
2168 while (str < scan) {
2169 /* grab up to convwidth digits from the input string */
2170 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2171 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2172 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002173 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 assert(c < PyLong_BASE);
2175 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 convmult = convmultmax;
2178 /* Calculate the shift only if we couldn't get
2179 * convwidth digits.
2180 */
2181 if (i != convwidth) {
2182 convmult = base;
2183 for ( ; i > 1; --i)
2184 convmult *= base;
2185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 /* Multiply z by convmult, and add c. */
2188 pz = z->ob_digit;
2189 pzstop = pz + Py_SIZE(z);
2190 for (; pz < pzstop; ++pz) {
2191 c += (twodigits)*pz * convmult;
2192 *pz = (digit)(c & PyLong_MASK);
2193 c >>= PyLong_SHIFT;
2194 }
2195 /* carry off the current end? */
2196 if (c) {
2197 assert(c < PyLong_BASE);
2198 if (Py_SIZE(z) < size_z) {
2199 *pz = (digit)c;
2200 ++Py_SIZE(z);
2201 }
2202 else {
2203 PyLongObject *tmp;
2204 /* Extremely rare. Get more space. */
2205 assert(Py_SIZE(z) == size_z);
2206 tmp = _PyLong_New(size_z + 1);
2207 if (tmp == NULL) {
2208 Py_DECREF(z);
2209 return NULL;
2210 }
2211 memcpy(tmp->ob_digit,
2212 z->ob_digit,
2213 sizeof(digit) * size_z);
2214 Py_DECREF(z);
2215 z = tmp;
2216 z->ob_digit[size_z] = (digit)c;
2217 ++size_z;
2218 }
2219 }
2220 }
2221 }
2222 if (z == NULL)
2223 return NULL;
2224 if (error_if_nonzero) {
2225 /* reset the base to 0, else the exception message
2226 doesn't make too much sense */
2227 base = 0;
2228 if (Py_SIZE(z) != 0)
2229 goto onError;
2230 /* there might still be other problems, therefore base
2231 remains zero here for the same reason */
2232 }
2233 if (str == start)
2234 goto onError;
2235 if (sign < 0)
2236 Py_SIZE(z) = -(Py_SIZE(z));
2237 while (*str && isspace(Py_CHARMASK(*str)))
2238 str++;
2239 if (*str != '\0')
2240 goto onError;
2241 if (pend)
2242 *pend = str;
2243 long_normalize(z);
2244 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002245
Mark Dickinson22b20182010-05-10 21:27:53 +00002246 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 Py_XDECREF(z);
2248 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2249 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2250 if (strobj == NULL)
2251 return NULL;
2252 PyErr_Format(PyExc_ValueError,
2253 "invalid literal for int() with base %d: %R",
2254 base, strobj);
2255 Py_DECREF(strobj);
2256 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002257}
2258
2259PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002260PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002261{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002262 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2263 if (unicode == NULL)
2264 return NULL;
2265 v = PyLong_FromUnicodeObject(unicode, base);
2266 Py_DECREF(unicode);
2267 return v;
2268}
2269
2270PyObject *
2271PyLong_FromUnicodeObject(PyObject *u, int base)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002274 PyObject *asciidig;
2275 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002279 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002282 if (buffer == NULL) {
2283 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 return NULL;
2285 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002286 result = PyLong_FromString(buffer, &end, base);
2287 if (result != NULL && end != buffer + buflen) {
2288 PyErr_SetString(PyExc_ValueError,
2289 "null byte in argument for int()");
2290 Py_DECREF(result);
2291 result = NULL;
2292 }
2293 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002295}
2296
Tim Peters9f688bf2000-07-07 15:53:28 +00002297/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002298static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002300static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002301
2302/* Long division with remainder, top-level routine */
2303
Guido van Rossume32e0141992-01-19 16:31:05 +00002304static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002305long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2309 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (size_b == 0) {
2312 PyErr_SetString(PyExc_ZeroDivisionError,
2313 "integer division or modulo by zero");
2314 return -1;
2315 }
2316 if (size_a < size_b ||
2317 (size_a == size_b &&
2318 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2319 /* |a| < |b|. */
2320 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2321 if (*pdiv == NULL)
2322 return -1;
2323 Py_INCREF(a);
2324 *prem = (PyLongObject *) a;
2325 return 0;
2326 }
2327 if (size_b == 1) {
2328 digit rem = 0;
2329 z = divrem1(a, b->ob_digit[0], &rem);
2330 if (z == NULL)
2331 return -1;
2332 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2333 if (*prem == NULL) {
2334 Py_DECREF(z);
2335 return -1;
2336 }
2337 }
2338 else {
2339 z = x_divrem(a, b, prem);
2340 if (z == NULL)
2341 return -1;
2342 }
2343 /* Set the signs.
2344 The quotient z has the sign of a*b;
2345 the remainder r has the sign of a,
2346 so a = b*z + r. */
2347 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2348 NEGATE(z);
2349 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2350 NEGATE(*prem);
2351 *pdiv = maybe_small_long(z);
2352 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002353}
2354
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002355/* Unsigned long division with remainder -- the algorithm. The arguments v1
2356 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002359x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 PyLongObject *v, *w, *a;
2362 Py_ssize_t i, k, size_v, size_w;
2363 int d;
2364 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2365 twodigits vv;
2366 sdigit zhi;
2367 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2370 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2371 handle the special case when the initial estimate q for a quotient
2372 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2373 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* allocate space; w will also be used to hold the final remainder */
2376 size_v = ABS(Py_SIZE(v1));
2377 size_w = ABS(Py_SIZE(w1));
2378 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2379 v = _PyLong_New(size_v+1);
2380 if (v == NULL) {
2381 *prem = NULL;
2382 return NULL;
2383 }
2384 w = _PyLong_New(size_w);
2385 if (w == NULL) {
2386 Py_DECREF(v);
2387 *prem = NULL;
2388 return NULL;
2389 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2392 shift v1 left by the same amount. Results go into w and v. */
2393 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2394 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2395 assert(carry == 0);
2396 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2397 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2398 v->ob_digit[size_v] = carry;
2399 size_v++;
2400 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2403 at most (and usually exactly) k = size_v - size_w digits. */
2404 k = size_v - size_w;
2405 assert(k >= 0);
2406 a = _PyLong_New(k);
2407 if (a == NULL) {
2408 Py_DECREF(w);
2409 Py_DECREF(v);
2410 *prem = NULL;
2411 return NULL;
2412 }
2413 v0 = v->ob_digit;
2414 w0 = w->ob_digit;
2415 wm1 = w0[size_w-1];
2416 wm2 = w0[size_w-2];
2417 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2418 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2419 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002422 Py_DECREF(a);
2423 Py_DECREF(w);
2424 Py_DECREF(v);
2425 *prem = NULL;
2426 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002427 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 /* estimate quotient digit q; may overestimate by 1 (rare) */
2430 vtop = vk[size_w];
2431 assert(vtop <= wm1);
2432 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2433 q = (digit)(vv / wm1);
2434 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2435 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2436 | vk[size_w-2])) {
2437 --q;
2438 r += wm1;
2439 if (r >= PyLong_BASE)
2440 break;
2441 }
2442 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2445 zhi = 0;
2446 for (i = 0; i < size_w; ++i) {
2447 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2448 -PyLong_BASE * q <= z < PyLong_BASE */
2449 z = (sdigit)vk[i] + zhi -
2450 (stwodigits)q * (stwodigits)w0[i];
2451 vk[i] = (digit)z & PyLong_MASK;
2452 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002453 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 /* add w back if q was too large (this branch taken rarely) */
2457 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2458 if ((sdigit)vtop + zhi < 0) {
2459 carry = 0;
2460 for (i = 0; i < size_w; ++i) {
2461 carry += vk[i] + w0[i];
2462 vk[i] = carry & PyLong_MASK;
2463 carry >>= PyLong_SHIFT;
2464 }
2465 --q;
2466 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* store quotient digit */
2469 assert(q < PyLong_BASE);
2470 *--ak = q;
2471 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* unshift remainder; we reuse w to store the result */
2474 carry = v_rshift(w0, v0, size_w, d);
2475 assert(carry==0);
2476 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 *prem = long_normalize(w);
2479 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002480}
2481
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002482/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2483 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2484 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2485 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2486 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2487 -1.0. */
2488
2489/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2490#if DBL_MANT_DIG == 53
2491#define EXP2_DBL_MANT_DIG 9007199254740992.0
2492#else
2493#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2494#endif
2495
2496double
2497_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2500 /* See below for why x_digits is always large enough. */
2501 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2502 double dx;
2503 /* Correction term for round-half-to-even rounding. For a digit x,
2504 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2505 multiple of 4, rounding ties to a multiple of 8. */
2506 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 a_size = ABS(Py_SIZE(a));
2509 if (a_size == 0) {
2510 /* Special case for 0: significand 0.0, exponent 0. */
2511 *e = 0;
2512 return 0.0;
2513 }
2514 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2515 /* The following is an overflow-free version of the check
2516 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2517 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2518 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2519 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002520 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2524 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 Number of digits needed for result: write // for floor division.
2527 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2536 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2539 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2540 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 in both cases.
2547 */
2548 if (a_bits <= DBL_MANT_DIG + 2) {
2549 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2550 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2551 x_size = 0;
2552 while (x_size < shift_digits)
2553 x_digits[x_size++] = 0;
2554 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2555 (int)shift_bits);
2556 x_size += a_size;
2557 x_digits[x_size++] = rem;
2558 }
2559 else {
2560 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2561 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2562 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2563 a_size - shift_digits, (int)shift_bits);
2564 x_size = a_size - shift_digits;
2565 /* For correct rounding below, we need the least significant
2566 bit of x to be 'sticky' for this shift: if any of the bits
2567 shifted out was nonzero, we set the least significant bit
2568 of x. */
2569 if (rem)
2570 x_digits[0] |= 1;
2571 else
2572 while (shift_digits > 0)
2573 if (a->ob_digit[--shift_digits]) {
2574 x_digits[0] |= 1;
2575 break;
2576 }
2577 }
Victor Stinner63941882011-09-29 00:42:28 +02002578 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 /* Round, and convert to double. */
2581 x_digits[0] += half_even_correction[x_digits[0] & 7];
2582 dx = x_digits[--x_size];
2583 while (x_size > 0)
2584 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Rescale; make correction if result is 1.0. */
2587 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2588 if (dx == 1.0) {
2589 if (a_bits == PY_SSIZE_T_MAX)
2590 goto overflow;
2591 dx = 0.5;
2592 a_bits += 1;
2593 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 *e = a_bits;
2596 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002597
2598 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* exponent > PY_SSIZE_T_MAX */
2600 PyErr_SetString(PyExc_OverflowError,
2601 "huge integer: number of bits overflows a Py_ssize_t");
2602 *e = 0;
2603 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002604}
2605
2606/* Get a C double from a long int object. Rounds to the nearest double,
2607 using the round-half-to-even rule in the case of a tie. */
2608
2609double
2610PyLong_AsDouble(PyObject *v)
2611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_ssize_t exponent;
2613 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002615 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 PyErr_BadInternalCall();
2617 return -1.0;
2618 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002619 if (!PyLong_Check(v)) {
2620 PyErr_SetString(PyExc_TypeError, "an integer is required");
2621 return -1.0;
2622 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2624 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2625 PyErr_SetString(PyExc_OverflowError,
2626 "long int too large to convert to float");
2627 return -1.0;
2628 }
2629 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002630}
2631
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002632/* Methods */
2633
2634static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002635long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002638}
2639
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002640static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002641long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 if (Py_SIZE(a) != Py_SIZE(b)) {
2646 sign = Py_SIZE(a) - Py_SIZE(b);
2647 }
2648 else {
2649 Py_ssize_t i = ABS(Py_SIZE(a));
2650 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2651 ;
2652 if (i < 0)
2653 sign = 0;
2654 else {
2655 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2656 if (Py_SIZE(a) < 0)
2657 sign = -sign;
2658 }
2659 }
2660 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002661}
2662
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002663#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002665
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002666static PyObject *
2667long_richcompare(PyObject *self, PyObject *other, int op)
2668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 int result;
2670 PyObject *v;
2671 CHECK_BINOP(self, other);
2672 if (self == other)
2673 result = 0;
2674 else
2675 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2676 /* Convert the return value to a Boolean */
2677 switch (op) {
2678 case Py_EQ:
2679 v = TEST_COND(result == 0);
2680 break;
2681 case Py_NE:
2682 v = TEST_COND(result != 0);
2683 break;
2684 case Py_LE:
2685 v = TEST_COND(result <= 0);
2686 break;
2687 case Py_GE:
2688 v = TEST_COND(result >= 0);
2689 break;
2690 case Py_LT:
2691 v = TEST_COND(result == -1);
2692 break;
2693 case Py_GT:
2694 v = TEST_COND(result == 1);
2695 break;
2696 default:
2697 PyErr_BadArgument();
2698 return NULL;
2699 }
2700 Py_INCREF(v);
2701 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002702}
2703
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002704static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002705long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002706{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002707 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 Py_ssize_t i;
2709 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 i = Py_SIZE(v);
2712 switch(i) {
2713 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2714 case 0: return 0;
2715 case 1: return v->ob_digit[0];
2716 }
2717 sign = 1;
2718 x = 0;
2719 if (i < 0) {
2720 sign = -1;
2721 i = -(i);
2722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002724 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2725 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2726 _PyHASH_MODULUS.
2727
2728 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2729 amounts to a rotation of the bits of x. To see this, write
2730
2731 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2732
2733 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2734 PyLong_SHIFT bits of x (those that are shifted out of the
2735 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2736 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2737 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2738 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2739 congruent to y modulo _PyHASH_MODULUS. So
2740
2741 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2742
2743 The right-hand side is just the result of rotating the
2744 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2745 not all _PyHASH_BITS bits of x are 1s, the same is true
2746 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2747 the reduction of x*2**PyLong_SHIFT modulo
2748 _PyHASH_MODULUS. */
2749 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2750 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002752 if (x >= _PyHASH_MODULUS)
2753 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 }
2755 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002756 if (x == (Py_uhash_t)-1)
2757 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002758 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002759}
2760
2761
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002762/* Add the absolute values of two long integers. */
2763
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002764static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002765x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2768 PyLongObject *z;
2769 Py_ssize_t i;
2770 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 /* Ensure a is the larger of the two: */
2773 if (size_a < size_b) {
2774 { PyLongObject *temp = a; a = b; b = temp; }
2775 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002776 size_a = size_b;
2777 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 }
2779 z = _PyLong_New(size_a+1);
2780 if (z == NULL)
2781 return NULL;
2782 for (i = 0; i < size_b; ++i) {
2783 carry += a->ob_digit[i] + b->ob_digit[i];
2784 z->ob_digit[i] = carry & PyLong_MASK;
2785 carry >>= PyLong_SHIFT;
2786 }
2787 for (; i < size_a; ++i) {
2788 carry += a->ob_digit[i];
2789 z->ob_digit[i] = carry & PyLong_MASK;
2790 carry >>= PyLong_SHIFT;
2791 }
2792 z->ob_digit[i] = carry;
2793 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002794}
2795
2796/* Subtract the absolute values of two integers. */
2797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002798static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002799x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2802 PyLongObject *z;
2803 Py_ssize_t i;
2804 int sign = 1;
2805 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 /* Ensure a is the larger of the two: */
2808 if (size_a < size_b) {
2809 sign = -1;
2810 { PyLongObject *temp = a; a = b; b = temp; }
2811 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002812 size_a = size_b;
2813 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 }
2815 else if (size_a == size_b) {
2816 /* Find highest digit where a and b differ: */
2817 i = size_a;
2818 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2819 ;
2820 if (i < 0)
2821 return (PyLongObject *)PyLong_FromLong(0);
2822 if (a->ob_digit[i] < b->ob_digit[i]) {
2823 sign = -1;
2824 { PyLongObject *temp = a; a = b; b = temp; }
2825 }
2826 size_a = size_b = i+1;
2827 }
2828 z = _PyLong_New(size_a);
2829 if (z == NULL)
2830 return NULL;
2831 for (i = 0; i < size_b; ++i) {
2832 /* The following assumes unsigned arithmetic
2833 works module 2**N for some N>PyLong_SHIFT. */
2834 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2835 z->ob_digit[i] = borrow & PyLong_MASK;
2836 borrow >>= PyLong_SHIFT;
2837 borrow &= 1; /* Keep only one sign bit */
2838 }
2839 for (; i < size_a; ++i) {
2840 borrow = a->ob_digit[i] - borrow;
2841 z->ob_digit[i] = borrow & PyLong_MASK;
2842 borrow >>= PyLong_SHIFT;
2843 borrow &= 1; /* Keep only one sign bit */
2844 }
2845 assert(borrow == 0);
2846 if (sign < 0)
2847 NEGATE(z);
2848 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002849}
2850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002851static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002852long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2859 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2860 MEDIUM_VALUE(b));
2861 return result;
2862 }
2863 if (Py_SIZE(a) < 0) {
2864 if (Py_SIZE(b) < 0) {
2865 z = x_add(a, b);
2866 if (z != NULL && Py_SIZE(z) != 0)
2867 Py_SIZE(z) = -(Py_SIZE(z));
2868 }
2869 else
2870 z = x_sub(b, a);
2871 }
2872 else {
2873 if (Py_SIZE(b) < 0)
2874 z = x_sub(a, b);
2875 else
2876 z = x_add(a, b);
2877 }
2878 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002879}
2880
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002881static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002882long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2889 PyObject* r;
2890 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2891 return r;
2892 }
2893 if (Py_SIZE(a) < 0) {
2894 if (Py_SIZE(b) < 0)
2895 z = x_sub(a, b);
2896 else
2897 z = x_add(a, b);
2898 if (z != NULL && Py_SIZE(z) != 0)
2899 Py_SIZE(z) = -(Py_SIZE(z));
2900 }
2901 else {
2902 if (Py_SIZE(b) < 0)
2903 z = x_add(a, b);
2904 else
2905 z = x_sub(a, b);
2906 }
2907 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002908}
2909
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910/* Grade school multiplication, ignoring the signs.
2911 * Returns the absolute value of the product, or NULL if error.
2912 */
2913static PyLongObject *
2914x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyLongObject *z;
2917 Py_ssize_t size_a = ABS(Py_SIZE(a));
2918 Py_ssize_t size_b = ABS(Py_SIZE(b));
2919 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 z = _PyLong_New(size_a + size_b);
2922 if (z == NULL)
2923 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2926 if (a == b) {
2927 /* Efficient squaring per HAC, Algorithm 14.16:
2928 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2929 * Gives slightly less than a 2x speedup when a == b,
2930 * via exploiting that each entry in the multiplication
2931 * pyramid appears twice (except for the size_a squares).
2932 */
2933 for (i = 0; i < size_a; ++i) {
2934 twodigits carry;
2935 twodigits f = a->ob_digit[i];
2936 digit *pz = z->ob_digit + (i << 1);
2937 digit *pa = a->ob_digit + i + 1;
2938 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002941 Py_DECREF(z);
2942 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002943 });
Tim Peters0973b992004-08-29 22:16:50 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 carry = *pz + f * f;
2946 *pz++ = (digit)(carry & PyLong_MASK);
2947 carry >>= PyLong_SHIFT;
2948 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 /* Now f is added in twice in each column of the
2951 * pyramid it appears. Same as adding f<<1 once.
2952 */
2953 f <<= 1;
2954 while (pa < paend) {
2955 carry += *pz + *pa++ * f;
2956 *pz++ = (digit)(carry & PyLong_MASK);
2957 carry >>= PyLong_SHIFT;
2958 assert(carry <= (PyLong_MASK << 1));
2959 }
2960 if (carry) {
2961 carry += *pz;
2962 *pz++ = (digit)(carry & PyLong_MASK);
2963 carry >>= PyLong_SHIFT;
2964 }
2965 if (carry)
2966 *pz += (digit)(carry & PyLong_MASK);
2967 assert((carry >> PyLong_SHIFT) == 0);
2968 }
2969 }
2970 else { /* a is not the same as b -- gradeschool long mult */
2971 for (i = 0; i < size_a; ++i) {
2972 twodigits carry = 0;
2973 twodigits f = a->ob_digit[i];
2974 digit *pz = z->ob_digit + i;
2975 digit *pb = b->ob_digit;
2976 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002979 Py_DECREF(z);
2980 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002981 });
Tim Peters0973b992004-08-29 22:16:50 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 while (pb < pbend) {
2984 carry += *pz + *pb++ * f;
2985 *pz++ = (digit)(carry & PyLong_MASK);
2986 carry >>= PyLong_SHIFT;
2987 assert(carry <= PyLong_MASK);
2988 }
2989 if (carry)
2990 *pz += (digit)(carry & PyLong_MASK);
2991 assert((carry >> PyLong_SHIFT) == 0);
2992 }
2993 }
2994 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002995}
2996
2997/* A helper for Karatsuba multiplication (k_mul).
2998 Takes a long "n" and an integer "size" representing the place to
2999 split, and sets low and high such that abs(n) == (high << size) + low,
3000 viewing the shift as being by digits. The sign bit is ignored, and
3001 the return values are >= 0.
3002 Returns 0 on success, -1 on failure.
3003*/
3004static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003005kmul_split(PyLongObject *n,
3006 Py_ssize_t size,
3007 PyLongObject **high,
3008 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 PyLongObject *hi, *lo;
3011 Py_ssize_t size_lo, size_hi;
3012 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 size_lo = MIN(size_n, size);
3015 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 if ((hi = _PyLong_New(size_hi)) == NULL)
3018 return -1;
3019 if ((lo = _PyLong_New(size_lo)) == NULL) {
3020 Py_DECREF(hi);
3021 return -1;
3022 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3025 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 *high = long_normalize(hi);
3028 *low = long_normalize(lo);
3029 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003030}
3031
Tim Peters60004642002-08-12 22:01:34 +00003032static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3033
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034/* Karatsuba multiplication. Ignores the input signs, and returns the
3035 * absolute value of the product (or NULL if error).
3036 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3037 */
3038static PyLongObject *
3039k_mul(PyLongObject *a, PyLongObject *b)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 Py_ssize_t asize = ABS(Py_SIZE(a));
3042 Py_ssize_t bsize = ABS(Py_SIZE(b));
3043 PyLongObject *ah = NULL;
3044 PyLongObject *al = NULL;
3045 PyLongObject *bh = NULL;
3046 PyLongObject *bl = NULL;
3047 PyLongObject *ret = NULL;
3048 PyLongObject *t1, *t2, *t3;
3049 Py_ssize_t shift; /* the number of digits we split off */
3050 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3053 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3054 * Then the original product is
3055 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3056 * By picking X to be a power of 2, "*X" is just shifting, and it's
3057 * been reduced to 3 multiplies on numbers half the size.
3058 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* We want to split based on the larger number; fiddle so that b
3061 * is largest.
3062 */
3063 if (asize > bsize) {
3064 t1 = a;
3065 a = b;
3066 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 i = asize;
3069 asize = bsize;
3070 bsize = i;
3071 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* Use gradeschool math when either number is too small. */
3074 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3075 if (asize <= i) {
3076 if (asize == 0)
3077 return (PyLongObject *)PyLong_FromLong(0);
3078 else
3079 return x_mul(a, b);
3080 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 /* If a is small compared to b, splitting on b gives a degenerate
3083 * case with ah==0, and Karatsuba may be (even much) less efficient
3084 * than "grade school" then. However, we can still win, by viewing
3085 * b as a string of "big digits", each of width a->ob_size. That
3086 * leads to a sequence of balanced calls to k_mul.
3087 */
3088 if (2 * asize <= bsize)
3089 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 /* Split a & b into hi & lo pieces. */
3092 shift = bsize >> 1;
3093 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3094 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 if (a == b) {
3097 bh = ah;
3098 bl = al;
3099 Py_INCREF(bh);
3100 Py_INCREF(bl);
3101 }
3102 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 /* The plan:
3105 * 1. Allocate result space (asize + bsize digits: that's always
3106 * enough).
3107 * 2. Compute ah*bh, and copy into result at 2*shift.
3108 * 3. Compute al*bl, and copy into result at 0. Note that this
3109 * can't overlap with #2.
3110 * 4. Subtract al*bl from the result, starting at shift. This may
3111 * underflow (borrow out of the high digit), but we don't care:
3112 * we're effectively doing unsigned arithmetic mod
3113 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3114 * borrows and carries out of the high digit can be ignored.
3115 * 5. Subtract ah*bh from the result, starting at shift.
3116 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3117 * at shift.
3118 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* 1. Allocate result space. */
3121 ret = _PyLong_New(asize + bsize);
3122 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003123#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* Fill with trash, to catch reference to uninitialized digits. */
3125 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003126#endif
Tim Peters44121a62002-08-12 06:17:58 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3129 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3130 assert(Py_SIZE(t1) >= 0);
3131 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3132 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3133 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 /* Zero-out the digits higher than the ah*bh copy. */
3136 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3137 if (i)
3138 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3139 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* 3. t2 <- al*bl, and copy into the low digits. */
3142 if ((t2 = k_mul(al, bl)) == NULL) {
3143 Py_DECREF(t1);
3144 goto fail;
3145 }
3146 assert(Py_SIZE(t2) >= 0);
3147 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3148 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 /* Zero out remaining digits. */
3151 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3152 if (i)
3153 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3156 * because it's fresher in cache.
3157 */
3158 i = Py_SIZE(ret) - shift; /* # digits after shift */
3159 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3160 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3163 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3166 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3167 Py_DECREF(ah);
3168 Py_DECREF(al);
3169 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 if (a == b) {
3172 t2 = t1;
3173 Py_INCREF(t2);
3174 }
3175 else if ((t2 = x_add(bh, bl)) == NULL) {
3176 Py_DECREF(t1);
3177 goto fail;
3178 }
3179 Py_DECREF(bh);
3180 Py_DECREF(bl);
3181 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 t3 = k_mul(t1, t2);
3184 Py_DECREF(t1);
3185 Py_DECREF(t2);
3186 if (t3 == NULL) goto fail;
3187 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 /* Add t3. It's not obvious why we can't run out of room here.
3190 * See the (*) comment after this function.
3191 */
3192 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3193 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003196
Mark Dickinson22b20182010-05-10 21:27:53 +00003197 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 Py_XDECREF(ret);
3199 Py_XDECREF(ah);
3200 Py_XDECREF(al);
3201 Py_XDECREF(bh);
3202 Py_XDECREF(bl);
3203 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003204}
3205
Tim Petersd6974a52002-08-13 20:37:51 +00003206/* (*) Why adding t3 can't "run out of room" above.
3207
Tim Petersab86c2b2002-08-15 20:06:00 +00003208Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3209to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003210
Tim Petersab86c2b2002-08-15 20:06:00 +000032111. For any integer i, i = c(i/2) + f(i/2). In particular,
3212 bsize = c(bsize/2) + f(bsize/2).
32132. shift = f(bsize/2)
32143. asize <= bsize
32154. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3216 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003217
Tim Petersab86c2b2002-08-15 20:06:00 +00003218We allocated asize + bsize result digits, and add t3 into them at an offset
3219of shift. This leaves asize+bsize-shift allocated digit positions for t3
3220to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3221asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003222
Tim Petersab86c2b2002-08-15 20:06:00 +00003223bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3224at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003225
Tim Petersab86c2b2002-08-15 20:06:00 +00003226If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3227digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3228most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003229
Tim Petersab86c2b2002-08-15 20:06:00 +00003230The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003231
Tim Petersab86c2b2002-08-15 20:06:00 +00003232 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003233
Tim Petersab86c2b2002-08-15 20:06:00 +00003234and we have asize + c(bsize/2) available digit positions. We need to show
3235this is always enough. An instance of c(bsize/2) cancels out in both, so
3236the question reduces to whether asize digits is enough to hold
3237(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3238then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3239asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003240digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003241asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003242c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3243is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3244bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003245
Tim Peters48d52c02002-08-14 17:07:32 +00003246Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3247clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3248ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003249*/
3250
Tim Peters60004642002-08-12 22:01:34 +00003251/* b has at least twice the digits of a, and a is big enough that Karatsuba
3252 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3253 * of slices, each with a->ob_size digits, and multiply the slices by a,
3254 * one at a time. This gives k_mul balanced inputs to work with, and is
3255 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003256 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003257 * single-width slice overlap between successive partial sums).
3258 */
3259static PyLongObject *
3260k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 const Py_ssize_t asize = ABS(Py_SIZE(a));
3263 Py_ssize_t bsize = ABS(Py_SIZE(b));
3264 Py_ssize_t nbdone; /* # of b digits already multiplied */
3265 PyLongObject *ret;
3266 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 assert(asize > KARATSUBA_CUTOFF);
3269 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 /* Allocate result space, and zero it out. */
3272 ret = _PyLong_New(asize + bsize);
3273 if (ret == NULL)
3274 return NULL;
3275 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 /* Successive slices of b are copied into bslice. */
3278 bslice = _PyLong_New(asize);
3279 if (bslice == NULL)
3280 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 nbdone = 0;
3283 while (bsize > 0) {
3284 PyLongObject *product;
3285 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 /* Multiply the next slice of b by a. */
3288 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3289 nbtouse * sizeof(digit));
3290 Py_SIZE(bslice) = nbtouse;
3291 product = k_mul(a, bslice);
3292 if (product == NULL)
3293 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* Add into result. */
3296 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3297 product->ob_digit, Py_SIZE(product));
3298 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 bsize -= nbtouse;
3301 nbdone += nbtouse;
3302 }
Tim Peters60004642002-08-12 22:01:34 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 Py_DECREF(bslice);
3305 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003306
Mark Dickinson22b20182010-05-10 21:27:53 +00003307 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 Py_DECREF(ret);
3309 Py_XDECREF(bslice);
3310 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003311}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003312
3313static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003314long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 /* fast path for single-digit multiplication */
3321 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3322 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003323#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003325#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 /* if we don't have long long then we're almost certainly
3327 using 15-bit digits, so v will fit in a long. In the
3328 unlikely event that we're using 30-bit digits on a platform
3329 without long long, a large v will just cause us to fall
3330 through to the general multiplication code below. */
3331 if (v >= LONG_MIN && v <= LONG_MAX)
3332 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003333#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 z = k_mul(a, b);
3337 /* Negate if exactly one of the inputs is negative. */
3338 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3339 NEGATE(z);
3340 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003341}
3342
Guido van Rossume32e0141992-01-19 16:31:05 +00003343/* The / and % operators are now defined in terms of divmod().
3344 The expression a mod b has the value a - b*floor(a/b).
3345 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003346 |a| by |b|, with the sign of a. This is also expressed
3347 as a - b*trunc(a/b), if trunc truncates towards zero.
3348 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 a b a rem b a mod b
3350 13 10 3 3
3351 -13 10 -3 7
3352 13 -10 3 -7
3353 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003354 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003355 have different signs. We then subtract one from the 'div'
3356 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003357
Tim Peters47e52ee2004-08-30 02:44:38 +00003358/* Compute
3359 * *pdiv, *pmod = divmod(v, w)
3360 * NULL can be passed for pdiv or pmod, in which case that part of
3361 * the result is simply thrown away. The caller owns a reference to
3362 * each of these it requests (does not pass NULL for).
3363 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003364static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003365l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 if (long_divrem(v, w, &div, &mod) < 0)
3371 return -1;
3372 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3373 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3374 PyLongObject *temp;
3375 PyLongObject *one;
3376 temp = (PyLongObject *) long_add(mod, w);
3377 Py_DECREF(mod);
3378 mod = temp;
3379 if (mod == NULL) {
3380 Py_DECREF(div);
3381 return -1;
3382 }
3383 one = (PyLongObject *) PyLong_FromLong(1L);
3384 if (one == NULL ||
3385 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3386 Py_DECREF(mod);
3387 Py_DECREF(div);
3388 Py_XDECREF(one);
3389 return -1;
3390 }
3391 Py_DECREF(one);
3392 Py_DECREF(div);
3393 div = temp;
3394 }
3395 if (pdiv != NULL)
3396 *pdiv = div;
3397 else
3398 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 if (pmod != NULL)
3401 *pmod = mod;
3402 else
3403 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003406}
3407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003408static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003409long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 CHECK_BINOP(a, b);
3414 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3415 div = NULL;
3416 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003417}
3418
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003419/* PyLong/PyLong -> float, with correctly rounded result. */
3420
3421#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3422#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3423
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003424static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003425long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 PyLongObject *a, *b, *x;
3428 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3429 digit mask, low;
3430 int inexact, negate, a_is_small, b_is_small;
3431 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 CHECK_BINOP(v, w);
3434 a = (PyLongObject *)v;
3435 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 /*
3438 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3441 1. choose a suitable integer 'shift'
3442 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3443 3. adjust x for correct rounding
3444 4. convert x to a double dx with the same value
3445 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3450 returns either 0.0 or -0.0, depending on the sign of b. For a and
3451 b both nonzero, ignore signs of a and b, and add the sign back in
3452 at the end. Now write a_bits and b_bits for the bit lengths of a
3453 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3454 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3459 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3460 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3461 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 1. The integer 'shift' is chosen so that x has the right number of
3466 bits for a double, plus two or three extra bits that will be used
3467 in the rounding decisions. Writing a_bits and b_bits for the
3468 number of significant bits in a and b respectively, a
3469 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 This is fine in the usual case, but if a/b is smaller than the
3474 smallest normal float then it can lead to double rounding on an
3475 IEEE 754 platform, giving incorrectly rounded results. So we
3476 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 2. The quantity x is computed by first shifting a (left -shift bits
3481 if shift <= 0, right shift bits if shift > 0) and then dividing by
3482 b. For both the shift and the division, we keep track of whether
3483 the result is inexact, in a flag 'inexact'; this information is
3484 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 With the choice of shift above, together with our assumption that
3487 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3488 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3491 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 For float representability, we need x/2**extra_bits <
3496 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3497 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 To round, we just modify the bottom digit of x in-place; this can
3502 end up giving a digit with value > PyLONG_MASK, but that's not a
3503 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 With the original choices for shift above, extra_bits will always
3506 be 2 or 3. Then rounding under the round-half-to-even rule, we
3507 round up iff the most significant of the extra bits is 1, and
3508 either: (a) the computation of x in step 2 had an inexact result,
3509 or (b) at least one other of the extra bits is 1, or (c) the least
3510 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 4. Conversion to a double is straightforward; all floating-point
3513 operations involved in the conversion are exact, so there's no
3514 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3517 The result will always be exactly representable as a double, except
3518 in the case that it overflows. To avoid dependence on the exact
3519 behaviour of ldexp on overflow, we check for overflow before
3520 applying ldexp. The result of ldexp is adjusted for sign before
3521 returning.
3522 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 /* Reduce to case where a and b are both positive. */
3525 a_size = ABS(Py_SIZE(a));
3526 b_size = ABS(Py_SIZE(b));
3527 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3528 if (b_size == 0) {
3529 PyErr_SetString(PyExc_ZeroDivisionError,
3530 "division by zero");
3531 goto error;
3532 }
3533 if (a_size == 0)
3534 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 /* Fast path for a and b small (exactly representable in a double).
3537 Relies on floating-point division being correctly rounded; results
3538 may be subject to double rounding on x86 machines that operate with
3539 the x87 FPU set to 64-bit precision. */
3540 a_is_small = a_size <= MANT_DIG_DIGITS ||
3541 (a_size == MANT_DIG_DIGITS+1 &&
3542 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3543 b_is_small = b_size <= MANT_DIG_DIGITS ||
3544 (b_size == MANT_DIG_DIGITS+1 &&
3545 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3546 if (a_is_small && b_is_small) {
3547 double da, db;
3548 da = a->ob_digit[--a_size];
3549 while (a_size > 0)
3550 da = da * PyLong_BASE + a->ob_digit[--a_size];
3551 db = b->ob_digit[--b_size];
3552 while (b_size > 0)
3553 db = db * PyLong_BASE + b->ob_digit[--b_size];
3554 result = da / db;
3555 goto success;
3556 }
Tim Peterse2a60002001-09-04 06:17:36 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 /* Catch obvious cases of underflow and overflow */
3559 diff = a_size - b_size;
3560 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3561 /* Extreme overflow */
3562 goto overflow;
3563 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3564 /* Extreme underflow */
3565 goto underflow_or_zero;
3566 /* Next line is now safe from overflowing a Py_ssize_t */
3567 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3568 bits_in_digit(b->ob_digit[b_size - 1]);
3569 /* Now diff = a_bits - b_bits. */
3570 if (diff > DBL_MAX_EXP)
3571 goto overflow;
3572 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3573 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 /* Choose value for shift; see comments for step 1 above. */
3576 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 /* x = abs(a * 2**-shift) */
3581 if (shift <= 0) {
3582 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3583 digit rem;
3584 /* x = a << -shift */
3585 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3586 /* In practice, it's probably impossible to end up
3587 here. Both a and b would have to be enormous,
3588 using close to SIZE_T_MAX bytes of memory each. */
3589 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003590 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 goto error;
3592 }
3593 x = _PyLong_New(a_size + shift_digits + 1);
3594 if (x == NULL)
3595 goto error;
3596 for (i = 0; i < shift_digits; i++)
3597 x->ob_digit[i] = 0;
3598 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3599 a_size, -shift % PyLong_SHIFT);
3600 x->ob_digit[a_size + shift_digits] = rem;
3601 }
3602 else {
3603 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3604 digit rem;
3605 /* x = a >> shift */
3606 assert(a_size >= shift_digits);
3607 x = _PyLong_New(a_size - shift_digits);
3608 if (x == NULL)
3609 goto error;
3610 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3611 a_size - shift_digits, shift % PyLong_SHIFT);
3612 /* set inexact if any of the bits shifted out is nonzero */
3613 if (rem)
3614 inexact = 1;
3615 while (!inexact && shift_digits > 0)
3616 if (a->ob_digit[--shift_digits])
3617 inexact = 1;
3618 }
3619 long_normalize(x);
3620 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3623 reference to x, so it's safe to modify it in-place. */
3624 if (b_size == 1) {
3625 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3626 b->ob_digit[0]);
3627 long_normalize(x);
3628 if (rem)
3629 inexact = 1;
3630 }
3631 else {
3632 PyLongObject *div, *rem;
3633 div = x_divrem(x, b, &rem);
3634 Py_DECREF(x);
3635 x = div;
3636 if (x == NULL)
3637 goto error;
3638 if (Py_SIZE(rem))
3639 inexact = 1;
3640 Py_DECREF(rem);
3641 }
3642 x_size = ABS(Py_SIZE(x));
3643 assert(x_size > 0); /* result of division is never zero */
3644 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 /* The number of extra bits that have to be rounded away. */
3647 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3648 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 /* Round by directly modifying the low digit of x. */
3651 mask = (digit)1 << (extra_bits - 1);
3652 low = x->ob_digit[0] | inexact;
3653 if (low & mask && low & (3*mask-1))
3654 low += mask;
3655 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 /* Convert x to a double dx; the conversion is exact. */
3658 dx = x->ob_digit[--x_size];
3659 while (x_size > 0)
3660 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3661 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* Check whether ldexp result will overflow a double. */
3664 if (shift + x_bits >= DBL_MAX_EXP &&
3665 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3666 goto overflow;
3667 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003668
3669 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003671
3672 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003674
3675 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 PyErr_SetString(PyExc_OverflowError,
3677 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003678 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003680}
3681
3682static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003683long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 CHECK_BINOP(a, b);
3688
3689 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3690 mod = NULL;
3691 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003692}
3693
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003694static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003695long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 PyLongObject *div, *mod;
3698 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3703 return NULL;
3704 }
3705 z = PyTuple_New(2);
3706 if (z != NULL) {
3707 PyTuple_SetItem(z, 0, (PyObject *) div);
3708 PyTuple_SetItem(z, 1, (PyObject *) mod);
3709 }
3710 else {
3711 Py_DECREF(div);
3712 Py_DECREF(mod);
3713 }
3714 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003715}
3716
Tim Peters47e52ee2004-08-30 02:44:38 +00003717/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003718static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003719long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3722 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 PyLongObject *z = NULL; /* accumulated result */
3725 Py_ssize_t i, j, k; /* counters */
3726 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 /* 5-ary values. If the exponent is large enough, table is
3729 * precomputed so that table[i] == a**i % c for i in range(32).
3730 */
3731 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3732 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 /* a, b, c = v, w, x */
3735 CHECK_BINOP(v, w);
3736 a = (PyLongObject*)v; Py_INCREF(a);
3737 b = (PyLongObject*)w; Py_INCREF(b);
3738 if (PyLong_Check(x)) {
3739 c = (PyLongObject *)x;
3740 Py_INCREF(x);
3741 }
3742 else if (x == Py_None)
3743 c = NULL;
3744 else {
3745 Py_DECREF(a);
3746 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003747 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 }
Tim Peters4c483c42001-09-05 06:24:58 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3751 if (c) {
3752 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003753 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 goto Error;
3755 }
3756 else {
3757 /* else return a float. This works because we know
3758 that this calls float_pow() which converts its
3759 arguments to double. */
3760 Py_DECREF(a);
3761 Py_DECREF(b);
3762 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3763 }
3764 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 if (c) {
3767 /* if modulus == 0:
3768 raise ValueError() */
3769 if (Py_SIZE(c) == 0) {
3770 PyErr_SetString(PyExc_ValueError,
3771 "pow() 3rd argument cannot be 0");
3772 goto Error;
3773 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 /* if modulus < 0:
3776 negativeOutput = True
3777 modulus = -modulus */
3778 if (Py_SIZE(c) < 0) {
3779 negativeOutput = 1;
3780 temp = (PyLongObject *)_PyLong_Copy(c);
3781 if (temp == NULL)
3782 goto Error;
3783 Py_DECREF(c);
3784 c = temp;
3785 temp = NULL;
3786 NEGATE(c);
3787 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 /* if modulus == 1:
3790 return 0 */
3791 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3792 z = (PyLongObject *)PyLong_FromLong(0L);
3793 goto Done;
3794 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 /* if base < 0:
3797 base = base % modulus
3798 Having the base positive just makes things easier. */
3799 if (Py_SIZE(a) < 0) {
3800 if (l_divmod(a, c, NULL, &temp) < 0)
3801 goto Error;
3802 Py_DECREF(a);
3803 a = temp;
3804 temp = NULL;
3805 }
3806 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 /* At this point a, b, and c are guaranteed non-negative UNLESS
3809 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 z = (PyLongObject *)PyLong_FromLong(1L);
3812 if (z == NULL)
3813 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 /* Perform a modular reduction, X = X % c, but leave X alone if c
3816 * is NULL.
3817 */
3818#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003819 do { \
3820 if (c != NULL) { \
3821 if (l_divmod(X, c, NULL, &temp) < 0) \
3822 goto Error; \
3823 Py_XDECREF(X); \
3824 X = temp; \
3825 temp = NULL; \
3826 } \
3827 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 /* Multiply two values, then reduce the result:
3830 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003831#define MULT(X, Y, result) \
3832 do { \
3833 temp = (PyLongObject *)long_mul(X, Y); \
3834 if (temp == NULL) \
3835 goto Error; \
3836 Py_XDECREF(result); \
3837 result = temp; \
3838 temp = NULL; \
3839 REDUCE(result); \
3840 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3843 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3844 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3845 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3846 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003849 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003851 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 }
3853 }
3854 }
3855 else {
3856 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3857 Py_INCREF(z); /* still holds 1L */
3858 table[0] = z;
3859 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003860 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3863 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3866 const int index = (bi >> j) & 0x1f;
3867 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003868 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003870 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 }
3872 }
3873 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 if (negativeOutput && (Py_SIZE(z) != 0)) {
3876 temp = (PyLongObject *)long_sub(z, c);
3877 if (temp == NULL)
3878 goto Error;
3879 Py_DECREF(z);
3880 z = temp;
3881 temp = NULL;
3882 }
3883 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003884
Mark Dickinson22b20182010-05-10 21:27:53 +00003885 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 if (z != NULL) {
3887 Py_DECREF(z);
3888 z = NULL;
3889 }
3890 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003891 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3893 for (i = 0; i < 32; ++i)
3894 Py_XDECREF(table[i]);
3895 }
3896 Py_DECREF(a);
3897 Py_DECREF(b);
3898 Py_XDECREF(c);
3899 Py_XDECREF(temp);
3900 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003901}
3902
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003903static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003904long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 /* Implement ~x as -(x+1) */
3907 PyLongObject *x;
3908 PyLongObject *w;
3909 if (ABS(Py_SIZE(v)) <=1)
3910 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3911 w = (PyLongObject *)PyLong_FromLong(1L);
3912 if (w == NULL)
3913 return NULL;
3914 x = (PyLongObject *) long_add(v, w);
3915 Py_DECREF(w);
3916 if (x == NULL)
3917 return NULL;
3918 Py_SIZE(x) = -(Py_SIZE(x));
3919 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003920}
3921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003922static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003923long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 PyLongObject *z;
3926 if (ABS(Py_SIZE(v)) <= 1)
3927 return PyLong_FromLong(-MEDIUM_VALUE(v));
3928 z = (PyLongObject *)_PyLong_Copy(v);
3929 if (z != NULL)
3930 Py_SIZE(z) = -(Py_SIZE(v));
3931 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003932}
3933
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003934static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003935long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 if (Py_SIZE(v) < 0)
3938 return long_neg(v);
3939 else
3940 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003941}
3942
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003943static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003944long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003947}
3948
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003949static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003950long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 PyLongObject *z = NULL;
3953 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3954 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 if (Py_SIZE(a) < 0) {
3959 /* Right shifting negative numbers is harder */
3960 PyLongObject *a1, *a2;
3961 a1 = (PyLongObject *) long_invert(a);
3962 if (a1 == NULL)
3963 goto rshift_error;
3964 a2 = (PyLongObject *) long_rshift(a1, b);
3965 Py_DECREF(a1);
3966 if (a2 == NULL)
3967 goto rshift_error;
3968 z = (PyLongObject *) long_invert(a2);
3969 Py_DECREF(a2);
3970 }
3971 else {
3972 shiftby = PyLong_AsSsize_t((PyObject *)b);
3973 if (shiftby == -1L && PyErr_Occurred())
3974 goto rshift_error;
3975 if (shiftby < 0) {
3976 PyErr_SetString(PyExc_ValueError,
3977 "negative shift count");
3978 goto rshift_error;
3979 }
3980 wordshift = shiftby / PyLong_SHIFT;
3981 newsize = ABS(Py_SIZE(a)) - wordshift;
3982 if (newsize <= 0)
3983 return PyLong_FromLong(0);
3984 loshift = shiftby % PyLong_SHIFT;
3985 hishift = PyLong_SHIFT - loshift;
3986 lomask = ((digit)1 << hishift) - 1;
3987 himask = PyLong_MASK ^ lomask;
3988 z = _PyLong_New(newsize);
3989 if (z == NULL)
3990 goto rshift_error;
3991 if (Py_SIZE(a) < 0)
3992 Py_SIZE(z) = -(Py_SIZE(z));
3993 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3994 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3995 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003996 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 }
3998 z = long_normalize(z);
3999 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004000 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004002
Guido van Rossumc6913e71991-11-19 20:26:46 +00004003}
4004
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004005static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004006long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 /* This version due to Tim Peters */
4009 PyLongObject *a = (PyLongObject*)v;
4010 PyLongObject *b = (PyLongObject*)w;
4011 PyLongObject *z = NULL;
4012 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4013 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 shiftby = PyLong_AsSsize_t((PyObject *)b);
4018 if (shiftby == -1L && PyErr_Occurred())
4019 goto lshift_error;
4020 if (shiftby < 0) {
4021 PyErr_SetString(PyExc_ValueError, "negative shift count");
4022 goto lshift_error;
4023 }
4024 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4025 wordshift = shiftby / PyLong_SHIFT;
4026 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 oldsize = ABS(Py_SIZE(a));
4029 newsize = oldsize + wordshift;
4030 if (remshift)
4031 ++newsize;
4032 z = _PyLong_New(newsize);
4033 if (z == NULL)
4034 goto lshift_error;
4035 if (Py_SIZE(a) < 0)
4036 NEGATE(z);
4037 for (i = 0; i < wordshift; i++)
4038 z->ob_digit[i] = 0;
4039 accum = 0;
4040 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4041 accum |= (twodigits)a->ob_digit[j] << remshift;
4042 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4043 accum >>= PyLong_SHIFT;
4044 }
4045 if (remshift)
4046 z->ob_digit[newsize-1] = (digit)accum;
4047 else
4048 assert(!accum);
4049 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004050 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004052}
4053
Mark Dickinson27a87a22009-10-25 20:43:34 +00004054/* Compute two's complement of digit vector a[0:m], writing result to
4055 z[0:m]. The digit vector a need not be normalized, but should not
4056 be entirely zero. a and z may point to the same digit vector. */
4057
4058static void
4059v_complement(digit *z, digit *a, Py_ssize_t m)
4060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 Py_ssize_t i;
4062 digit carry = 1;
4063 for (i = 0; i < m; ++i) {
4064 carry += a[i] ^ PyLong_MASK;
4065 z[i] = carry & PyLong_MASK;
4066 carry >>= PyLong_SHIFT;
4067 }
4068 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004069}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004070
4071/* Bitwise and/xor/or operations */
4072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004073static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004074long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004076 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 int nega, negb, negz;
4079 Py_ssize_t size_a, size_b, size_z, i;
4080 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 /* Bitwise operations for negative numbers operate as though
4083 on a two's complement representation. So convert arguments
4084 from sign-magnitude to two's complement, and convert the
4085 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 /* If a is negative, replace it by its two's complement. */
4088 size_a = ABS(Py_SIZE(a));
4089 nega = Py_SIZE(a) < 0;
4090 if (nega) {
4091 z = _PyLong_New(size_a);
4092 if (z == NULL)
4093 return NULL;
4094 v_complement(z->ob_digit, a->ob_digit, size_a);
4095 a = z;
4096 }
4097 else
4098 /* Keep reference count consistent. */
4099 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 /* Same for b. */
4102 size_b = ABS(Py_SIZE(b));
4103 negb = Py_SIZE(b) < 0;
4104 if (negb) {
4105 z = _PyLong_New(size_b);
4106 if (z == NULL) {
4107 Py_DECREF(a);
4108 return NULL;
4109 }
4110 v_complement(z->ob_digit, b->ob_digit, size_b);
4111 b = z;
4112 }
4113 else
4114 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 /* Swap a and b if necessary to ensure size_a >= size_b. */
4117 if (size_a < size_b) {
4118 z = a; a = b; b = z;
4119 size_z = size_a; size_a = size_b; size_b = size_z;
4120 negz = nega; nega = negb; negb = negz;
4121 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* JRH: The original logic here was to allocate the result value (z)
4124 as the longer of the two operands. However, there are some cases
4125 where the result is guaranteed to be shorter than that: AND of two
4126 positives, OR of two negatives: use the shorter number. AND with
4127 mixed signs: use the positive number. OR with mixed signs: use the
4128 negative number.
4129 */
4130 switch (op) {
4131 case '^':
4132 negz = nega ^ negb;
4133 size_z = size_a;
4134 break;
4135 case '&':
4136 negz = nega & negb;
4137 size_z = negb ? size_a : size_b;
4138 break;
4139 case '|':
4140 negz = nega | negb;
4141 size_z = negb ? size_b : size_a;
4142 break;
4143 default:
4144 PyErr_BadArgument();
4145 return NULL;
4146 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 /* We allow an extra digit if z is negative, to make sure that
4149 the final two's complement of z doesn't overflow. */
4150 z = _PyLong_New(size_z + negz);
4151 if (z == NULL) {
4152 Py_DECREF(a);
4153 Py_DECREF(b);
4154 return NULL;
4155 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 /* Compute digits for overlap of a and b. */
4158 switch(op) {
4159 case '&':
4160 for (i = 0; i < size_b; ++i)
4161 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4162 break;
4163 case '|':
4164 for (i = 0; i < size_b; ++i)
4165 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4166 break;
4167 case '^':
4168 for (i = 0; i < size_b; ++i)
4169 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4170 break;
4171 default:
4172 PyErr_BadArgument();
4173 return NULL;
4174 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 /* Copy any remaining digits of a, inverting if necessary. */
4177 if (op == '^' && negb)
4178 for (; i < size_z; ++i)
4179 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4180 else if (i < size_z)
4181 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4182 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 /* Complement result if negative. */
4185 if (negz) {
4186 Py_SIZE(z) = -(Py_SIZE(z));
4187 z->ob_digit[size_z] = PyLong_MASK;
4188 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4189 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 Py_DECREF(a);
4192 Py_DECREF(b);
4193 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004194}
4195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004196static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004197long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 PyObject *c;
4200 CHECK_BINOP(a, b);
4201 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4202 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004203}
4204
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004205static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004206long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 PyObject *c;
4209 CHECK_BINOP(a, b);
4210 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4211 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004212}
4213
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004214static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004215long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 PyObject *c;
4218 CHECK_BINOP(a, b);
4219 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4220 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004221}
4222
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004223static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004224long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 if (PyLong_CheckExact(v))
4227 Py_INCREF(v);
4228 else
4229 v = _PyLong_Copy((PyLongObject *)v);
4230 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004231}
4232
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004233static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004234long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 double result;
4237 result = PyLong_AsDouble(v);
4238 if (result == -1.0 && PyErr_Occurred())
4239 return NULL;
4240 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004241}
4242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004243static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004244long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004245
Tim Peters6d6c1a32001-08-02 04:15:00 +00004246static PyObject *
4247long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4248{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004249 PyObject *obase = NULL, *x = NULL;
4250 long base;
4251 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 if (type != &PyLong_Type)
4255 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004256 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4257 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 return NULL;
4259 if (x == NULL)
4260 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004261 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004263
4264 base = PyLong_AsLongAndOverflow(obase, &overflow);
4265 if (base == -1 && PyErr_Occurred())
4266 return NULL;
4267 if (overflow || (base != 0 && base < 2) || base > 36) {
4268 PyErr_SetString(PyExc_ValueError,
4269 "int() arg 2 must be >= 2 and <= 36");
4270 return NULL;
4271 }
4272
4273 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004274 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4276 /* Since PyLong_FromString doesn't have a length parameter,
4277 * check here for possible NULs in the string. */
4278 char *string;
4279 Py_ssize_t size = Py_SIZE(x);
4280 if (PyByteArray_Check(x))
4281 string = PyByteArray_AS_STRING(x);
4282 else
4283 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004284 if (strlen(string) != (size_t)size || !size) {
4285 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 x is a bytes or buffer, *and* a base is given. */
4287 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004288 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004289 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 return NULL;
4291 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004292 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 }
4294 else {
4295 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004296 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 return NULL;
4298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299}
4300
Guido van Rossumbef14172001-08-29 15:47:46 +00004301/* Wimpy, slow approach to tp_new calls for subtypes of long:
4302 first create a regular long from whatever arguments we got,
4303 then allocate a subtype instance and initialize it from
4304 the regular long. The regular long is then thrown away.
4305*/
4306static PyObject *
4307long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 PyLongObject *tmp, *newobj;
4310 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 assert(PyType_IsSubtype(type, &PyLong_Type));
4313 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4314 if (tmp == NULL)
4315 return NULL;
4316 assert(PyLong_CheckExact(tmp));
4317 n = Py_SIZE(tmp);
4318 if (n < 0)
4319 n = -n;
4320 newobj = (PyLongObject *)type->tp_alloc(type, n);
4321 if (newobj == NULL) {
4322 Py_DECREF(tmp);
4323 return NULL;
4324 }
4325 assert(PyLong_Check(newobj));
4326 Py_SIZE(newobj) = Py_SIZE(tmp);
4327 for (i = 0; i < n; i++)
4328 newobj->ob_digit[i] = tmp->ob_digit[i];
4329 Py_DECREF(tmp);
4330 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004331}
4332
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004333static PyObject *
4334long_getnewargs(PyLongObject *v)
4335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004337}
4338
Guido van Rossumb43daf72007-08-01 18:08:08 +00004339static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004340long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004342}
4343
4344static PyObject *
4345long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004347}
4348
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004349static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004350long__format__(PyObject *self, PyObject *args)
4351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004353 _PyUnicodeWriter writer;
4354 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4357 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004358
4359 _PyUnicodeWriter_Init(&writer, 0);
4360 ret = _PyLong_FormatAdvancedWriter(
4361 &writer,
4362 self,
4363 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4364 if (ret == -1) {
4365 _PyUnicodeWriter_Dealloc(&writer);
4366 return NULL;
4367 }
4368 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004369}
4370
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004371/* Return a pair (q, r) such that a = b * q + r, and
4372 abs(r) <= abs(b)/2, with equality possible only if q is even.
4373 In other words, q == a / b, rounded to the nearest integer using
4374 round-half-to-even. */
4375
4376PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004377_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004378{
4379 PyLongObject *quo = NULL, *rem = NULL;
4380 PyObject *one = NULL, *twice_rem, *result, *temp;
4381 int cmp, quo_is_odd, quo_is_neg;
4382
4383 /* Equivalent Python code:
4384
4385 def divmod_near(a, b):
4386 q, r = divmod(a, b)
4387 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4388 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4389 # positive, 2 * r < b if b negative.
4390 greater_than_half = 2*r > b if b > 0 else 2*r < b
4391 exactly_half = 2*r == b
4392 if greater_than_half or exactly_half and q % 2 == 1:
4393 q += 1
4394 r -= b
4395 return q, r
4396
4397 */
4398 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4399 PyErr_SetString(PyExc_TypeError,
4400 "non-integer arguments in division");
4401 return NULL;
4402 }
4403
4404 /* Do a and b have different signs? If so, quotient is negative. */
4405 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4406
4407 one = PyLong_FromLong(1L);
4408 if (one == NULL)
4409 return NULL;
4410
4411 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4412 goto error;
4413
4414 /* compare twice the remainder with the divisor, to see
4415 if we need to adjust the quotient and remainder */
4416 twice_rem = long_lshift((PyObject *)rem, one);
4417 if (twice_rem == NULL)
4418 goto error;
4419 if (quo_is_neg) {
4420 temp = long_neg((PyLongObject*)twice_rem);
4421 Py_DECREF(twice_rem);
4422 twice_rem = temp;
4423 if (twice_rem == NULL)
4424 goto error;
4425 }
4426 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4427 Py_DECREF(twice_rem);
4428
4429 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4430 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4431 /* fix up quotient */
4432 if (quo_is_neg)
4433 temp = long_sub(quo, (PyLongObject *)one);
4434 else
4435 temp = long_add(quo, (PyLongObject *)one);
4436 Py_DECREF(quo);
4437 quo = (PyLongObject *)temp;
4438 if (quo == NULL)
4439 goto error;
4440 /* and remainder */
4441 if (quo_is_neg)
4442 temp = long_add(rem, (PyLongObject *)b);
4443 else
4444 temp = long_sub(rem, (PyLongObject *)b);
4445 Py_DECREF(rem);
4446 rem = (PyLongObject *)temp;
4447 if (rem == NULL)
4448 goto error;
4449 }
4450
4451 result = PyTuple_New(2);
4452 if (result == NULL)
4453 goto error;
4454
4455 /* PyTuple_SET_ITEM steals references */
4456 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4457 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4458 Py_DECREF(one);
4459 return result;
4460
4461 error:
4462 Py_XDECREF(quo);
4463 Py_XDECREF(rem);
4464 Py_XDECREF(one);
4465 return NULL;
4466}
4467
Eric Smith8c663262007-08-25 02:26:07 +00004468static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004469long_round(PyObject *self, PyObject *args)
4470{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004471 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004472
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004473 /* To round an integer m to the nearest 10**n (n positive), we make use of
4474 * the divmod_near operation, defined by:
4475 *
4476 * divmod_near(a, b) = (q, r)
4477 *
4478 * where q is the nearest integer to the quotient a / b (the
4479 * nearest even integer in the case of a tie) and r == a - q * b.
4480 * Hence q * b = a - r is the nearest multiple of b to a,
4481 * preferring even multiples in the case of a tie.
4482 *
4483 * So the nearest multiple of 10**n to m is:
4484 *
4485 * m - divmod_near(m, 10**n)[1].
4486 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4488 return NULL;
4489 if (o_ndigits == NULL)
4490 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004491
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004492 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (ndigits == NULL)
4494 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004495
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004496 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (Py_SIZE(ndigits) >= 0) {
4498 Py_DECREF(ndigits);
4499 return long_long(self);
4500 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004501
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004502 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4503 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004505 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004507 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004508
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004509 result = PyLong_FromLong(10L);
4510 if (result == NULL) {
4511 Py_DECREF(ndigits);
4512 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004514
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004515 temp = long_pow(result, ndigits, Py_None);
4516 Py_DECREF(ndigits);
4517 Py_DECREF(result);
4518 result = temp;
4519 if (result == NULL)
4520 return NULL;
4521
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004522 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004523 Py_DECREF(result);
4524 result = temp;
4525 if (result == NULL)
4526 return NULL;
4527
4528 temp = long_sub((PyLongObject *)self,
4529 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4530 Py_DECREF(result);
4531 result = temp;
4532
4533 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004534}
4535
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004536static PyObject *
4537long_sizeof(PyLongObject *v)
4538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4542 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004543}
4544
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004545static PyObject *
4546long_bit_length(PyLongObject *v)
4547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 PyLongObject *result, *x, *y;
4549 Py_ssize_t ndigits, msd_bits = 0;
4550 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 assert(v != NULL);
4553 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 ndigits = ABS(Py_SIZE(v));
4556 if (ndigits == 0)
4557 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 msd = v->ob_digit[ndigits-1];
4560 while (msd >= 32) {
4561 msd_bits += 6;
4562 msd >>= 6;
4563 }
4564 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4567 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 /* expression above may overflow; use Python integers instead */
4570 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4571 if (result == NULL)
4572 return NULL;
4573 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4574 if (x == NULL)
4575 goto error;
4576 y = (PyLongObject *)long_mul(result, x);
4577 Py_DECREF(x);
4578 if (y == NULL)
4579 goto error;
4580 Py_DECREF(result);
4581 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4584 if (x == NULL)
4585 goto error;
4586 y = (PyLongObject *)long_add(result, x);
4587 Py_DECREF(x);
4588 if (y == NULL)
4589 goto error;
4590 Py_DECREF(result);
4591 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004594
Mark Dickinson22b20182010-05-10 21:27:53 +00004595 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 Py_DECREF(result);
4597 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004598}
4599
4600PyDoc_STRVAR(long_bit_length_doc,
4601"int.bit_length() -> int\n\
4602\n\
4603Number of bits necessary to represent self in binary.\n\
4604>>> bin(37)\n\
4605'0b100101'\n\
4606>>> (37).bit_length()\n\
46076");
4608
Christian Heimes53876d92008-04-19 00:31:39 +00004609#if 0
4610static PyObject *
4611long_is_finite(PyObject *v)
4612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004614}
4615#endif
4616
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004617
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004618static PyObject *
4619long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 PyObject *byteorder_str;
4622 PyObject *is_signed_obj = NULL;
4623 Py_ssize_t length;
4624 int little_endian;
4625 int is_signed;
4626 PyObject *bytes;
4627 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4630 &length, &byteorder_str,
4631 &is_signed_obj))
4632 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 if (args != NULL && Py_SIZE(args) > 2) {
4635 PyErr_SetString(PyExc_TypeError,
4636 "'signed' is a keyword-only argument");
4637 return NULL;
4638 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4641 little_endian = 1;
4642 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4643 little_endian = 0;
4644 else {
4645 PyErr_SetString(PyExc_ValueError,
4646 "byteorder must be either 'little' or 'big'");
4647 return NULL;
4648 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 if (is_signed_obj != NULL) {
4651 int cmp = PyObject_IsTrue(is_signed_obj);
4652 if (cmp < 0)
4653 return NULL;
4654 is_signed = cmp ? 1 : 0;
4655 }
4656 else {
4657 /* If the signed argument was omitted, use False as the
4658 default. */
4659 is_signed = 0;
4660 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 if (length < 0) {
4663 PyErr_SetString(PyExc_ValueError,
4664 "length argument must be non-negative");
4665 return NULL;
4666 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 bytes = PyBytes_FromStringAndSize(NULL, length);
4669 if (bytes == NULL)
4670 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4673 length, little_endian, is_signed) < 0) {
4674 Py_DECREF(bytes);
4675 return NULL;
4676 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004679}
4680
Mark Dickinson078c2532010-01-30 18:06:17 +00004681PyDoc_STRVAR(long_to_bytes_doc,
4682"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004683\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004684Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004685\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004687raised if the integer is not representable with the given number of\n\
4688bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004689\n\
4690The byteorder argument determines the byte order used to represent the\n\
4691integer. If byteorder is 'big', the most significant byte is at the\n\
4692beginning of the byte array. If byteorder is 'little', the most\n\
4693significant byte is at the end of the byte array. To request the native\n\
4694byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4695\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004696The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004698is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004699
4700static PyObject *
4701long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 PyObject *byteorder_str;
4704 PyObject *is_signed_obj = NULL;
4705 int little_endian;
4706 int is_signed;
4707 PyObject *obj;
4708 PyObject *bytes;
4709 PyObject *long_obj;
4710 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4713 &obj, &byteorder_str,
4714 &is_signed_obj))
4715 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (args != NULL && Py_SIZE(args) > 2) {
4718 PyErr_SetString(PyExc_TypeError,
4719 "'signed' is a keyword-only argument");
4720 return NULL;
4721 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4724 little_endian = 1;
4725 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4726 little_endian = 0;
4727 else {
4728 PyErr_SetString(PyExc_ValueError,
4729 "byteorder must be either 'little' or 'big'");
4730 return NULL;
4731 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 if (is_signed_obj != NULL) {
4734 int cmp = PyObject_IsTrue(is_signed_obj);
4735 if (cmp < 0)
4736 return NULL;
4737 is_signed = cmp ? 1 : 0;
4738 }
4739 else {
4740 /* If the signed argument was omitted, use False as the
4741 default. */
4742 is_signed = 0;
4743 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 bytes = PyObject_Bytes(obj);
4746 if (bytes == NULL)
4747 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 long_obj = _PyLong_FromByteArray(
4750 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4751 little_endian, is_signed);
4752 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 /* If from_bytes() was used on subclass, allocate new subclass
4755 * instance, initialize it with decoded long value and return it.
4756 */
4757 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4758 PyLongObject *newobj;
4759 int i;
4760 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 newobj = (PyLongObject *)type->tp_alloc(type, n);
4763 if (newobj == NULL) {
4764 Py_DECREF(long_obj);
4765 return NULL;
4766 }
4767 assert(PyLong_Check(newobj));
4768 Py_SIZE(newobj) = Py_SIZE(long_obj);
4769 for (i = 0; i < n; i++) {
4770 newobj->ob_digit[i] =
4771 ((PyLongObject *)long_obj)->ob_digit[i];
4772 }
4773 Py_DECREF(long_obj);
4774 return (PyObject *)newobj;
4775 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004778}
4779
Mark Dickinson078c2532010-01-30 18:06:17 +00004780PyDoc_STRVAR(long_from_bytes_doc,
4781"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4782\n\
4783Return the integer represented by the given array of bytes.\n\
4784\n\
4785The bytes argument must either support the buffer protocol or be an\n\
4786iterable object producing bytes. Bytes and bytearray are examples of\n\
4787built-in objects that support the buffer protocol.\n\
4788\n\
4789The byteorder argument determines the byte order used to represent the\n\
4790integer. If byteorder is 'big', the most significant byte is at the\n\
4791beginning of the byte array. If byteorder is 'little', the most\n\
4792significant byte is at the end of the byte array. To request the native\n\
4793byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4794\n\
4795The signed keyword-only argument indicates whether two's complement is\n\
4796used to represent the integer.");
4797
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004798static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4800 "Returns self, the complex conjugate of any int."},
4801 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4802 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004803#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4805 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004806#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 {"to_bytes", (PyCFunction)long_to_bytes,
4808 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4809 {"from_bytes", (PyCFunction)long_from_bytes,
4810 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4811 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4812 "Truncating an Integral returns itself."},
4813 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4814 "Flooring an Integral returns itself."},
4815 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4816 "Ceiling of an Integral returns itself."},
4817 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4818 "Rounding an Integral returns itself.\n"
4819 "Rounding with an ndigits argument also returns an integer."},
4820 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4821 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4822 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4823 "Returns size in memory, in bytes"},
4824 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004825};
4826
Guido van Rossumb43daf72007-08-01 18:08:08 +00004827static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004828 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004829 (getter)long_long, (setter)NULL,
4830 "the real part of a complex number",
4831 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004832 {"imag",
4833 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004834 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004835 NULL},
4836 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004837 (getter)long_long, (setter)NULL,
4838 "the numerator of a rational number in lowest terms",
4839 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004840 {"denominator",
4841 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004842 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004843 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004844 {NULL} /* Sentinel */
4845};
4846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004847PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004848"int(x=0) -> integer\n\
4849int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004850\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004851Convert a number or string to an integer, or return 0 if no arguments\n\
4852are given. If x is a number, return x.__int__(). For floating point\n\
4853numbers, this truncates towards zero.\n\
4854\n\
4855If x is not a number or if base is given, then x must be a string,\n\
4856bytes, or bytearray instance representing an integer literal in the\n\
4857given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4858by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4859Base 0 means to interpret the base from the string as an integer literal.\n\
4860>>> int('0b100', base=0)\n\
48614");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004862
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004863static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004864 (binaryfunc)long_add, /*nb_add*/
4865 (binaryfunc)long_sub, /*nb_subtract*/
4866 (binaryfunc)long_mul, /*nb_multiply*/
4867 long_mod, /*nb_remainder*/
4868 long_divmod, /*nb_divmod*/
4869 long_pow, /*nb_power*/
4870 (unaryfunc)long_neg, /*nb_negative*/
4871 (unaryfunc)long_long, /*tp_positive*/
4872 (unaryfunc)long_abs, /*tp_absolute*/
4873 (inquiry)long_bool, /*tp_bool*/
4874 (unaryfunc)long_invert, /*nb_invert*/
4875 long_lshift, /*nb_lshift*/
4876 (binaryfunc)long_rshift, /*nb_rshift*/
4877 long_and, /*nb_and*/
4878 long_xor, /*nb_xor*/
4879 long_or, /*nb_or*/
4880 long_long, /*nb_int*/
4881 0, /*nb_reserved*/
4882 long_float, /*nb_float*/
4883 0, /* nb_inplace_add */
4884 0, /* nb_inplace_subtract */
4885 0, /* nb_inplace_multiply */
4886 0, /* nb_inplace_remainder */
4887 0, /* nb_inplace_power */
4888 0, /* nb_inplace_lshift */
4889 0, /* nb_inplace_rshift */
4890 0, /* nb_inplace_and */
4891 0, /* nb_inplace_xor */
4892 0, /* nb_inplace_or */
4893 long_div, /* nb_floor_divide */
4894 long_true_divide, /* nb_true_divide */
4895 0, /* nb_inplace_floor_divide */
4896 0, /* nb_inplace_true_divide */
4897 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004898};
4899
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004900PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4902 "int", /* tp_name */
4903 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4904 sizeof(digit), /* tp_itemsize */
4905 long_dealloc, /* tp_dealloc */
4906 0, /* tp_print */
4907 0, /* tp_getattr */
4908 0, /* tp_setattr */
4909 0, /* tp_reserved */
4910 long_to_decimal_string, /* tp_repr */
4911 &long_as_number, /* tp_as_number */
4912 0, /* tp_as_sequence */
4913 0, /* tp_as_mapping */
4914 (hashfunc)long_hash, /* tp_hash */
4915 0, /* tp_call */
4916 long_to_decimal_string, /* tp_str */
4917 PyObject_GenericGetAttr, /* tp_getattro */
4918 0, /* tp_setattro */
4919 0, /* tp_as_buffer */
4920 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4921 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4922 long_doc, /* tp_doc */
4923 0, /* tp_traverse */
4924 0, /* tp_clear */
4925 long_richcompare, /* tp_richcompare */
4926 0, /* tp_weaklistoffset */
4927 0, /* tp_iter */
4928 0, /* tp_iternext */
4929 long_methods, /* tp_methods */
4930 0, /* tp_members */
4931 long_getset, /* tp_getset */
4932 0, /* tp_base */
4933 0, /* tp_dict */
4934 0, /* tp_descr_get */
4935 0, /* tp_descr_set */
4936 0, /* tp_dictoffset */
4937 0, /* tp_init */
4938 0, /* tp_alloc */
4939 long_new, /* tp_new */
4940 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004941};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004942
Mark Dickinsonbd792642009-03-18 20:06:12 +00004943static PyTypeObject Int_InfoType;
4944
4945PyDoc_STRVAR(int_info__doc__,
4946"sys.int_info\n\
4947\n\
4948A struct sequence that holds information about Python's\n\
4949internal representation of integers. The attributes are read only.");
4950
4951static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004953 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004955};
4956
4957static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 "sys.int_info", /* name */
4959 int_info__doc__, /* doc */
4960 int_info_fields, /* fields */
4961 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004962};
4963
4964PyObject *
4965PyLong_GetInfo(void)
4966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 PyObject* int_info;
4968 int field = 0;
4969 int_info = PyStructSequence_New(&Int_InfoType);
4970 if (int_info == NULL)
4971 return NULL;
4972 PyStructSequence_SET_ITEM(int_info, field++,
4973 PyLong_FromLong(PyLong_SHIFT));
4974 PyStructSequence_SET_ITEM(int_info, field++,
4975 PyLong_FromLong(sizeof(digit)));
4976 if (PyErr_Occurred()) {
4977 Py_CLEAR(int_info);
4978 return NULL;
4979 }
4980 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004981}
4982
Guido van Rossumddefaf32007-01-14 03:31:43 +00004983int
4984_PyLong_Init(void)
4985{
4986#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 int ival, size;
4988 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4991 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4992 if (Py_TYPE(v) == &PyLong_Type) {
4993 /* The element is already initialized, most likely
4994 * the Python interpreter was initialized before.
4995 */
4996 Py_ssize_t refcnt;
4997 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5000 _Py_NewReference(op);
5001 /* _Py_NewReference sets the ref count to 1 but
5002 * the ref count might be larger. Set the refcnt
5003 * to the original refcnt + 1 */
5004 Py_REFCNT(op) = refcnt + 1;
5005 assert(Py_SIZE(op) == size);
5006 assert(v->ob_digit[0] == abs(ival));
5007 }
5008 else {
5009 PyObject_INIT(v, &PyLong_Type);
5010 }
5011 Py_SIZE(v) = size;
5012 v->ob_digit[0] = abs(ival);
5013 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005014#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 /* initialize int_info */
5016 if (Int_InfoType.tp_name == 0)
5017 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005020}
5021
5022void
5023PyLong_Fini(void)
5024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 /* Integers are currently statically allocated. Py_DECREF is not
5026 needed, but Python must forget about the reference or multiple
5027 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005028#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 int i;
5030 PyLongObject *v = small_ints;
5031 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5032 _Py_DEC_REFTOTAL;
5033 _Py_ForgetReference((PyObject*)v);
5034 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005035#endif
5036}