blob: 850396b8efe1a3193d36b1e9739a3fc693870725 [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"
Mark Dickinsonbd792642009-03-18 20:06:12 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Guido van Rossumddefaf32007-01-14 03:31:43 +000013#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000015#endif
16#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000019
Mark Dickinsone4416742009-02-15 15:14:57 +000020/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
22 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
34int quick_int_allocs, quick_neg_int_allocs;
35#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Guido van Rossumddefaf32007-01-14 03:31:43 +000072/* If a freshly-allocated long is already shared, it must
73 be a small integer, so negating it must go to PyLong_FromLong */
74#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
76 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
77 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
78 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000079/* For long multiplication, use the O(N**2) school algorithm unless
80 * both operands contain more than KARATSUBA_CUTOFF digits (this
81 * being an internal Python long digit, in base BASE).
82 */
Tim Peters0973b992004-08-29 22:16:50 +000083#define KARATSUBA_CUTOFF 70
84#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000085
Tim Peters47e52ee2004-08-30 02:44:38 +000086/* For exponentiation, use the binary left-to-right algorithm
87 * unless the exponent contains more than FIVEARY_CUTOFF digits.
88 * In that case, do 5 bits at a time. The potential drawback is that
89 * a table of 2**5 intermediate results is computed.
90 */
91#define FIVEARY_CUTOFF 8
92
Tim Peters5af4e6c2002-08-12 02:31:19 +000093#undef MIN
94#undef MAX
95#define MAX(x, y) ((x) < (y) ? (y) : (x))
96#define MIN(x, y) ((x) > (y) ? (y) : (x))
97
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000098#define SIGCHECK(PyTryBlock) \
99 do { \
100 if (PyErr_CheckSignals()) PyTryBlock \
101 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000102
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000103/* Normalize (remove leading zeros from) a long int object.
104 Doesn't attempt to free the storage--in most cases, due to the nature
105 of the algorithms used, this could save at most be one word anyway. */
106
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000108long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 Py_ssize_t j = ABS(Py_SIZE(v));
111 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 while (i > 0 && v->ob_digit[i-1] == 0)
114 --i;
115 if (i != j)
116 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
117 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118}
119
120/* Allocate a new long int object with size digits.
121 Return NULL and set exception if we run out of memory. */
122
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000123#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000125
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000127_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyLongObject *result;
130 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
131 sizeof(digit)*size. Previous incarnations of this code used
132 sizeof(PyVarObject) instead of the offsetof, but this risks being
133 incorrect in the presence of padding between the PyVarObject header
134 and the digits. */
135 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
136 PyErr_SetString(PyExc_OverflowError,
137 "too many digits in integer");
138 return NULL;
139 }
140 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
141 size*sizeof(digit));
142 if (!result) {
143 PyErr_NoMemory();
144 return NULL;
145 }
146 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000147}
148
Tim Peters64b5ce32001-09-10 20:52:51 +0000149PyObject *
150_PyLong_Copy(PyLongObject *src)
151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 PyLongObject *result;
153 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 assert(src != NULL);
156 i = Py_SIZE(src);
157 if (i < 0)
158 i = -(i);
159 if (i < 2) {
160 sdigit ival = src->ob_digit[0];
161 if (Py_SIZE(src) < 0)
162 ival = -ival;
163 CHECK_SMALL_INT(ival);
164 }
165 result = _PyLong_New(i);
166 if (result != NULL) {
167 Py_SIZE(result) = Py_SIZE(src);
168 while (--i >= 0)
169 result->ob_digit[i] = src->ob_digit[i];
170 }
171 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000172}
173
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174/* Create a new long int object from a C long int */
175
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000177PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 PyLongObject *v;
180 unsigned long abs_ival;
181 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
182 int ndigits = 0;
183 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (ival < 0) {
188 /* negate: can't write this as abs_ival = -ival since that
189 invokes undefined behaviour when ival is LONG_MIN */
190 abs_ival = 0U-(unsigned long)ival;
191 sign = -1;
192 }
193 else {
194 abs_ival = (unsigned long)ival;
195 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* Fast path for single-digit ints */
198 if (!(abs_ival >> PyLong_SHIFT)) {
199 v = _PyLong_New(1);
200 if (v) {
201 Py_SIZE(v) = sign;
202 v->ob_digit[0] = Py_SAFE_DOWNCAST(
203 abs_ival, unsigned long, digit);
204 }
205 return (PyObject*)v;
206 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000207
Mark Dickinson249b8982009-04-27 19:41:00 +0000208#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* 2 digits */
210 if (!(abs_ival >> 2*PyLong_SHIFT)) {
211 v = _PyLong_New(2);
212 if (v) {
213 Py_SIZE(v) = 2*sign;
214 v->ob_digit[0] = Py_SAFE_DOWNCAST(
215 abs_ival & PyLong_MASK, unsigned long, digit);
216 v->ob_digit[1] = Py_SAFE_DOWNCAST(
217 abs_ival >> PyLong_SHIFT, unsigned long, digit);
218 }
219 return (PyObject*)v;
220 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000221#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Larger numbers: loop to determine number of digits */
224 t = abs_ival;
225 while (t) {
226 ++ndigits;
227 t >>= PyLong_SHIFT;
228 }
229 v = _PyLong_New(ndigits);
230 if (v != NULL) {
231 digit *p = v->ob_digit;
232 Py_SIZE(v) = ndigits*sign;
233 t = abs_ival;
234 while (t) {
235 *p++ = Py_SAFE_DOWNCAST(
236 t & PyLong_MASK, unsigned long, digit);
237 t >>= PyLong_SHIFT;
238 }
239 }
240 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241}
242
Guido van Rossum53756b11997-01-03 17:14:46 +0000243/* Create a new long int object from a C unsigned long int */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000246PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyLongObject *v;
249 unsigned long t;
250 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (ival < PyLong_BASE)
253 return PyLong_FromLong(ival);
254 /* Count the number of Python digits. */
255 t = (unsigned long)ival;
256 while (t) {
257 ++ndigits;
258 t >>= PyLong_SHIFT;
259 }
260 v = _PyLong_New(ndigits);
261 if (v != NULL) {
262 digit *p = v->ob_digit;
263 Py_SIZE(v) = ndigits;
264 while (ival) {
265 *p++ = (digit)(ival & PyLong_MASK);
266 ival >>= PyLong_SHIFT;
267 }
268 }
269 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000270}
271
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272/* Create a new long int object from a C double */
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyLongObject *v;
278 double frac;
279 int i, ndig, expo, neg;
280 neg = 0;
281 if (Py_IS_INFINITY(dval)) {
282 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000283 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return NULL;
285 }
286 if (Py_IS_NAN(dval)) {
287 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000288 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return NULL;
290 }
291 if (dval < 0.0) {
292 neg = 1;
293 dval = -dval;
294 }
295 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
296 if (expo <= 0)
297 return PyLong_FromLong(0L);
298 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
299 v = _PyLong_New(ndig);
300 if (v == NULL)
301 return NULL;
302 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
303 for (i = ndig; --i >= 0; ) {
304 digit bits = (digit)frac;
305 v->ob_digit[i] = bits;
306 frac = frac - (double)bits;
307 frac = ldexp(frac, PyLong_SHIFT);
308 }
309 if (neg)
310 Py_SIZE(v) = -(Py_SIZE(v));
311 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000312}
313
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
315 * anything about what happens when a signed integer operation overflows,
316 * and some compilers think they're doing you a favor by being "clever"
317 * then. The bit pattern for the largest postive signed long is
318 * (unsigned long)LONG_MAX, and for the smallest negative signed long
319 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
320 * However, some other compilers warn about applying unary minus to an
321 * unsigned operand. Hence the weird "0-".
322 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
324#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000326/* Get a C long int from a long int object.
327 Returns -1 and sets an error condition if overflow occurs. */
328
329long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000330PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* This version by Tim Peters */
333 register PyLongObject *v;
334 unsigned long x, prev;
335 long res;
336 Py_ssize_t i;
337 int sign;
338 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 *overflow = 0;
341 if (vv == NULL) {
342 PyErr_BadInternalCall();
343 return -1;
344 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (!PyLong_Check(vv)) {
347 PyNumberMethods *nb;
348 nb = vv->ob_type->tp_as_number;
349 if (nb == NULL || nb->nb_int == NULL) {
350 PyErr_SetString(PyExc_TypeError,
351 "an integer is required");
352 return -1;
353 }
354 vv = (*nb->nb_int) (vv);
355 if (vv == NULL)
356 return -1;
357 do_decref = 1;
358 if (!PyLong_Check(vv)) {
359 Py_DECREF(vv);
360 PyErr_SetString(PyExc_TypeError,
361 "nb_int should return int object");
362 return -1;
363 }
364 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 res = -1;
367 v = (PyLongObject *)vv;
368 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 switch (i) {
371 case -1:
372 res = -(sdigit)v->ob_digit[0];
373 break;
374 case 0:
375 res = 0;
376 break;
377 case 1:
378 res = v->ob_digit[0];
379 break;
380 default:
381 sign = 1;
382 x = 0;
383 if (i < 0) {
384 sign = -1;
385 i = -(i);
386 }
387 while (--i >= 0) {
388 prev = x;
389 x = (x << PyLong_SHIFT) | v->ob_digit[i];
390 if ((x >> PyLong_SHIFT) != prev) {
391 *overflow = sign;
392 goto exit;
393 }
394 }
395 /* Haven't lost any bits, but casting to long requires extra
396 * care (see comment above).
397 */
398 if (x <= (unsigned long)LONG_MAX) {
399 res = (long)x * sign;
400 }
401 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
402 res = LONG_MIN;
403 }
404 else {
405 *overflow = sign;
406 /* res is already set to -1 */
407 }
408 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000409 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (do_decref) {
411 Py_DECREF(vv);
412 }
413 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000414}
415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000417PyLong_AsLong(PyObject *obj)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 int overflow;
420 long result = PyLong_AsLongAndOverflow(obj, &overflow);
421 if (overflow) {
422 /* XXX: could be cute and give a different
423 message for overflow == -1 */
424 PyErr_SetString(PyExc_OverflowError,
425 "Python int too large to convert to C long");
426 }
427 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000428}
429
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000430/* Get a Py_ssize_t from a long int object.
431 Returns -1 and sets an error condition if overflow occurs. */
432
433Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000434PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 register PyLongObject *v;
436 size_t x, prev;
437 Py_ssize_t i;
438 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (vv == NULL) {
441 PyErr_BadInternalCall();
442 return -1;
443 }
444 if (!PyLong_Check(vv)) {
445 PyErr_SetString(PyExc_TypeError, "an integer is required");
446 return -1;
447 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 v = (PyLongObject *)vv;
450 i = Py_SIZE(v);
451 switch (i) {
452 case -1: return -(sdigit)v->ob_digit[0];
453 case 0: return 0;
454 case 1: return v->ob_digit[0];
455 }
456 sign = 1;
457 x = 0;
458 if (i < 0) {
459 sign = -1;
460 i = -(i);
461 }
462 while (--i >= 0) {
463 prev = x;
464 x = (x << PyLong_SHIFT) | v->ob_digit[i];
465 if ((x >> PyLong_SHIFT) != prev)
466 goto overflow;
467 }
468 /* Haven't lost any bits, but casting to a signed type requires
469 * extra care (see comment above).
470 */
471 if (x <= (size_t)PY_SSIZE_T_MAX) {
472 return (Py_ssize_t)x * sign;
473 }
474 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
475 return PY_SSIZE_T_MIN;
476 }
477 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478
Mark Dickinson22b20182010-05-10 21:27:53 +0000479 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyErr_SetString(PyExc_OverflowError,
481 "Python int too large to convert to C ssize_t");
482 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000483}
484
Guido van Rossumd8c80482002-08-13 00:24:58 +0000485/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000486 Returns -1 and sets an error condition if overflow occurs. */
487
488unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000489PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 register PyLongObject *v;
492 unsigned long x, prev;
493 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (vv == NULL) {
496 PyErr_BadInternalCall();
497 return (unsigned long)-1;
498 }
499 if (!PyLong_Check(vv)) {
500 PyErr_SetString(PyExc_TypeError, "an integer is required");
501 return (unsigned long)-1;
502 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 v = (PyLongObject *)vv;
505 i = Py_SIZE(v);
506 x = 0;
507 if (i < 0) {
508 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000509 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return (unsigned long) -1;
511 }
512 switch (i) {
513 case 0: return 0;
514 case 1: return v->ob_digit[0];
515 }
516 while (--i >= 0) {
517 prev = x;
518 x = (x << PyLong_SHIFT) | v->ob_digit[i];
519 if ((x >> PyLong_SHIFT) != prev) {
520 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000521 "python int too large to convert "
522 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return (unsigned long) -1;
524 }
525 }
526 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000527}
528
529/* Get a C unsigned long int from a long int object.
530 Returns -1 and sets an error condition if overflow occurs. */
531
532size_t
533PyLong_AsSize_t(PyObject *vv)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 register PyLongObject *v;
536 size_t x, prev;
537 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (vv == NULL) {
540 PyErr_BadInternalCall();
541 return (size_t) -1;
542 }
543 if (!PyLong_Check(vv)) {
544 PyErr_SetString(PyExc_TypeError, "an integer is required");
545 return (size_t)-1;
546 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 v = (PyLongObject *)vv;
549 i = Py_SIZE(v);
550 x = 0;
551 if (i < 0) {
552 PyErr_SetString(PyExc_OverflowError,
553 "can't convert negative value to size_t");
554 return (size_t) -1;
555 }
556 switch (i) {
557 case 0: return 0;
558 case 1: return v->ob_digit[0];
559 }
560 while (--i >= 0) {
561 prev = x;
562 x = (x << PyLong_SHIFT) | v->ob_digit[i];
563 if ((x >> PyLong_SHIFT) != prev) {
564 PyErr_SetString(PyExc_OverflowError,
565 "Python int too large to convert to C size_t");
566 return (unsigned long) -1;
567 }
568 }
569 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000570}
571
Thomas Hellera4ea6032003-04-17 18:55:45 +0000572/* Get a C unsigned long int from a long int object, ignoring the high bits.
573 Returns -1 and sets an error condition if an error occurs. */
574
Guido van Rossumddefaf32007-01-14 03:31:43 +0000575static unsigned long
576_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 register PyLongObject *v;
579 unsigned long x;
580 Py_ssize_t i;
581 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (vv == NULL || !PyLong_Check(vv)) {
584 PyErr_BadInternalCall();
585 return (unsigned long) -1;
586 }
587 v = (PyLongObject *)vv;
588 i = Py_SIZE(v);
589 switch (i) {
590 case 0: return 0;
591 case 1: return v->ob_digit[0];
592 }
593 sign = 1;
594 x = 0;
595 if (i < 0) {
596 sign = -1;
597 i = -i;
598 }
599 while (--i >= 0) {
600 x = (x << PyLong_SHIFT) | v->ob_digit[i];
601 }
602 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000603}
604
Guido van Rossumddefaf32007-01-14 03:31:43 +0000605unsigned long
606PyLong_AsUnsignedLongMask(register PyObject *op)
607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyNumberMethods *nb;
609 PyLongObject *lo;
610 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (op && PyLong_Check(op))
613 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
616 nb->nb_int == NULL) {
617 PyErr_SetString(PyExc_TypeError, "an integer is required");
618 return (unsigned long)-1;
619 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 lo = (PyLongObject*) (*nb->nb_int) (op);
622 if (lo == NULL)
623 return (unsigned long)-1;
624 if (PyLong_Check(lo)) {
625 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
626 Py_DECREF(lo);
627 if (PyErr_Occurred())
628 return (unsigned long)-1;
629 return val;
630 }
631 else
632 {
633 Py_DECREF(lo);
634 PyErr_SetString(PyExc_TypeError,
635 "nb_int should return int object");
636 return (unsigned long)-1;
637 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000638}
639
Tim Peters5b8132f2003-01-31 15:52:05 +0000640int
641_PyLong_Sign(PyObject *vv)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 assert(v != NULL);
646 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000649}
650
Tim Petersbaefd9e2003-01-28 20:37:45 +0000651size_t
652_PyLong_NumBits(PyObject *vv)
653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyLongObject *v = (PyLongObject *)vv;
655 size_t result = 0;
656 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(v != NULL);
659 assert(PyLong_Check(v));
660 ndigits = ABS(Py_SIZE(v));
661 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
662 if (ndigits > 0) {
663 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 result = (ndigits - 1) * PyLong_SHIFT;
666 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
667 goto Overflow;
668 do {
669 ++result;
670 if (result == 0)
671 goto Overflow;
672 msd >>= 1;
673 } while (msd);
674 }
675 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000676
Mark Dickinson22b20182010-05-10 21:27:53 +0000677 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
679 "to express in a platform size_t");
680 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000681}
682
Tim Peters2a9b3672001-06-11 21:23:58 +0000683PyObject *
684_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000686{
Mark Dickinson22b20182010-05-10 21:27:53 +0000687 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 int incr; /* direction to move pstartbyte */
689 const unsigned char* pendbyte; /* MSB of bytes */
690 size_t numsignificantbytes; /* number of bytes that matter */
691 Py_ssize_t ndigits; /* number of Python long digits */
692 PyLongObject* v; /* result */
693 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (n == 0)
696 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (little_endian) {
699 pstartbyte = bytes;
700 pendbyte = bytes + n - 1;
701 incr = 1;
702 }
703 else {
704 pstartbyte = bytes + n - 1;
705 pendbyte = bytes;
706 incr = -1;
707 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (is_signed)
710 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Compute numsignificantbytes. This consists of finding the most
713 significant byte. Leading 0 bytes are insignficant if the number
714 is positive, and leading 0xff bytes if negative. */
715 {
716 size_t i;
717 const unsigned char* p = pendbyte;
718 const int pincr = -incr; /* search MSB to LSB */
719 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 for (i = 0; i < n; ++i, p += pincr) {
722 if (*p != insignficant)
723 break;
724 }
725 numsignificantbytes = n - i;
726 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
727 actually has 2 significant bytes. OTOH, 0xff0001 ==
728 -0x00ffff, so we wouldn't *need* to bump it there; but we
729 do for 0xffff = -0x0001. To be safe without bothering to
730 check every case, bump it regardless. */
731 if (is_signed && numsignificantbytes < n)
732 ++numsignificantbytes;
733 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* How many Python long digits do we need? We have
736 8*numsignificantbytes bits, and each Python long digit has
737 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
738 /* catch overflow before it happens */
739 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
740 PyErr_SetString(PyExc_OverflowError,
741 "byte array too long to convert to int");
742 return NULL;
743 }
744 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
745 v = _PyLong_New(ndigits);
746 if (v == NULL)
747 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 /* Copy the bits over. The tricky parts are computing 2's-comp on
750 the fly for signed numbers, and dealing with the mismatch between
751 8-bit bytes and (probably) 15-bit Python digits.*/
752 {
753 size_t i;
754 twodigits carry = 1; /* for 2's-comp calculation */
755 twodigits accum = 0; /* sliding register */
756 unsigned int accumbits = 0; /* number of bits in accum */
757 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
760 twodigits thisbyte = *p;
761 /* Compute correction for 2's comp, if needed. */
762 if (is_signed) {
763 thisbyte = (0xff ^ thisbyte) + carry;
764 carry = thisbyte >> 8;
765 thisbyte &= 0xff;
766 }
767 /* Because we're going LSB to MSB, thisbyte is
768 more significant than what's already in accum,
769 so needs to be prepended to accum. */
770 accum |= (twodigits)thisbyte << accumbits;
771 accumbits += 8;
772 if (accumbits >= PyLong_SHIFT) {
773 /* There's enough to fill a Python digit. */
774 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000775 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 ++idigit;
777 accum >>= PyLong_SHIFT;
778 accumbits -= PyLong_SHIFT;
779 assert(accumbits < PyLong_SHIFT);
780 }
781 }
782 assert(accumbits < PyLong_SHIFT);
783 if (accumbits) {
784 assert(idigit < ndigits);
785 v->ob_digit[idigit] = (digit)accum;
786 ++idigit;
787 }
788 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_SIZE(v) = is_signed ? -idigit : idigit;
791 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000792}
793
794int
795_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 unsigned char* bytes, size_t n,
797 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000800 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000802 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
804 digit carry; /* for computing 2's-comp */
805 size_t j; /* # bytes filled */
806 unsigned char* p; /* pointer to next byte in bytes */
807 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (Py_SIZE(v) < 0) {
812 ndigits = -(Py_SIZE(v));
813 if (!is_signed) {
814 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000815 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return -1;
817 }
818 do_twos_comp = 1;
819 }
820 else {
821 ndigits = Py_SIZE(v);
822 do_twos_comp = 0;
823 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (little_endian) {
826 p = bytes;
827 pincr = 1;
828 }
829 else {
830 p = bytes + n - 1;
831 pincr = -1;
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Copy over all the Python digits.
835 It's crucial that every Python digit except for the MSD contribute
836 exactly PyLong_SHIFT bits to the total, so first assert that the long is
837 normalized. */
838 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
839 j = 0;
840 accum = 0;
841 accumbits = 0;
842 carry = do_twos_comp ? 1 : 0;
843 for (i = 0; i < ndigits; ++i) {
844 digit thisdigit = v->ob_digit[i];
845 if (do_twos_comp) {
846 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
847 carry = thisdigit >> PyLong_SHIFT;
848 thisdigit &= PyLong_MASK;
849 }
850 /* Because we're going LSB to MSB, thisdigit is more
851 significant than what's already in accum, so needs to be
852 prepended to accum. */
853 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* The most-significant digit may be (probably is) at least
856 partly empty. */
857 if (i == ndigits - 1) {
858 /* Count # of sign bits -- they needn't be stored,
859 * although for signed conversion we need later to
860 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000861 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 while (s != 0) {
863 s >>= 1;
864 accumbits++;
865 }
866 }
867 else
868 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* Store as many bytes as possible. */
871 while (accumbits >= 8) {
872 if (j >= n)
873 goto Overflow;
874 ++j;
875 *p = (unsigned char)(accum & 0xff);
876 p += pincr;
877 accumbits -= 8;
878 accum >>= 8;
879 }
880 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Store the straggler (if any). */
883 assert(accumbits < 8);
884 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
885 if (accumbits > 0) {
886 if (j >= n)
887 goto Overflow;
888 ++j;
889 if (do_twos_comp) {
890 /* Fill leading bits of the byte with sign bits
891 (appropriately pretending that the long had an
892 infinite supply of sign bits). */
893 accum |= (~(twodigits)0) << accumbits;
894 }
895 *p = (unsigned char)(accum & 0xff);
896 p += pincr;
897 }
898 else if (j == n && n > 0 && is_signed) {
899 /* The main loop filled the byte array exactly, so the code
900 just above didn't get to ensure there's a sign bit, and the
901 loop below wouldn't add one either. Make sure a sign bit
902 exists. */
903 unsigned char msb = *(p - pincr);
904 int sign_bit_set = msb >= 0x80;
905 assert(accumbits == 0);
906 if (sign_bit_set == do_twos_comp)
907 return 0;
908 else
909 goto Overflow;
910 }
Tim Peters05607ad2001-06-13 21:01:27 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Fill remaining bytes with copies of the sign bit. */
913 {
914 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
915 for ( ; j < n; ++j, p += pincr)
916 *p = signbyte;
917 }
Tim Peters05607ad2001-06-13 21:01:27 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000920
Mark Dickinson22b20182010-05-10 21:27:53 +0000921 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
923 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000924
Tim Peters2a9b3672001-06-11 21:23:58 +0000925}
926
Guido van Rossum78694d91998-09-18 14:14:13 +0000927/* Create a new long (or int) object from a C pointer */
928
929PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000930PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000931{
Tim Peters70128a12001-06-16 08:48:40 +0000932#ifndef HAVE_LONG_LONG
933# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
934#endif
935#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000936# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000937#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* special-case null pointer */
939 if (!p)
940 return PyLong_FromLong(0);
941 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000942
Guido van Rossum78694d91998-09-18 14:14:13 +0000943}
944
945/* Get a C pointer from a long object (or an int object in some cases) */
946
947void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000948PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* This function will allow int or long objects. If vv is neither,
951 then the PyLong_AsLong*() functions will raise the exception:
952 PyExc_SystemError, "bad argument to internal function"
953 */
Tim Peters70128a12001-06-16 08:48:40 +0000954#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
958 x = PyLong_AsLong(vv);
959 else
960 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000961#else
Tim Peters70128a12001-06-16 08:48:40 +0000962
963#ifndef HAVE_LONG_LONG
964# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
965#endif
966#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000968#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
972 x = PyLong_AsLongLong(vv);
973 else
974 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000975
976#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (x == -1 && PyErr_Occurred())
979 return NULL;
980 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000981}
982
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000983#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000984
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000985/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000986 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000987 */
988
Tim Peterscf37dfc2001-06-14 18:42:50 +0000989#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000990#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000991
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000993
994PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyLongObject *v;
998 unsigned PY_LONG_LONG abs_ival;
999 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1000 int ndigits = 0;
1001 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 CHECK_SMALL_INT(ival);
1004 if (ival < 0) {
1005 /* avoid signed overflow on negation; see comments
1006 in PyLong_FromLong above. */
1007 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1008 negative = 1;
1009 }
1010 else {
1011 abs_ival = (unsigned PY_LONG_LONG)ival;
1012 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* Count the number of Python digits.
1015 We used to pick 5 ("big enough for anything"), but that's a
1016 waste of time and space given that 5*15 = 75 bits are rarely
1017 needed. */
1018 t = abs_ival;
1019 while (t) {
1020 ++ndigits;
1021 t >>= PyLong_SHIFT;
1022 }
1023 v = _PyLong_New(ndigits);
1024 if (v != NULL) {
1025 digit *p = v->ob_digit;
1026 Py_SIZE(v) = negative ? -ndigits : ndigits;
1027 t = abs_ival;
1028 while (t) {
1029 *p++ = (digit)(t & PyLong_MASK);
1030 t >>= PyLong_SHIFT;
1031 }
1032 }
1033 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034}
1035
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001036/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001037
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001038PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyLongObject *v;
1042 unsigned PY_LONG_LONG t;
1043 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (ival < PyLong_BASE)
1046 return PyLong_FromLong((long)ival);
1047 /* Count the number of Python digits. */
1048 t = (unsigned PY_LONG_LONG)ival;
1049 while (t) {
1050 ++ndigits;
1051 t >>= PyLong_SHIFT;
1052 }
1053 v = _PyLong_New(ndigits);
1054 if (v != NULL) {
1055 digit *p = v->ob_digit;
1056 Py_SIZE(v) = ndigits;
1057 while (ival) {
1058 *p++ = (digit)(ival & PyLong_MASK);
1059 ival >>= PyLong_SHIFT;
1060 }
1061 }
1062 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001063}
1064
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065/* Create a new long int object from a C Py_ssize_t. */
1066
1067PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001068PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyLongObject *v;
1071 size_t abs_ival;
1072 size_t t; /* unsigned so >> doesn't propagate sign bit */
1073 int ndigits = 0;
1074 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 CHECK_SMALL_INT(ival);
1077 if (ival < 0) {
1078 /* avoid signed overflow when ival = SIZE_T_MIN */
1079 abs_ival = (size_t)(-1-ival)+1;
1080 negative = 1;
1081 }
1082 else {
1083 abs_ival = (size_t)ival;
1084 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 /* Count the number of Python digits. */
1087 t = abs_ival;
1088 while (t) {
1089 ++ndigits;
1090 t >>= PyLong_SHIFT;
1091 }
1092 v = _PyLong_New(ndigits);
1093 if (v != NULL) {
1094 digit *p = v->ob_digit;
1095 Py_SIZE(v) = negative ? -ndigits : ndigits;
1096 t = abs_ival;
1097 while (t) {
1098 *p++ = (digit)(t & PyLong_MASK);
1099 t >>= PyLong_SHIFT;
1100 }
1101 }
1102 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103}
1104
1105/* Create a new long int object from a C size_t. */
1106
1107PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001108PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 PyLongObject *v;
1111 size_t t;
1112 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (ival < PyLong_BASE)
1115 return PyLong_FromLong((long)ival);
1116 /* Count the number of Python digits. */
1117 t = ival;
1118 while (t) {
1119 ++ndigits;
1120 t >>= PyLong_SHIFT;
1121 }
1122 v = _PyLong_New(ndigits);
1123 if (v != NULL) {
1124 digit *p = v->ob_digit;
1125 Py_SIZE(v) = ndigits;
1126 while (ival) {
1127 *p++ = (digit)(ival & PyLong_MASK);
1128 ival >>= PyLong_SHIFT;
1129 }
1130 }
1131 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001132}
1133
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001134/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001135 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001136
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001137PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001138PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyLongObject *v;
1141 PY_LONG_LONG bytes;
1142 int one = 1;
1143 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (vv == NULL) {
1146 PyErr_BadInternalCall();
1147 return -1;
1148 }
1149 if (!PyLong_Check(vv)) {
1150 PyNumberMethods *nb;
1151 PyObject *io;
1152 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1153 nb->nb_int == NULL) {
1154 PyErr_SetString(PyExc_TypeError, "an integer is required");
1155 return -1;
1156 }
1157 io = (*nb->nb_int) (vv);
1158 if (io == NULL)
1159 return -1;
1160 if (PyLong_Check(io)) {
1161 bytes = PyLong_AsLongLong(io);
1162 Py_DECREF(io);
1163 return bytes;
1164 }
1165 Py_DECREF(io);
1166 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1167 return -1;
1168 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 v = (PyLongObject*)vv;
1171 switch(Py_SIZE(v)) {
1172 case -1: return -(sdigit)v->ob_digit[0];
1173 case 0: return 0;
1174 case 1: return v->ob_digit[0];
1175 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001176 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1177 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1180 if (res < 0)
1181 return (PY_LONG_LONG)-1;
1182 else
1183 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184}
1185
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001186/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001187 Return -1 and set an error if overflow occurs. */
1188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001190PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyLongObject *v;
1193 unsigned PY_LONG_LONG bytes;
1194 int one = 1;
1195 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (vv == NULL || !PyLong_Check(vv)) {
1198 PyErr_BadInternalCall();
1199 return (unsigned PY_LONG_LONG)-1;
1200 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 v = (PyLongObject*)vv;
1203 switch(Py_SIZE(v)) {
1204 case 0: return 0;
1205 case 1: return v->ob_digit[0];
1206 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001207
Mark Dickinson22b20182010-05-10 21:27:53 +00001208 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1209 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1212 if (res < 0)
1213 return (unsigned PY_LONG_LONG)res;
1214 else
1215 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216}
Tim Petersd1a7da62001-06-13 00:35:57 +00001217
Thomas Hellera4ea6032003-04-17 18:55:45 +00001218/* Get a C unsigned long int from a long int object, ignoring the high bits.
1219 Returns -1 and sets an error condition if an error occurs. */
1220
Guido van Rossumddefaf32007-01-14 03:31:43 +00001221static unsigned PY_LONG_LONG
1222_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 register PyLongObject *v;
1225 unsigned PY_LONG_LONG x;
1226 Py_ssize_t i;
1227 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (vv == NULL || !PyLong_Check(vv)) {
1230 PyErr_BadInternalCall();
1231 return (unsigned long) -1;
1232 }
1233 v = (PyLongObject *)vv;
1234 switch(Py_SIZE(v)) {
1235 case 0: return 0;
1236 case 1: return v->ob_digit[0];
1237 }
1238 i = Py_SIZE(v);
1239 sign = 1;
1240 x = 0;
1241 if (i < 0) {
1242 sign = -1;
1243 i = -i;
1244 }
1245 while (--i >= 0) {
1246 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1247 }
1248 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001249}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001250
1251unsigned PY_LONG_LONG
1252PyLong_AsUnsignedLongLongMask(register PyObject *op)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyNumberMethods *nb;
1255 PyLongObject *lo;
1256 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (op && PyLong_Check(op))
1259 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1262 nb->nb_int == NULL) {
1263 PyErr_SetString(PyExc_TypeError, "an integer is required");
1264 return (unsigned PY_LONG_LONG)-1;
1265 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 lo = (PyLongObject*) (*nb->nb_int) (op);
1268 if (lo == NULL)
1269 return (unsigned PY_LONG_LONG)-1;
1270 if (PyLong_Check(lo)) {
1271 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1272 Py_DECREF(lo);
1273 if (PyErr_Occurred())
1274 return (unsigned PY_LONG_LONG)-1;
1275 return val;
1276 }
1277 else
1278 {
1279 Py_DECREF(lo);
1280 PyErr_SetString(PyExc_TypeError,
1281 "nb_int should return int object");
1282 return (unsigned PY_LONG_LONG)-1;
1283 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001284}
Tim Petersd1a7da62001-06-13 00:35:57 +00001285#undef IS_LITTLE_ENDIAN
1286
Mark Dickinson93f562c2010-01-30 10:30:15 +00001287/* Get a C long long int from a Python long or Python int object.
1288 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1289 on the sign of the result. Otherwise *overflow is 0.
1290
1291 For other errors (e.g., type error), returns -1 and sets an error
1292 condition.
1293*/
1294
1295PY_LONG_LONG
1296PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 /* This version by Tim Peters */
1299 register PyLongObject *v;
1300 unsigned PY_LONG_LONG x, prev;
1301 PY_LONG_LONG res;
1302 Py_ssize_t i;
1303 int sign;
1304 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 *overflow = 0;
1307 if (vv == NULL) {
1308 PyErr_BadInternalCall();
1309 return -1;
1310 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (!PyLong_Check(vv)) {
1313 PyNumberMethods *nb;
1314 nb = vv->ob_type->tp_as_number;
1315 if (nb == NULL || nb->nb_int == NULL) {
1316 PyErr_SetString(PyExc_TypeError,
1317 "an integer is required");
1318 return -1;
1319 }
1320 vv = (*nb->nb_int) (vv);
1321 if (vv == NULL)
1322 return -1;
1323 do_decref = 1;
1324 if (!PyLong_Check(vv)) {
1325 Py_DECREF(vv);
1326 PyErr_SetString(PyExc_TypeError,
1327 "nb_int should return int object");
1328 return -1;
1329 }
1330 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 res = -1;
1333 v = (PyLongObject *)vv;
1334 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 switch (i) {
1337 case -1:
1338 res = -(sdigit)v->ob_digit[0];
1339 break;
1340 case 0:
1341 res = 0;
1342 break;
1343 case 1:
1344 res = v->ob_digit[0];
1345 break;
1346 default:
1347 sign = 1;
1348 x = 0;
1349 if (i < 0) {
1350 sign = -1;
1351 i = -(i);
1352 }
1353 while (--i >= 0) {
1354 prev = x;
1355 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1356 if ((x >> PyLong_SHIFT) != prev) {
1357 *overflow = sign;
1358 goto exit;
1359 }
1360 }
1361 /* Haven't lost any bits, but casting to long requires extra
1362 * care (see comment above).
1363 */
1364 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1365 res = (PY_LONG_LONG)x * sign;
1366 }
1367 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1368 res = PY_LLONG_MIN;
1369 }
1370 else {
1371 *overflow = sign;
1372 /* res is already set to -1 */
1373 }
1374 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001375 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (do_decref) {
1377 Py_DECREF(vv);
1378 }
1379 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001380}
1381
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001382#endif /* HAVE_LONG_LONG */
1383
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001384#define CHECK_BINOP(v,w) \
1385 do { \
1386 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1387 Py_INCREF(Py_NotImplemented); \
1388 return Py_NotImplemented; \
1389 } \
1390 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001391
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001392/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1393 2**k if d is nonzero, else 0. */
1394
1395static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1397 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001398};
1399
1400static int
1401bits_in_digit(digit d)
1402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 int d_bits = 0;
1404 while (d >= 32) {
1405 d_bits += 6;
1406 d >>= 6;
1407 }
1408 d_bits += (int)BitLengthTable[d];
1409 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001410}
1411
Tim Peters877a2122002-08-12 05:09:36 +00001412/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1413 * is modified in place, by adding y to it. Carries are propagated as far as
1414 * x[m-1], and the remaining carry (0 or 1) is returned.
1415 */
1416static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 Py_ssize_t i;
1420 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 assert(m >= n);
1423 for (i = 0; i < n; ++i) {
1424 carry += x[i] + y[i];
1425 x[i] = carry & PyLong_MASK;
1426 carry >>= PyLong_SHIFT;
1427 assert((carry & 1) == carry);
1428 }
1429 for (; carry && i < m; ++i) {
1430 carry += x[i];
1431 x[i] = carry & PyLong_MASK;
1432 carry >>= PyLong_SHIFT;
1433 assert((carry & 1) == carry);
1434 }
1435 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001436}
1437
1438/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1439 * is modified in place, by subtracting y from it. Borrows are propagated as
1440 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1441 */
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 Py_ssize_t i;
1446 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(m >= n);
1449 for (i = 0; i < n; ++i) {
1450 borrow = x[i] - y[i] - borrow;
1451 x[i] = borrow & PyLong_MASK;
1452 borrow >>= PyLong_SHIFT;
1453 borrow &= 1; /* keep only 1 sign bit */
1454 }
1455 for (; borrow && i < m; ++i) {
1456 borrow = x[i] - borrow;
1457 x[i] = borrow & PyLong_MASK;
1458 borrow >>= PyLong_SHIFT;
1459 borrow &= 1;
1460 }
1461 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001462}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001463
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001464/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1465 * result in z[0:m], and return the d bits shifted out of the top.
1466 */
1467static digit
1468v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 Py_ssize_t i;
1471 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 assert(0 <= d && d < PyLong_SHIFT);
1474 for (i=0; i < m; i++) {
1475 twodigits acc = (twodigits)a[i] << d | carry;
1476 z[i] = (digit)acc & PyLong_MASK;
1477 carry = (digit)(acc >> PyLong_SHIFT);
1478 }
1479 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001480}
1481
1482/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1483 * result in z[0:m], and return the d bits shifted out of the bottom.
1484 */
1485static digit
1486v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 Py_ssize_t i;
1489 digit carry = 0;
1490 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 assert(0 <= d && d < PyLong_SHIFT);
1493 for (i=m; i-- > 0;) {
1494 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1495 carry = (digit)acc & mask;
1496 z[i] = (digit)(acc >> d);
1497 }
1498 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499}
1500
Tim Peters212e6142001-07-14 12:23:19 +00001501/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1502 in pout, and returning the remainder. pin and pout point at the LSD.
1503 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001504 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001505 immutable. */
1506
1507static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 assert(n > 0 && n <= PyLong_MASK);
1513 pin += size;
1514 pout += size;
1515 while (--size >= 0) {
1516 digit hi;
1517 rem = (rem << PyLong_SHIFT) | *--pin;
1518 *--pout = hi = (digit)(rem / n);
1519 rem -= (twodigits)hi * n;
1520 }
1521 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001522}
1523
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001524/* Divide a long integer by a digit, returning both the quotient
1525 (as function result) and the remainder (through *prem).
1526 The sign of a is ignored; n should not be zero. */
1527
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001529divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 const Py_ssize_t size = ABS(Py_SIZE(a));
1532 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 assert(n > 0 && n <= PyLong_MASK);
1535 z = _PyLong_New(size);
1536 if (z == NULL)
1537 return NULL;
1538 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1539 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001540}
1541
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001542/* Convert a long integer to a base 10 string. Returns a new non-shared
1543 string. (Return value is non-shared so that callers can modify the
1544 returned value if necessary.) */
1545
1546static PyObject *
1547long_to_decimal_string(PyObject *aa)
1548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyLongObject *scratch, *a;
1550 PyObject *str;
1551 Py_ssize_t size, strlen, size_a, i, j;
1552 digit *pout, *pin, rem, tenpow;
1553 Py_UNICODE *p;
1554 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 a = (PyLongObject *)aa;
1557 if (a == NULL || !PyLong_Check(a)) {
1558 PyErr_BadInternalCall();
1559 return NULL;
1560 }
1561 size_a = ABS(Py_SIZE(a));
1562 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* quick and dirty upper bound for the number of digits
1565 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 But log2(a) < size_a * PyLong_SHIFT, and
1570 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1571 > 3 * _PyLong_DECIMAL_SHIFT
1572 */
1573 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1574 PyErr_SetString(PyExc_OverflowError,
1575 "long is too large to format");
1576 return NULL;
1577 }
1578 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1579 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1580 scratch = _PyLong_New(size);
1581 if (scratch == NULL)
1582 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* convert array of base _PyLong_BASE digits in pin to an array of
1585 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1586 Volume 2 (3rd edn), section 4.4, Method 1b). */
1587 pin = a->ob_digit;
1588 pout = scratch->ob_digit;
1589 size = 0;
1590 for (i = size_a; --i >= 0; ) {
1591 digit hi = pin[i];
1592 for (j = 0; j < size; j++) {
1593 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1594 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1595 pout[j] = (digit)(z - (twodigits)hi *
1596 _PyLong_DECIMAL_BASE);
1597 }
1598 while (hi) {
1599 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1600 hi /= _PyLong_DECIMAL_BASE;
1601 }
1602 /* check for keyboard interrupt */
1603 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001604 Py_DECREF(scratch);
1605 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001606 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 }
1608 /* pout should have at least one digit, so that the case when a = 0
1609 works correctly */
1610 if (size == 0)
1611 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* calculate exact length of output string, and allocate */
1614 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1615 tenpow = 10;
1616 rem = pout[size-1];
1617 while (rem >= tenpow) {
1618 tenpow *= 10;
1619 strlen++;
1620 }
1621 str = PyUnicode_FromUnicode(NULL, strlen);
1622 if (str == NULL) {
1623 Py_DECREF(scratch);
1624 return NULL;
1625 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* fill the string right-to-left */
1628 p = PyUnicode_AS_UNICODE(str) + strlen;
1629 *p = '\0';
1630 /* pout[0] through pout[size-2] contribute exactly
1631 _PyLong_DECIMAL_SHIFT digits each */
1632 for (i=0; i < size - 1; i++) {
1633 rem = pout[i];
1634 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1635 *--p = '0' + rem % 10;
1636 rem /= 10;
1637 }
1638 }
1639 /* pout[size-1]: always produce at least one decimal digit */
1640 rem = pout[i];
1641 do {
1642 *--p = '0' + rem % 10;
1643 rem /= 10;
1644 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* and sign */
1647 if (negative)
1648 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* check we've counted correctly */
1651 assert(p == PyUnicode_AS_UNICODE(str));
1652 Py_DECREF(scratch);
1653 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001654}
1655
Mark Dickinsoncd068122009-09-18 14:53:08 +00001656/* Convert a long int object to a string, using a given conversion base,
1657 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001658 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001660PyObject *
1661_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 register PyLongObject *a = (PyLongObject *)aa;
1664 PyObject *str;
1665 Py_ssize_t i, sz;
1666 Py_ssize_t size_a;
1667 Py_UNICODE *p, sign = '\0';
1668 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 assert(base == 2 || base == 8 || base == 10 || base == 16);
1671 if (base == 10)
1672 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (a == NULL || !PyLong_Check(a)) {
1675 PyErr_BadInternalCall();
1676 return NULL;
1677 }
1678 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 /* Compute a rough upper bound for the length of the string */
1681 switch (base) {
1682 case 16:
1683 bits = 4;
1684 break;
1685 case 8:
1686 bits = 3;
1687 break;
1688 case 2:
1689 bits = 1;
1690 break;
1691 default:
1692 assert(0); /* shouldn't ever get here */
1693 bits = 0; /* to silence gcc warning */
1694 }
1695 /* compute length of output string: allow 2 characters for prefix and
1696 1 for possible '-' sign. */
1697 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1698 PyErr_SetString(PyExc_OverflowError,
1699 "int is too large to format");
1700 return NULL;
1701 }
1702 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1703 is safe from overflow */
1704 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1705 assert(sz >= 0);
1706 str = PyUnicode_FromUnicode(NULL, sz);
1707 if (str == NULL)
1708 return NULL;
1709 p = PyUnicode_AS_UNICODE(str) + sz;
1710 *p = '\0';
1711 if (Py_SIZE(a) < 0)
1712 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (Py_SIZE(a) == 0) {
1715 *--p = '0';
1716 }
1717 else {
1718 /* JRH: special case for power-of-2 bases */
1719 twodigits accum = 0;
1720 int accumbits = 0; /* # of bits in accum */
1721 for (i = 0; i < size_a; ++i) {
1722 accum |= (twodigits)a->ob_digit[i] << accumbits;
1723 accumbits += PyLong_SHIFT;
1724 assert(accumbits >= bits);
1725 do {
1726 Py_UNICODE cdigit;
1727 cdigit = (Py_UNICODE)(accum & (base - 1));
1728 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1729 assert(p > PyUnicode_AS_UNICODE(str));
1730 *--p = cdigit;
1731 accumbits -= bits;
1732 accum >>= bits;
1733 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1734 }
1735 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (base == 16)
1738 *--p = 'x';
1739 else if (base == 8)
1740 *--p = 'o';
1741 else /* (base == 2) */
1742 *--p = 'b';
1743 *--p = '0';
1744 if (sign)
1745 *--p = sign;
1746 if (p != PyUnicode_AS_UNICODE(str)) {
1747 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1748 assert(p > q);
1749 do {
1750 } while ((*q++ = *p++) != '\0');
1751 q--;
1752 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1753 PyUnicode_AS_UNICODE(str)))) {
1754 Py_DECREF(str);
1755 return NULL;
1756 }
1757 }
1758 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001759}
1760
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761/* Table of digit values for 8-bit string -> integer conversion.
1762 * '0' maps to 0, ..., '9' maps to 9.
1763 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1764 * All other indices map to 37.
1765 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001766 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001767 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001768unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1770 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1771 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1772 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1773 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1774 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1775 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1776 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1777 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1779 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1780 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1781 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1782 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1783 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1784 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785};
1786
1787/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001788 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1789 * non-digit (which may be *str!). A normalized long is returned.
1790 * The point to this routine is that it takes time linear in the number of
1791 * string characters.
1792 */
1793static PyLongObject *
1794long_from_binary_base(char **str, int base)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 char *p = *str;
1797 char *start = p;
1798 int bits_per_char;
1799 Py_ssize_t n;
1800 PyLongObject *z;
1801 twodigits accum;
1802 int bits_in_accum;
1803 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1806 n = base;
1807 for (bits_per_char = -1; n; ++bits_per_char)
1808 n >>= 1;
1809 /* n <- total # of bits needed, while setting p to end-of-string */
1810 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1811 ++p;
1812 *str = p;
1813 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1814 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1815 if (n / bits_per_char < p - start) {
1816 PyErr_SetString(PyExc_ValueError,
1817 "int string too large to convert");
1818 return NULL;
1819 }
1820 n = n / PyLong_SHIFT;
1821 z = _PyLong_New(n);
1822 if (z == NULL)
1823 return NULL;
1824 /* Read string from right, and fill in long from left; i.e.,
1825 * from least to most significant in both.
1826 */
1827 accum = 0;
1828 bits_in_accum = 0;
1829 pdigit = z->ob_digit;
1830 while (--p >= start) {
1831 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1832 assert(k >= 0 && k < base);
1833 accum |= (twodigits)k << bits_in_accum;
1834 bits_in_accum += bits_per_char;
1835 if (bits_in_accum >= PyLong_SHIFT) {
1836 *pdigit++ = (digit)(accum & PyLong_MASK);
1837 assert(pdigit - z->ob_digit <= n);
1838 accum >>= PyLong_SHIFT;
1839 bits_in_accum -= PyLong_SHIFT;
1840 assert(bits_in_accum < PyLong_SHIFT);
1841 }
1842 }
1843 if (bits_in_accum) {
1844 assert(bits_in_accum <= PyLong_SHIFT);
1845 *pdigit++ = (digit)accum;
1846 assert(pdigit - z->ob_digit <= n);
1847 }
1848 while (pdigit - z->ob_digit < n)
1849 *pdigit++ = 0;
1850 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001851}
1852
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001853PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001854PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int sign = 1, error_if_nonzero = 0;
1857 char *start, *orig_str = str;
1858 PyLongObject *z = NULL;
1859 PyObject *strobj;
1860 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if ((base != 0 && base < 2) || base > 36) {
1863 PyErr_SetString(PyExc_ValueError,
1864 "int() arg 2 must be >= 2 and <= 36");
1865 return NULL;
1866 }
1867 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1868 str++;
1869 if (*str == '+')
1870 ++str;
1871 else if (*str == '-') {
1872 ++str;
1873 sign = -1;
1874 }
1875 if (base == 0) {
1876 if (str[0] != '0')
1877 base = 10;
1878 else if (str[1] == 'x' || str[1] == 'X')
1879 base = 16;
1880 else if (str[1] == 'o' || str[1] == 'O')
1881 base = 8;
1882 else if (str[1] == 'b' || str[1] == 'B')
1883 base = 2;
1884 else {
1885 /* "old" (C-style) octal literal, now invalid.
1886 it might still be zero though */
1887 error_if_nonzero = 1;
1888 base = 10;
1889 }
1890 }
1891 if (str[0] == '0' &&
1892 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1893 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1894 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1895 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 start = str;
1898 if ((base & (base - 1)) == 0)
1899 z = long_from_binary_base(&str, base);
1900 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901/***
1902Binary bases can be converted in time linear in the number of digits, because
1903Python's representation base is binary. Other bases (including decimal!) use
1904the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001905
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906First some math: the largest integer that can be expressed in N base-B digits
1907is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1908case number of Python digits needed to hold it is the smallest integer n s.t.
1909
1910 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1911 BASE**n >= B**N [taking logs to base BASE]
1912 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1913
1914The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1915this quickly. A Python long with that much space is reserved near the start,
1916and the result is computed into it.
1917
1918The input string is actually treated as being in base base**i (i.e., i digits
1919are processed at a time), where two more static arrays hold:
1920
1921 convwidth_base[base] = the largest integer i such that base**i <= BASE
1922 convmultmax_base[base] = base ** convwidth_base[base]
1923
1924The first of these is the largest i such that i consecutive input digits
1925must fit in a single Python digit. The second is effectively the input
1926base we're really using.
1927
1928Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1929convmultmax_base[base], the result is "simply"
1930
1931 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1932
1933where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001934
1935Error analysis: as above, the number of Python digits `n` needed is worst-
1936case
1937
1938 n >= N * log(B)/log(BASE)
1939
1940where `N` is the number of input digits in base `B`. This is computed via
1941
1942 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1943
1944below. Two numeric concerns are how much space this can waste, and whether
1945the computed result can be too small. To be concrete, assume BASE = 2**15,
1946which is the default (and it's unlikely anyone changes that).
1947
1948Waste isn't a problem: provided the first input digit isn't 0, the difference
1949between the worst-case input with N digits and the smallest input with N
1950digits is about a factor of B, but B is small compared to BASE so at most
1951one allocated Python digit can remain unused on that count. If
1952N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1953and adding 1 returns a result 1 larger than necessary. However, that can't
1954happen: whenever B is a power of 2, long_from_binary_base() is called
1955instead, and it's impossible for B**i to be an integer power of 2**15 when
1956B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1957an exact integer when B is not a power of 2, since B**i has a prime factor
1958other than 2 in that case, but (2**15)**j's only prime factor is 2).
1959
1960The computed result can be too small if the true value of N*log(B)/log(BASE)
1961is a little bit larger than an exact integer, but due to roundoff errors (in
1962computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1963yields a numeric result a little less than that integer. Unfortunately, "how
1964close can a transcendental function get to an integer over some range?"
1965questions are generally theoretically intractable. Computer analysis via
1966continued fractions is practical: expand log(B)/log(BASE) via continued
1967fractions, giving a sequence i/j of "the best" rational approximations. Then
1968j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1969we can get very close to being in trouble, but very rarely. For example,
197076573 is a denominator in one of the continued-fraction approximations to
1971log(10)/log(2**15), and indeed:
1972
1973 >>> log(10)/log(2**15)*76573
1974 16958.000000654003
1975
1976is very close to an integer. If we were working with IEEE single-precision,
1977rounding errors could kill us. Finding worst cases in IEEE double-precision
1978requires better-than-double-precision log() functions, and Tim didn't bother.
1979Instead the code checks to see whether the allocated space is enough as each
1980new Python digit is added, and copies the whole thing to a larger long if not.
1981This should happen extremely rarely, and in fact I don't have a test case
1982that triggers it(!). Instead the code was tested by artificially allocating
1983just 1 digit at the start, so that the copying code was exercised for every
1984digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 register twodigits c; /* current input character */
1987 Py_ssize_t size_z;
1988 int i;
1989 int convwidth;
1990 twodigits convmultmax, convmult;
1991 digit *pz, *pzstop;
1992 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 static double log_base_BASE[37] = {0.0e0,};
1995 static int convwidth_base[37] = {0,};
1996 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (log_base_BASE[base] == 0.0) {
1999 twodigits convmax = base;
2000 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002001
Mark Dickinson22b20182010-05-10 21:27:53 +00002002 log_base_BASE[base] = (log((double)base) /
2003 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 for (;;) {
2005 twodigits next = convmax * base;
2006 if (next > PyLong_BASE)
2007 break;
2008 convmax = next;
2009 ++i;
2010 }
2011 convmultmax_base[base] = convmax;
2012 assert(i > 0);
2013 convwidth_base[base] = i;
2014 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Find length of the string of numeric characters. */
2017 scan = str;
2018 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2019 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Create a long object that can contain the largest possible
2022 * integer with this base and length. Note that there's no
2023 * need to initialize z->ob_digit -- no slot is read up before
2024 * being stored into.
2025 */
2026 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2027 /* Uncomment next line to test exceedingly rare copy code */
2028 /* size_z = 1; */
2029 assert(size_z > 0);
2030 z = _PyLong_New(size_z);
2031 if (z == NULL)
2032 return NULL;
2033 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* `convwidth` consecutive input digits are treated as a single
2036 * digit in base `convmultmax`.
2037 */
2038 convwidth = convwidth_base[base];
2039 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Work ;-) */
2042 while (str < scan) {
2043 /* grab up to convwidth digits from the input string */
2044 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2045 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2046 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002047 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 assert(c < PyLong_BASE);
2049 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 convmult = convmultmax;
2052 /* Calculate the shift only if we couldn't get
2053 * convwidth digits.
2054 */
2055 if (i != convwidth) {
2056 convmult = base;
2057 for ( ; i > 1; --i)
2058 convmult *= base;
2059 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* Multiply z by convmult, and add c. */
2062 pz = z->ob_digit;
2063 pzstop = pz + Py_SIZE(z);
2064 for (; pz < pzstop; ++pz) {
2065 c += (twodigits)*pz * convmult;
2066 *pz = (digit)(c & PyLong_MASK);
2067 c >>= PyLong_SHIFT;
2068 }
2069 /* carry off the current end? */
2070 if (c) {
2071 assert(c < PyLong_BASE);
2072 if (Py_SIZE(z) < size_z) {
2073 *pz = (digit)c;
2074 ++Py_SIZE(z);
2075 }
2076 else {
2077 PyLongObject *tmp;
2078 /* Extremely rare. Get more space. */
2079 assert(Py_SIZE(z) == size_z);
2080 tmp = _PyLong_New(size_z + 1);
2081 if (tmp == NULL) {
2082 Py_DECREF(z);
2083 return NULL;
2084 }
2085 memcpy(tmp->ob_digit,
2086 z->ob_digit,
2087 sizeof(digit) * size_z);
2088 Py_DECREF(z);
2089 z = tmp;
2090 z->ob_digit[size_z] = (digit)c;
2091 ++size_z;
2092 }
2093 }
2094 }
2095 }
2096 if (z == NULL)
2097 return NULL;
2098 if (error_if_nonzero) {
2099 /* reset the base to 0, else the exception message
2100 doesn't make too much sense */
2101 base = 0;
2102 if (Py_SIZE(z) != 0)
2103 goto onError;
2104 /* there might still be other problems, therefore base
2105 remains zero here for the same reason */
2106 }
2107 if (str == start)
2108 goto onError;
2109 if (sign < 0)
2110 Py_SIZE(z) = -(Py_SIZE(z));
2111 while (*str && isspace(Py_CHARMASK(*str)))
2112 str++;
2113 if (*str != '\0')
2114 goto onError;
2115 if (pend)
2116 *pend = str;
2117 long_normalize(z);
2118 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002119
Mark Dickinson22b20182010-05-10 21:27:53 +00002120 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 Py_XDECREF(z);
2122 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2123 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2124 if (strobj == NULL)
2125 return NULL;
2126 PyErr_Format(PyExc_ValueError,
2127 "invalid literal for int() with base %d: %R",
2128 base, strobj);
2129 Py_DECREF(strobj);
2130 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002131}
2132
2133PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002134PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyObject *result;
2137 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (buffer == NULL)
2140 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2143 PyMem_FREE(buffer);
2144 return NULL;
2145 }
2146 result = PyLong_FromString(buffer, NULL, base);
2147 PyMem_FREE(buffer);
2148 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149}
2150
Tim Peters9f688bf2000-07-07 15:53:28 +00002151/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002154static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155
2156/* Long division with remainder, top-level routine */
2157
Guido van Rossume32e0141992-01-19 16:31:05 +00002158static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002159long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2163 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (size_b == 0) {
2166 PyErr_SetString(PyExc_ZeroDivisionError,
2167 "integer division or modulo by zero");
2168 return -1;
2169 }
2170 if (size_a < size_b ||
2171 (size_a == size_b &&
2172 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2173 /* |a| < |b|. */
2174 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2175 if (*pdiv == NULL)
2176 return -1;
2177 Py_INCREF(a);
2178 *prem = (PyLongObject *) a;
2179 return 0;
2180 }
2181 if (size_b == 1) {
2182 digit rem = 0;
2183 z = divrem1(a, b->ob_digit[0], &rem);
2184 if (z == NULL)
2185 return -1;
2186 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2187 if (*prem == NULL) {
2188 Py_DECREF(z);
2189 return -1;
2190 }
2191 }
2192 else {
2193 z = x_divrem(a, b, prem);
2194 if (z == NULL)
2195 return -1;
2196 }
2197 /* Set the signs.
2198 The quotient z has the sign of a*b;
2199 the remainder r has the sign of a,
2200 so a = b*z + r. */
2201 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2202 NEGATE(z);
2203 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2204 NEGATE(*prem);
2205 *pdiv = maybe_small_long(z);
2206 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002207}
2208
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002209/* Unsigned long division with remainder -- the algorithm. The arguments v1
2210 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002213x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyLongObject *v, *w, *a;
2216 Py_ssize_t i, k, size_v, size_w;
2217 int d;
2218 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2219 twodigits vv;
2220 sdigit zhi;
2221 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2224 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2225 handle the special case when the initial estimate q for a quotient
2226 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2227 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* allocate space; w will also be used to hold the final remainder */
2230 size_v = ABS(Py_SIZE(v1));
2231 size_w = ABS(Py_SIZE(w1));
2232 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2233 v = _PyLong_New(size_v+1);
2234 if (v == NULL) {
2235 *prem = NULL;
2236 return NULL;
2237 }
2238 w = _PyLong_New(size_w);
2239 if (w == NULL) {
2240 Py_DECREF(v);
2241 *prem = NULL;
2242 return NULL;
2243 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2246 shift v1 left by the same amount. Results go into w and v. */
2247 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2248 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2249 assert(carry == 0);
2250 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2251 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2252 v->ob_digit[size_v] = carry;
2253 size_v++;
2254 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2257 at most (and usually exactly) k = size_v - size_w digits. */
2258 k = size_v - size_w;
2259 assert(k >= 0);
2260 a = _PyLong_New(k);
2261 if (a == NULL) {
2262 Py_DECREF(w);
2263 Py_DECREF(v);
2264 *prem = NULL;
2265 return NULL;
2266 }
2267 v0 = v->ob_digit;
2268 w0 = w->ob_digit;
2269 wm1 = w0[size_w-1];
2270 wm2 = w0[size_w-2];
2271 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2272 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2273 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002276 Py_DECREF(a);
2277 Py_DECREF(w);
2278 Py_DECREF(v);
2279 *prem = NULL;
2280 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002281 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* estimate quotient digit q; may overestimate by 1 (rare) */
2284 vtop = vk[size_w];
2285 assert(vtop <= wm1);
2286 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2287 q = (digit)(vv / wm1);
2288 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2289 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2290 | vk[size_w-2])) {
2291 --q;
2292 r += wm1;
2293 if (r >= PyLong_BASE)
2294 break;
2295 }
2296 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2299 zhi = 0;
2300 for (i = 0; i < size_w; ++i) {
2301 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2302 -PyLong_BASE * q <= z < PyLong_BASE */
2303 z = (sdigit)vk[i] + zhi -
2304 (stwodigits)q * (stwodigits)w0[i];
2305 vk[i] = (digit)z & PyLong_MASK;
2306 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002307 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* add w back if q was too large (this branch taken rarely) */
2311 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2312 if ((sdigit)vtop + zhi < 0) {
2313 carry = 0;
2314 for (i = 0; i < size_w; ++i) {
2315 carry += vk[i] + w0[i];
2316 vk[i] = carry & PyLong_MASK;
2317 carry >>= PyLong_SHIFT;
2318 }
2319 --q;
2320 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* store quotient digit */
2323 assert(q < PyLong_BASE);
2324 *--ak = q;
2325 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* unshift remainder; we reuse w to store the result */
2328 carry = v_rshift(w0, v0, size_w, d);
2329 assert(carry==0);
2330 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 *prem = long_normalize(w);
2333 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002334}
2335
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002336/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2337 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2338 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2339 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2340 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2341 -1.0. */
2342
2343/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2344#if DBL_MANT_DIG == 53
2345#define EXP2_DBL_MANT_DIG 9007199254740992.0
2346#else
2347#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2348#endif
2349
2350double
2351_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2354 /* See below for why x_digits is always large enough. */
2355 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2356 double dx;
2357 /* Correction term for round-half-to-even rounding. For a digit x,
2358 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2359 multiple of 4, rounding ties to a multiple of 8. */
2360 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 a_size = ABS(Py_SIZE(a));
2363 if (a_size == 0) {
2364 /* Special case for 0: significand 0.0, exponent 0. */
2365 *e = 0;
2366 return 0.0;
2367 }
2368 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2369 /* The following is an overflow-free version of the check
2370 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2371 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2372 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2373 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002374 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2378 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Number of digits needed for result: write // for floor division.
2381 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2390 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2393 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2394 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 in both cases.
2401 */
2402 if (a_bits <= DBL_MANT_DIG + 2) {
2403 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2404 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2405 x_size = 0;
2406 while (x_size < shift_digits)
2407 x_digits[x_size++] = 0;
2408 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2409 (int)shift_bits);
2410 x_size += a_size;
2411 x_digits[x_size++] = rem;
2412 }
2413 else {
2414 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2415 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2416 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2417 a_size - shift_digits, (int)shift_bits);
2418 x_size = a_size - shift_digits;
2419 /* For correct rounding below, we need the least significant
2420 bit of x to be 'sticky' for this shift: if any of the bits
2421 shifted out was nonzero, we set the least significant bit
2422 of x. */
2423 if (rem)
2424 x_digits[0] |= 1;
2425 else
2426 while (shift_digits > 0)
2427 if (a->ob_digit[--shift_digits]) {
2428 x_digits[0] |= 1;
2429 break;
2430 }
2431 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002432 assert(1 <= x_size &&
2433 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* Round, and convert to double. */
2436 x_digits[0] += half_even_correction[x_digits[0] & 7];
2437 dx = x_digits[--x_size];
2438 while (x_size > 0)
2439 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 /* Rescale; make correction if result is 1.0. */
2442 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2443 if (dx == 1.0) {
2444 if (a_bits == PY_SSIZE_T_MAX)
2445 goto overflow;
2446 dx = 0.5;
2447 a_bits += 1;
2448 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 *e = a_bits;
2451 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002452
2453 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* exponent > PY_SSIZE_T_MAX */
2455 PyErr_SetString(PyExc_OverflowError,
2456 "huge integer: number of bits overflows a Py_ssize_t");
2457 *e = 0;
2458 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002459}
2460
2461/* Get a C double from a long int object. Rounds to the nearest double,
2462 using the round-half-to-even rule in the case of a tie. */
2463
2464double
2465PyLong_AsDouble(PyObject *v)
2466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 Py_ssize_t exponent;
2468 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (v == NULL || !PyLong_Check(v)) {
2471 PyErr_BadInternalCall();
2472 return -1.0;
2473 }
2474 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2475 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2476 PyErr_SetString(PyExc_OverflowError,
2477 "long int too large to convert to float");
2478 return -1.0;
2479 }
2480 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002481}
2482
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002483/* Methods */
2484
2485static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002486long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002489}
2490
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002491static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002492long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (Py_SIZE(a) != Py_SIZE(b)) {
2497 sign = Py_SIZE(a) - Py_SIZE(b);
2498 }
2499 else {
2500 Py_ssize_t i = ABS(Py_SIZE(a));
2501 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2502 ;
2503 if (i < 0)
2504 sign = 0;
2505 else {
2506 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2507 if (Py_SIZE(a) < 0)
2508 sign = -sign;
2509 }
2510 }
2511 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512}
2513
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002514#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002516
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517static PyObject *
2518long_richcompare(PyObject *self, PyObject *other, int op)
2519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 int result;
2521 PyObject *v;
2522 CHECK_BINOP(self, other);
2523 if (self == other)
2524 result = 0;
2525 else
2526 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2527 /* Convert the return value to a Boolean */
2528 switch (op) {
2529 case Py_EQ:
2530 v = TEST_COND(result == 0);
2531 break;
2532 case Py_NE:
2533 v = TEST_COND(result != 0);
2534 break;
2535 case Py_LE:
2536 v = TEST_COND(result <= 0);
2537 break;
2538 case Py_GE:
2539 v = TEST_COND(result >= 0);
2540 break;
2541 case Py_LT:
2542 v = TEST_COND(result == -1);
2543 break;
2544 case Py_GT:
2545 v = TEST_COND(result == 1);
2546 break;
2547 default:
2548 PyErr_BadArgument();
2549 return NULL;
2550 }
2551 Py_INCREF(v);
2552 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002553}
2554
Guido van Rossum9bfef441993-03-29 10:43:31 +00002555static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002556long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 unsigned long x;
2559 Py_ssize_t i;
2560 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 i = Py_SIZE(v);
2563 switch(i) {
2564 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2565 case 0: return 0;
2566 case 1: return v->ob_digit[0];
2567 }
2568 sign = 1;
2569 x = 0;
2570 if (i < 0) {
2571 sign = -1;
2572 i = -(i);
2573 }
2574 /* The following loop produces a C unsigned long x such that x is
2575 congruent to the absolute value of v modulo ULONG_MAX. The
2576 resulting x is nonzero if and only if v is. */
2577 while (--i >= 0) {
2578 /* Force a native long #-bits (32 or 64) circular shift */
2579 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
2580 x += v->ob_digit[i];
2581 /* If the addition above overflowed we compensate by
2582 incrementing. This preserves the value modulo
2583 ULONG_MAX. */
2584 if (x < v->ob_digit[i])
2585 x++;
2586 }
2587 x = x * sign;
2588 if (x == (unsigned long)-1)
2589 x = (unsigned long)-2;
2590 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002591}
2592
2593
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002594/* Add the absolute values of two long integers. */
2595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002596static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002597x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2600 PyLongObject *z;
2601 Py_ssize_t i;
2602 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 /* Ensure a is the larger of the two: */
2605 if (size_a < size_b) {
2606 { PyLongObject *temp = a; a = b; b = temp; }
2607 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002608 size_a = size_b;
2609 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 }
2611 z = _PyLong_New(size_a+1);
2612 if (z == NULL)
2613 return NULL;
2614 for (i = 0; i < size_b; ++i) {
2615 carry += a->ob_digit[i] + b->ob_digit[i];
2616 z->ob_digit[i] = carry & PyLong_MASK;
2617 carry >>= PyLong_SHIFT;
2618 }
2619 for (; i < size_a; ++i) {
2620 carry += a->ob_digit[i];
2621 z->ob_digit[i] = carry & PyLong_MASK;
2622 carry >>= PyLong_SHIFT;
2623 }
2624 z->ob_digit[i] = carry;
2625 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002626}
2627
2628/* Subtract the absolute values of two integers. */
2629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002630static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002631x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2634 PyLongObject *z;
2635 Py_ssize_t i;
2636 int sign = 1;
2637 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 /* Ensure a is the larger of the two: */
2640 if (size_a < size_b) {
2641 sign = -1;
2642 { PyLongObject *temp = a; a = b; b = temp; }
2643 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002644 size_a = size_b;
2645 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
2647 else if (size_a == size_b) {
2648 /* Find highest digit where a and b differ: */
2649 i = size_a;
2650 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2651 ;
2652 if (i < 0)
2653 return (PyLongObject *)PyLong_FromLong(0);
2654 if (a->ob_digit[i] < b->ob_digit[i]) {
2655 sign = -1;
2656 { PyLongObject *temp = a; a = b; b = temp; }
2657 }
2658 size_a = size_b = i+1;
2659 }
2660 z = _PyLong_New(size_a);
2661 if (z == NULL)
2662 return NULL;
2663 for (i = 0; i < size_b; ++i) {
2664 /* The following assumes unsigned arithmetic
2665 works module 2**N for some N>PyLong_SHIFT. */
2666 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2667 z->ob_digit[i] = borrow & PyLong_MASK;
2668 borrow >>= PyLong_SHIFT;
2669 borrow &= 1; /* Keep only one sign bit */
2670 }
2671 for (; i < size_a; ++i) {
2672 borrow = a->ob_digit[i] - borrow;
2673 z->ob_digit[i] = borrow & PyLong_MASK;
2674 borrow >>= PyLong_SHIFT;
2675 borrow &= 1; /* Keep only one sign bit */
2676 }
2677 assert(borrow == 0);
2678 if (sign < 0)
2679 NEGATE(z);
2680 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002681}
2682
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002683static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002684long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2691 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2692 MEDIUM_VALUE(b));
2693 return result;
2694 }
2695 if (Py_SIZE(a) < 0) {
2696 if (Py_SIZE(b) < 0) {
2697 z = x_add(a, b);
2698 if (z != NULL && Py_SIZE(z) != 0)
2699 Py_SIZE(z) = -(Py_SIZE(z));
2700 }
2701 else
2702 z = x_sub(b, a);
2703 }
2704 else {
2705 if (Py_SIZE(b) < 0)
2706 z = x_sub(a, b);
2707 else
2708 z = x_add(a, b);
2709 }
2710 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711}
2712
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002713static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002714long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2721 PyObject* r;
2722 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2723 return r;
2724 }
2725 if (Py_SIZE(a) < 0) {
2726 if (Py_SIZE(b) < 0)
2727 z = x_sub(a, b);
2728 else
2729 z = x_add(a, b);
2730 if (z != NULL && Py_SIZE(z) != 0)
2731 Py_SIZE(z) = -(Py_SIZE(z));
2732 }
2733 else {
2734 if (Py_SIZE(b) < 0)
2735 z = x_add(a, b);
2736 else
2737 z = x_sub(a, b);
2738 }
2739 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002740}
2741
Tim Peters5af4e6c2002-08-12 02:31:19 +00002742/* Grade school multiplication, ignoring the signs.
2743 * Returns the absolute value of the product, or NULL if error.
2744 */
2745static PyLongObject *
2746x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 PyLongObject *z;
2749 Py_ssize_t size_a = ABS(Py_SIZE(a));
2750 Py_ssize_t size_b = ABS(Py_SIZE(b));
2751 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 z = _PyLong_New(size_a + size_b);
2754 if (z == NULL)
2755 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2758 if (a == b) {
2759 /* Efficient squaring per HAC, Algorithm 14.16:
2760 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2761 * Gives slightly less than a 2x speedup when a == b,
2762 * via exploiting that each entry in the multiplication
2763 * pyramid appears twice (except for the size_a squares).
2764 */
2765 for (i = 0; i < size_a; ++i) {
2766 twodigits carry;
2767 twodigits f = a->ob_digit[i];
2768 digit *pz = z->ob_digit + (i << 1);
2769 digit *pa = a->ob_digit + i + 1;
2770 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002773 Py_DECREF(z);
2774 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002775 });
Tim Peters0973b992004-08-29 22:16:50 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 carry = *pz + f * f;
2778 *pz++ = (digit)(carry & PyLong_MASK);
2779 carry >>= PyLong_SHIFT;
2780 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* Now f is added in twice in each column of the
2783 * pyramid it appears. Same as adding f<<1 once.
2784 */
2785 f <<= 1;
2786 while (pa < paend) {
2787 carry += *pz + *pa++ * f;
2788 *pz++ = (digit)(carry & PyLong_MASK);
2789 carry >>= PyLong_SHIFT;
2790 assert(carry <= (PyLong_MASK << 1));
2791 }
2792 if (carry) {
2793 carry += *pz;
2794 *pz++ = (digit)(carry & PyLong_MASK);
2795 carry >>= PyLong_SHIFT;
2796 }
2797 if (carry)
2798 *pz += (digit)(carry & PyLong_MASK);
2799 assert((carry >> PyLong_SHIFT) == 0);
2800 }
2801 }
2802 else { /* a is not the same as b -- gradeschool long mult */
2803 for (i = 0; i < size_a; ++i) {
2804 twodigits carry = 0;
2805 twodigits f = a->ob_digit[i];
2806 digit *pz = z->ob_digit + i;
2807 digit *pb = b->ob_digit;
2808 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002811 Py_DECREF(z);
2812 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002813 });
Tim Peters0973b992004-08-29 22:16:50 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 while (pb < pbend) {
2816 carry += *pz + *pb++ * f;
2817 *pz++ = (digit)(carry & PyLong_MASK);
2818 carry >>= PyLong_SHIFT;
2819 assert(carry <= PyLong_MASK);
2820 }
2821 if (carry)
2822 *pz += (digit)(carry & PyLong_MASK);
2823 assert((carry >> PyLong_SHIFT) == 0);
2824 }
2825 }
2826 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002827}
2828
2829/* A helper for Karatsuba multiplication (k_mul).
2830 Takes a long "n" and an integer "size" representing the place to
2831 split, and sets low and high such that abs(n) == (high << size) + low,
2832 viewing the shift as being by digits. The sign bit is ignored, and
2833 the return values are >= 0.
2834 Returns 0 on success, -1 on failure.
2835*/
2836static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002837kmul_split(PyLongObject *n,
2838 Py_ssize_t size,
2839 PyLongObject **high,
2840 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 PyLongObject *hi, *lo;
2843 Py_ssize_t size_lo, size_hi;
2844 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 size_lo = MIN(size_n, size);
2847 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 if ((hi = _PyLong_New(size_hi)) == NULL)
2850 return -1;
2851 if ((lo = _PyLong_New(size_lo)) == NULL) {
2852 Py_DECREF(hi);
2853 return -1;
2854 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2857 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 *high = long_normalize(hi);
2860 *low = long_normalize(lo);
2861 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002862}
2863
Tim Peters60004642002-08-12 22:01:34 +00002864static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2865
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866/* Karatsuba multiplication. Ignores the input signs, and returns the
2867 * absolute value of the product (or NULL if error).
2868 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2869 */
2870static PyLongObject *
2871k_mul(PyLongObject *a, PyLongObject *b)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 Py_ssize_t asize = ABS(Py_SIZE(a));
2874 Py_ssize_t bsize = ABS(Py_SIZE(b));
2875 PyLongObject *ah = NULL;
2876 PyLongObject *al = NULL;
2877 PyLongObject *bh = NULL;
2878 PyLongObject *bl = NULL;
2879 PyLongObject *ret = NULL;
2880 PyLongObject *t1, *t2, *t3;
2881 Py_ssize_t shift; /* the number of digits we split off */
2882 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2885 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2886 * Then the original product is
2887 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2888 * By picking X to be a power of 2, "*X" is just shifting, and it's
2889 * been reduced to 3 multiplies on numbers half the size.
2890 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 /* We want to split based on the larger number; fiddle so that b
2893 * is largest.
2894 */
2895 if (asize > bsize) {
2896 t1 = a;
2897 a = b;
2898 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 i = asize;
2901 asize = bsize;
2902 bsize = i;
2903 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 /* Use gradeschool math when either number is too small. */
2906 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2907 if (asize <= i) {
2908 if (asize == 0)
2909 return (PyLongObject *)PyLong_FromLong(0);
2910 else
2911 return x_mul(a, b);
2912 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 /* If a is small compared to b, splitting on b gives a degenerate
2915 * case with ah==0, and Karatsuba may be (even much) less efficient
2916 * than "grade school" then. However, we can still win, by viewing
2917 * b as a string of "big digits", each of width a->ob_size. That
2918 * leads to a sequence of balanced calls to k_mul.
2919 */
2920 if (2 * asize <= bsize)
2921 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 /* Split a & b into hi & lo pieces. */
2924 shift = bsize >> 1;
2925 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2926 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 if (a == b) {
2929 bh = ah;
2930 bl = al;
2931 Py_INCREF(bh);
2932 Py_INCREF(bl);
2933 }
2934 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 /* The plan:
2937 * 1. Allocate result space (asize + bsize digits: that's always
2938 * enough).
2939 * 2. Compute ah*bh, and copy into result at 2*shift.
2940 * 3. Compute al*bl, and copy into result at 0. Note that this
2941 * can't overlap with #2.
2942 * 4. Subtract al*bl from the result, starting at shift. This may
2943 * underflow (borrow out of the high digit), but we don't care:
2944 * we're effectively doing unsigned arithmetic mod
2945 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2946 * borrows and carries out of the high digit can be ignored.
2947 * 5. Subtract ah*bh from the result, starting at shift.
2948 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2949 * at shift.
2950 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* 1. Allocate result space. */
2953 ret = _PyLong_New(asize + bsize);
2954 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002955#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 /* Fill with trash, to catch reference to uninitialized digits. */
2957 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002958#endif
Tim Peters44121a62002-08-12 06:17:58 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2961 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2962 assert(Py_SIZE(t1) >= 0);
2963 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2964 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2965 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 /* Zero-out the digits higher than the ah*bh copy. */
2968 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2969 if (i)
2970 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2971 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 /* 3. t2 <- al*bl, and copy into the low digits. */
2974 if ((t2 = k_mul(al, bl)) == NULL) {
2975 Py_DECREF(t1);
2976 goto fail;
2977 }
2978 assert(Py_SIZE(t2) >= 0);
2979 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2980 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 /* Zero out remaining digits. */
2983 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2984 if (i)
2985 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2988 * because it's fresher in cache.
2989 */
2990 i = Py_SIZE(ret) - shift; /* # digits after shift */
2991 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2992 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2995 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2998 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2999 Py_DECREF(ah);
3000 Py_DECREF(al);
3001 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 if (a == b) {
3004 t2 = t1;
3005 Py_INCREF(t2);
3006 }
3007 else if ((t2 = x_add(bh, bl)) == NULL) {
3008 Py_DECREF(t1);
3009 goto fail;
3010 }
3011 Py_DECREF(bh);
3012 Py_DECREF(bl);
3013 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 t3 = k_mul(t1, t2);
3016 Py_DECREF(t1);
3017 Py_DECREF(t2);
3018 if (t3 == NULL) goto fail;
3019 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 /* Add t3. It's not obvious why we can't run out of room here.
3022 * See the (*) comment after this function.
3023 */
3024 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3025 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003028
Mark Dickinson22b20182010-05-10 21:27:53 +00003029 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 Py_XDECREF(ret);
3031 Py_XDECREF(ah);
3032 Py_XDECREF(al);
3033 Py_XDECREF(bh);
3034 Py_XDECREF(bl);
3035 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003036}
3037
Tim Petersd6974a52002-08-13 20:37:51 +00003038/* (*) Why adding t3 can't "run out of room" above.
3039
Tim Petersab86c2b2002-08-15 20:06:00 +00003040Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3041to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003042
Tim Petersab86c2b2002-08-15 20:06:00 +000030431. For any integer i, i = c(i/2) + f(i/2). In particular,
3044 bsize = c(bsize/2) + f(bsize/2).
30452. shift = f(bsize/2)
30463. asize <= bsize
30474. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3048 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003049
Tim Petersab86c2b2002-08-15 20:06:00 +00003050We allocated asize + bsize result digits, and add t3 into them at an offset
3051of shift. This leaves asize+bsize-shift allocated digit positions for t3
3052to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3053asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003054
Tim Petersab86c2b2002-08-15 20:06:00 +00003055bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3056at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003057
Tim Petersab86c2b2002-08-15 20:06:00 +00003058If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3059digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3060most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003061
Tim Petersab86c2b2002-08-15 20:06:00 +00003062The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003063
Tim Petersab86c2b2002-08-15 20:06:00 +00003064 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003065
Tim Petersab86c2b2002-08-15 20:06:00 +00003066and we have asize + c(bsize/2) available digit positions. We need to show
3067this is always enough. An instance of c(bsize/2) cancels out in both, so
3068the question reduces to whether asize digits is enough to hold
3069(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3070then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3071asize 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 +00003072digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003073asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003074c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3075is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3076bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003077
Tim Peters48d52c02002-08-14 17:07:32 +00003078Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3079clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3080ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003081*/
3082
Tim Peters60004642002-08-12 22:01:34 +00003083/* b has at least twice the digits of a, and a is big enough that Karatsuba
3084 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3085 * of slices, each with a->ob_size digits, and multiply the slices by a,
3086 * one at a time. This gives k_mul balanced inputs to work with, and is
3087 * also cache-friendly (we compute one double-width slice of the result
3088 * at a time, then move on, never bactracking except for the helpful
3089 * single-width slice overlap between successive partial sums).
3090 */
3091static PyLongObject *
3092k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 const Py_ssize_t asize = ABS(Py_SIZE(a));
3095 Py_ssize_t bsize = ABS(Py_SIZE(b));
3096 Py_ssize_t nbdone; /* # of b digits already multiplied */
3097 PyLongObject *ret;
3098 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 assert(asize > KARATSUBA_CUTOFF);
3101 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 /* Allocate result space, and zero it out. */
3104 ret = _PyLong_New(asize + bsize);
3105 if (ret == NULL)
3106 return NULL;
3107 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 /* Successive slices of b are copied into bslice. */
3110 bslice = _PyLong_New(asize);
3111 if (bslice == NULL)
3112 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 nbdone = 0;
3115 while (bsize > 0) {
3116 PyLongObject *product;
3117 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 /* Multiply the next slice of b by a. */
3120 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3121 nbtouse * sizeof(digit));
3122 Py_SIZE(bslice) = nbtouse;
3123 product = k_mul(a, bslice);
3124 if (product == NULL)
3125 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 /* Add into result. */
3128 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3129 product->ob_digit, Py_SIZE(product));
3130 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 bsize -= nbtouse;
3133 nbdone += nbtouse;
3134 }
Tim Peters60004642002-08-12 22:01:34 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 Py_DECREF(bslice);
3137 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003138
Mark Dickinson22b20182010-05-10 21:27:53 +00003139 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_DECREF(ret);
3141 Py_XDECREF(bslice);
3142 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003143}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003144
3145static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003146long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 /* fast path for single-digit multiplication */
3153 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3154 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003155#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003157#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 /* if we don't have long long then we're almost certainly
3159 using 15-bit digits, so v will fit in a long. In the
3160 unlikely event that we're using 30-bit digits on a platform
3161 without long long, a large v will just cause us to fall
3162 through to the general multiplication code below. */
3163 if (v >= LONG_MIN && v <= LONG_MAX)
3164 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003165#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 z = k_mul(a, b);
3169 /* Negate if exactly one of the inputs is negative. */
3170 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3171 NEGATE(z);
3172 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003173}
3174
Guido van Rossume32e0141992-01-19 16:31:05 +00003175/* The / and % operators are now defined in terms of divmod().
3176 The expression a mod b has the value a - b*floor(a/b).
3177 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003178 |a| by |b|, with the sign of a. This is also expressed
3179 as a - b*trunc(a/b), if trunc truncates towards zero.
3180 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 a b a rem b a mod b
3182 13 10 3 3
3183 -13 10 -3 7
3184 13 -10 3 -7
3185 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003186 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003187 have different signs. We then subtract one from the 'div'
3188 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003189
Tim Peters47e52ee2004-08-30 02:44:38 +00003190/* Compute
3191 * *pdiv, *pmod = divmod(v, w)
3192 * NULL can be passed for pdiv or pmod, in which case that part of
3193 * the result is simply thrown away. The caller owns a reference to
3194 * each of these it requests (does not pass NULL for).
3195 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003196static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 if (long_divrem(v, w, &div, &mod) < 0)
3203 return -1;
3204 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3205 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3206 PyLongObject *temp;
3207 PyLongObject *one;
3208 temp = (PyLongObject *) long_add(mod, w);
3209 Py_DECREF(mod);
3210 mod = temp;
3211 if (mod == NULL) {
3212 Py_DECREF(div);
3213 return -1;
3214 }
3215 one = (PyLongObject *) PyLong_FromLong(1L);
3216 if (one == NULL ||
3217 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3218 Py_DECREF(mod);
3219 Py_DECREF(div);
3220 Py_XDECREF(one);
3221 return -1;
3222 }
3223 Py_DECREF(one);
3224 Py_DECREF(div);
3225 div = temp;
3226 }
3227 if (pdiv != NULL)
3228 *pdiv = div;
3229 else
3230 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 if (pmod != NULL)
3233 *pmod = mod;
3234 else
3235 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003238}
3239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003240static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003241long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 CHECK_BINOP(a, b);
3246 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3247 div = NULL;
3248 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003249}
3250
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003251/* PyLong/PyLong -> float, with correctly rounded result. */
3252
3253#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3254#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3255
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003257long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyLongObject *a, *b, *x;
3260 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3261 digit mask, low;
3262 int inexact, negate, a_is_small, b_is_small;
3263 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 CHECK_BINOP(v, w);
3266 a = (PyLongObject *)v;
3267 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 /*
3270 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3273 1. choose a suitable integer 'shift'
3274 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3275 3. adjust x for correct rounding
3276 4. convert x to a double dx with the same value
3277 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3282 returns either 0.0 or -0.0, depending on the sign of b. For a and
3283 b both nonzero, ignore signs of a and b, and add the sign back in
3284 at the end. Now write a_bits and b_bits for the bit lengths of a
3285 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3286 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3291 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3292 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3293 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 1. The integer 'shift' is chosen so that x has the right number of
3298 bits for a double, plus two or three extra bits that will be used
3299 in the rounding decisions. Writing a_bits and b_bits for the
3300 number of significant bits in a and b respectively, a
3301 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 This is fine in the usual case, but if a/b is smaller than the
3306 smallest normal float then it can lead to double rounding on an
3307 IEEE 754 platform, giving incorrectly rounded results. So we
3308 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 2. The quantity x is computed by first shifting a (left -shift bits
3313 if shift <= 0, right shift bits if shift > 0) and then dividing by
3314 b. For both the shift and the division, we keep track of whether
3315 the result is inexact, in a flag 'inexact'; this information is
3316 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 With the choice of shift above, together with our assumption that
3319 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3320 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3323 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 For float representability, we need x/2**extra_bits <
3328 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3329 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 To round, we just modify the bottom digit of x in-place; this can
3334 end up giving a digit with value > PyLONG_MASK, but that's not a
3335 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 With the original choices for shift above, extra_bits will always
3338 be 2 or 3. Then rounding under the round-half-to-even rule, we
3339 round up iff the most significant of the extra bits is 1, and
3340 either: (a) the computation of x in step 2 had an inexact result,
3341 or (b) at least one other of the extra bits is 1, or (c) the least
3342 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 4. Conversion to a double is straightforward; all floating-point
3345 operations involved in the conversion are exact, so there's no
3346 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3349 The result will always be exactly representable as a double, except
3350 in the case that it overflows. To avoid dependence on the exact
3351 behaviour of ldexp on overflow, we check for overflow before
3352 applying ldexp. The result of ldexp is adjusted for sign before
3353 returning.
3354 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* Reduce to case where a and b are both positive. */
3357 a_size = ABS(Py_SIZE(a));
3358 b_size = ABS(Py_SIZE(b));
3359 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3360 if (b_size == 0) {
3361 PyErr_SetString(PyExc_ZeroDivisionError,
3362 "division by zero");
3363 goto error;
3364 }
3365 if (a_size == 0)
3366 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 /* Fast path for a and b small (exactly representable in a double).
3369 Relies on floating-point division being correctly rounded; results
3370 may be subject to double rounding on x86 machines that operate with
3371 the x87 FPU set to 64-bit precision. */
3372 a_is_small = a_size <= MANT_DIG_DIGITS ||
3373 (a_size == MANT_DIG_DIGITS+1 &&
3374 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3375 b_is_small = b_size <= MANT_DIG_DIGITS ||
3376 (b_size == MANT_DIG_DIGITS+1 &&
3377 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3378 if (a_is_small && b_is_small) {
3379 double da, db;
3380 da = a->ob_digit[--a_size];
3381 while (a_size > 0)
3382 da = da * PyLong_BASE + a->ob_digit[--a_size];
3383 db = b->ob_digit[--b_size];
3384 while (b_size > 0)
3385 db = db * PyLong_BASE + b->ob_digit[--b_size];
3386 result = da / db;
3387 goto success;
3388 }
Tim Peterse2a60002001-09-04 06:17:36 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 /* Catch obvious cases of underflow and overflow */
3391 diff = a_size - b_size;
3392 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3393 /* Extreme overflow */
3394 goto overflow;
3395 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3396 /* Extreme underflow */
3397 goto underflow_or_zero;
3398 /* Next line is now safe from overflowing a Py_ssize_t */
3399 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3400 bits_in_digit(b->ob_digit[b_size - 1]);
3401 /* Now diff = a_bits - b_bits. */
3402 if (diff > DBL_MAX_EXP)
3403 goto overflow;
3404 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3405 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 /* Choose value for shift; see comments for step 1 above. */
3408 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 /* x = abs(a * 2**-shift) */
3413 if (shift <= 0) {
3414 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3415 digit rem;
3416 /* x = a << -shift */
3417 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3418 /* In practice, it's probably impossible to end up
3419 here. Both a and b would have to be enormous,
3420 using close to SIZE_T_MAX bytes of memory each. */
3421 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003422 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 goto error;
3424 }
3425 x = _PyLong_New(a_size + shift_digits + 1);
3426 if (x == NULL)
3427 goto error;
3428 for (i = 0; i < shift_digits; i++)
3429 x->ob_digit[i] = 0;
3430 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3431 a_size, -shift % PyLong_SHIFT);
3432 x->ob_digit[a_size + shift_digits] = rem;
3433 }
3434 else {
3435 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3436 digit rem;
3437 /* x = a >> shift */
3438 assert(a_size >= shift_digits);
3439 x = _PyLong_New(a_size - shift_digits);
3440 if (x == NULL)
3441 goto error;
3442 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3443 a_size - shift_digits, shift % PyLong_SHIFT);
3444 /* set inexact if any of the bits shifted out is nonzero */
3445 if (rem)
3446 inexact = 1;
3447 while (!inexact && shift_digits > 0)
3448 if (a->ob_digit[--shift_digits])
3449 inexact = 1;
3450 }
3451 long_normalize(x);
3452 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3455 reference to x, so it's safe to modify it in-place. */
3456 if (b_size == 1) {
3457 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3458 b->ob_digit[0]);
3459 long_normalize(x);
3460 if (rem)
3461 inexact = 1;
3462 }
3463 else {
3464 PyLongObject *div, *rem;
3465 div = x_divrem(x, b, &rem);
3466 Py_DECREF(x);
3467 x = div;
3468 if (x == NULL)
3469 goto error;
3470 if (Py_SIZE(rem))
3471 inexact = 1;
3472 Py_DECREF(rem);
3473 }
3474 x_size = ABS(Py_SIZE(x));
3475 assert(x_size > 0); /* result of division is never zero */
3476 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 /* The number of extra bits that have to be rounded away. */
3479 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3480 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 /* Round by directly modifying the low digit of x. */
3483 mask = (digit)1 << (extra_bits - 1);
3484 low = x->ob_digit[0] | inexact;
3485 if (low & mask && low & (3*mask-1))
3486 low += mask;
3487 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 /* Convert x to a double dx; the conversion is exact. */
3490 dx = x->ob_digit[--x_size];
3491 while (x_size > 0)
3492 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3493 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* Check whether ldexp result will overflow a double. */
3496 if (shift + x_bits >= DBL_MAX_EXP &&
3497 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3498 goto overflow;
3499 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500
3501 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
3504 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003506
3507 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 PyErr_SetString(PyExc_OverflowError,
3509 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003510 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003512}
3513
3514static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003515long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 CHECK_BINOP(a, b);
3520
3521 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3522 mod = NULL;
3523 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003524}
3525
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003526static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003527long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 PyLongObject *div, *mod;
3530 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3535 return NULL;
3536 }
3537 z = PyTuple_New(2);
3538 if (z != NULL) {
3539 PyTuple_SetItem(z, 0, (PyObject *) div);
3540 PyTuple_SetItem(z, 1, (PyObject *) mod);
3541 }
3542 else {
3543 Py_DECREF(div);
3544 Py_DECREF(mod);
3545 }
3546 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003547}
3548
Tim Peters47e52ee2004-08-30 02:44:38 +00003549/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003550static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003551long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3554 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 PyLongObject *z = NULL; /* accumulated result */
3557 Py_ssize_t i, j, k; /* counters */
3558 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 /* 5-ary values. If the exponent is large enough, table is
3561 * precomputed so that table[i] == a**i % c for i in range(32).
3562 */
3563 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3564 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 /* a, b, c = v, w, x */
3567 CHECK_BINOP(v, w);
3568 a = (PyLongObject*)v; Py_INCREF(a);
3569 b = (PyLongObject*)w; Py_INCREF(b);
3570 if (PyLong_Check(x)) {
3571 c = (PyLongObject *)x;
3572 Py_INCREF(x);
3573 }
3574 else if (x == Py_None)
3575 c = NULL;
3576 else {
3577 Py_DECREF(a);
3578 Py_DECREF(b);
3579 Py_INCREF(Py_NotImplemented);
3580 return Py_NotImplemented;
3581 }
Tim Peters4c483c42001-09-05 06:24:58 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3584 if (c) {
3585 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003586 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 goto Error;
3588 }
3589 else {
3590 /* else return a float. This works because we know
3591 that this calls float_pow() which converts its
3592 arguments to double. */
3593 Py_DECREF(a);
3594 Py_DECREF(b);
3595 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3596 }
3597 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 if (c) {
3600 /* if modulus == 0:
3601 raise ValueError() */
3602 if (Py_SIZE(c) == 0) {
3603 PyErr_SetString(PyExc_ValueError,
3604 "pow() 3rd argument cannot be 0");
3605 goto Error;
3606 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* if modulus < 0:
3609 negativeOutput = True
3610 modulus = -modulus */
3611 if (Py_SIZE(c) < 0) {
3612 negativeOutput = 1;
3613 temp = (PyLongObject *)_PyLong_Copy(c);
3614 if (temp == NULL)
3615 goto Error;
3616 Py_DECREF(c);
3617 c = temp;
3618 temp = NULL;
3619 NEGATE(c);
3620 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 /* if modulus == 1:
3623 return 0 */
3624 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3625 z = (PyLongObject *)PyLong_FromLong(0L);
3626 goto Done;
3627 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 /* if base < 0:
3630 base = base % modulus
3631 Having the base positive just makes things easier. */
3632 if (Py_SIZE(a) < 0) {
3633 if (l_divmod(a, c, NULL, &temp) < 0)
3634 goto Error;
3635 Py_DECREF(a);
3636 a = temp;
3637 temp = NULL;
3638 }
3639 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* At this point a, b, and c are guaranteed non-negative UNLESS
3642 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 z = (PyLongObject *)PyLong_FromLong(1L);
3645 if (z == NULL)
3646 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* Perform a modular reduction, X = X % c, but leave X alone if c
3649 * is NULL.
3650 */
3651#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003652 do { \
3653 if (c != NULL) { \
3654 if (l_divmod(X, c, NULL, &temp) < 0) \
3655 goto Error; \
3656 Py_XDECREF(X); \
3657 X = temp; \
3658 temp = NULL; \
3659 } \
3660 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* Multiply two values, then reduce the result:
3663 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003664#define MULT(X, Y, result) \
3665 do { \
3666 temp = (PyLongObject *)long_mul(X, Y); \
3667 if (temp == NULL) \
3668 goto Error; \
3669 Py_XDECREF(result); \
3670 result = temp; \
3671 temp = NULL; \
3672 REDUCE(result); \
3673 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3676 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3677 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3678 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3679 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003682 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003684 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 }
3686 }
3687 }
3688 else {
3689 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3690 Py_INCREF(z); /* still holds 1L */
3691 table[0] = z;
3692 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003693 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3696 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3699 const int index = (bi >> j) & 0x1f;
3700 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003701 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003703 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 }
3705 }
3706 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (negativeOutput && (Py_SIZE(z) != 0)) {
3709 temp = (PyLongObject *)long_sub(z, c);
3710 if (temp == NULL)
3711 goto Error;
3712 Py_DECREF(z);
3713 z = temp;
3714 temp = NULL;
3715 }
3716 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003717
Mark Dickinson22b20182010-05-10 21:27:53 +00003718 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (z != NULL) {
3720 Py_DECREF(z);
3721 z = NULL;
3722 }
3723 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003724 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3726 for (i = 0; i < 32; ++i)
3727 Py_XDECREF(table[i]);
3728 }
3729 Py_DECREF(a);
3730 Py_DECREF(b);
3731 Py_XDECREF(c);
3732 Py_XDECREF(temp);
3733 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003734}
3735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003736static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003737long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 /* Implement ~x as -(x+1) */
3740 PyLongObject *x;
3741 PyLongObject *w;
3742 if (ABS(Py_SIZE(v)) <=1)
3743 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3744 w = (PyLongObject *)PyLong_FromLong(1L);
3745 if (w == NULL)
3746 return NULL;
3747 x = (PyLongObject *) long_add(v, w);
3748 Py_DECREF(w);
3749 if (x == NULL)
3750 return NULL;
3751 Py_SIZE(x) = -(Py_SIZE(x));
3752 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003753}
3754
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003755static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003756long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 PyLongObject *z;
3759 if (ABS(Py_SIZE(v)) <= 1)
3760 return PyLong_FromLong(-MEDIUM_VALUE(v));
3761 z = (PyLongObject *)_PyLong_Copy(v);
3762 if (z != NULL)
3763 Py_SIZE(z) = -(Py_SIZE(v));
3764 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003765}
3766
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003767static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003768long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 if (Py_SIZE(v) < 0)
3771 return long_neg(v);
3772 else
3773 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003774}
3775
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003776static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003777long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003780}
3781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003782static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003783long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 PyLongObject *z = NULL;
3786 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3787 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 if (Py_SIZE(a) < 0) {
3792 /* Right shifting negative numbers is harder */
3793 PyLongObject *a1, *a2;
3794 a1 = (PyLongObject *) long_invert(a);
3795 if (a1 == NULL)
3796 goto rshift_error;
3797 a2 = (PyLongObject *) long_rshift(a1, b);
3798 Py_DECREF(a1);
3799 if (a2 == NULL)
3800 goto rshift_error;
3801 z = (PyLongObject *) long_invert(a2);
3802 Py_DECREF(a2);
3803 }
3804 else {
3805 shiftby = PyLong_AsSsize_t((PyObject *)b);
3806 if (shiftby == -1L && PyErr_Occurred())
3807 goto rshift_error;
3808 if (shiftby < 0) {
3809 PyErr_SetString(PyExc_ValueError,
3810 "negative shift count");
3811 goto rshift_error;
3812 }
3813 wordshift = shiftby / PyLong_SHIFT;
3814 newsize = ABS(Py_SIZE(a)) - wordshift;
3815 if (newsize <= 0)
3816 return PyLong_FromLong(0);
3817 loshift = shiftby % PyLong_SHIFT;
3818 hishift = PyLong_SHIFT - loshift;
3819 lomask = ((digit)1 << hishift) - 1;
3820 himask = PyLong_MASK ^ lomask;
3821 z = _PyLong_New(newsize);
3822 if (z == NULL)
3823 goto rshift_error;
3824 if (Py_SIZE(a) < 0)
3825 Py_SIZE(z) = -(Py_SIZE(z));
3826 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3827 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3828 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003829 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 }
3831 z = long_normalize(z);
3832 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003833 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003835
Guido van Rossumc6913e71991-11-19 20:26:46 +00003836}
3837
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003838static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003839long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 /* This version due to Tim Peters */
3842 PyLongObject *a = (PyLongObject*)v;
3843 PyLongObject *b = (PyLongObject*)w;
3844 PyLongObject *z = NULL;
3845 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3846 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 shiftby = PyLong_AsSsize_t((PyObject *)b);
3851 if (shiftby == -1L && PyErr_Occurred())
3852 goto lshift_error;
3853 if (shiftby < 0) {
3854 PyErr_SetString(PyExc_ValueError, "negative shift count");
3855 goto lshift_error;
3856 }
3857 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3858 wordshift = shiftby / PyLong_SHIFT;
3859 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 oldsize = ABS(Py_SIZE(a));
3862 newsize = oldsize + wordshift;
3863 if (remshift)
3864 ++newsize;
3865 z = _PyLong_New(newsize);
3866 if (z == NULL)
3867 goto lshift_error;
3868 if (Py_SIZE(a) < 0)
3869 NEGATE(z);
3870 for (i = 0; i < wordshift; i++)
3871 z->ob_digit[i] = 0;
3872 accum = 0;
3873 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3874 accum |= (twodigits)a->ob_digit[j] << remshift;
3875 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3876 accum >>= PyLong_SHIFT;
3877 }
3878 if (remshift)
3879 z->ob_digit[newsize-1] = (digit)accum;
3880 else
3881 assert(!accum);
3882 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003883 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003885}
3886
Mark Dickinson27a87a22009-10-25 20:43:34 +00003887/* Compute two's complement of digit vector a[0:m], writing result to
3888 z[0:m]. The digit vector a need not be normalized, but should not
3889 be entirely zero. a and z may point to the same digit vector. */
3890
3891static void
3892v_complement(digit *z, digit *a, Py_ssize_t m)
3893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 Py_ssize_t i;
3895 digit carry = 1;
3896 for (i = 0; i < m; ++i) {
3897 carry += a[i] ^ PyLong_MASK;
3898 z[i] = carry & PyLong_MASK;
3899 carry >>= PyLong_SHIFT;
3900 }
3901 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003902}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003903
3904/* Bitwise and/xor/or operations */
3905
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003906static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003907long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003909 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 int nega, negb, negz;
3912 Py_ssize_t size_a, size_b, size_z, i;
3913 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 /* Bitwise operations for negative numbers operate as though
3916 on a two's complement representation. So convert arguments
3917 from sign-magnitude to two's complement, and convert the
3918 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 /* If a is negative, replace it by its two's complement. */
3921 size_a = ABS(Py_SIZE(a));
3922 nega = Py_SIZE(a) < 0;
3923 if (nega) {
3924 z = _PyLong_New(size_a);
3925 if (z == NULL)
3926 return NULL;
3927 v_complement(z->ob_digit, a->ob_digit, size_a);
3928 a = z;
3929 }
3930 else
3931 /* Keep reference count consistent. */
3932 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 /* Same for b. */
3935 size_b = ABS(Py_SIZE(b));
3936 negb = Py_SIZE(b) < 0;
3937 if (negb) {
3938 z = _PyLong_New(size_b);
3939 if (z == NULL) {
3940 Py_DECREF(a);
3941 return NULL;
3942 }
3943 v_complement(z->ob_digit, b->ob_digit, size_b);
3944 b = z;
3945 }
3946 else
3947 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 /* Swap a and b if necessary to ensure size_a >= size_b. */
3950 if (size_a < size_b) {
3951 z = a; a = b; b = z;
3952 size_z = size_a; size_a = size_b; size_b = size_z;
3953 negz = nega; nega = negb; negb = negz;
3954 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 /* JRH: The original logic here was to allocate the result value (z)
3957 as the longer of the two operands. However, there are some cases
3958 where the result is guaranteed to be shorter than that: AND of two
3959 positives, OR of two negatives: use the shorter number. AND with
3960 mixed signs: use the positive number. OR with mixed signs: use the
3961 negative number.
3962 */
3963 switch (op) {
3964 case '^':
3965 negz = nega ^ negb;
3966 size_z = size_a;
3967 break;
3968 case '&':
3969 negz = nega & negb;
3970 size_z = negb ? size_a : size_b;
3971 break;
3972 case '|':
3973 negz = nega | negb;
3974 size_z = negb ? size_b : size_a;
3975 break;
3976 default:
3977 PyErr_BadArgument();
3978 return NULL;
3979 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 /* We allow an extra digit if z is negative, to make sure that
3982 the final two's complement of z doesn't overflow. */
3983 z = _PyLong_New(size_z + negz);
3984 if (z == NULL) {
3985 Py_DECREF(a);
3986 Py_DECREF(b);
3987 return NULL;
3988 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 /* Compute digits for overlap of a and b. */
3991 switch(op) {
3992 case '&':
3993 for (i = 0; i < size_b; ++i)
3994 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3995 break;
3996 case '|':
3997 for (i = 0; i < size_b; ++i)
3998 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3999 break;
4000 case '^':
4001 for (i = 0; i < size_b; ++i)
4002 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4003 break;
4004 default:
4005 PyErr_BadArgument();
4006 return NULL;
4007 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 /* Copy any remaining digits of a, inverting if necessary. */
4010 if (op == '^' && negb)
4011 for (; i < size_z; ++i)
4012 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4013 else if (i < size_z)
4014 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4015 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 /* Complement result if negative. */
4018 if (negz) {
4019 Py_SIZE(z) = -(Py_SIZE(z));
4020 z->ob_digit[size_z] = PyLong_MASK;
4021 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4022 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 Py_DECREF(a);
4025 Py_DECREF(b);
4026 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004027}
4028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004029static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004030long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 PyObject *c;
4033 CHECK_BINOP(a, b);
4034 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4035 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004036}
4037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004038static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004039long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 PyObject *c;
4042 CHECK_BINOP(a, b);
4043 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4044 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004045}
4046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004047static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004048long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 PyObject *c;
4051 CHECK_BINOP(a, b);
4052 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4053 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004054}
4055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004056static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004057long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (PyLong_CheckExact(v))
4060 Py_INCREF(v);
4061 else
4062 v = _PyLong_Copy((PyLongObject *)v);
4063 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004064}
4065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004066static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004067long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 double result;
4070 result = PyLong_AsDouble(v);
4071 if (result == -1.0 && PyErr_Occurred())
4072 return NULL;
4073 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004074}
4075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004076static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004077long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004078
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079static PyObject *
4080long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 PyObject *x = NULL;
4083 int base = -909; /* unlikely! */
4084 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 if (type != &PyLong_Type)
4087 return long_subtype_new(type, args, kwds); /* Wimp out */
4088 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
4089 &x, &base))
4090 return NULL;
4091 if (x == NULL)
4092 return PyLong_FromLong(0L);
4093 if (base == -909)
4094 return PyNumber_Long(x);
4095 else if (PyUnicode_Check(x))
4096 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4097 PyUnicode_GET_SIZE(x),
4098 base);
4099 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4100 /* Since PyLong_FromString doesn't have a length parameter,
4101 * check here for possible NULs in the string. */
4102 char *string;
4103 Py_ssize_t size = Py_SIZE(x);
4104 if (PyByteArray_Check(x))
4105 string = PyByteArray_AS_STRING(x);
4106 else
4107 string = PyBytes_AS_STRING(x);
4108 if (strlen(string) != (size_t)size) {
4109 /* We only see this if there's a null byte in x,
4110 x is a bytes or buffer, *and* a base is given. */
4111 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004112 "invalid literal for int() with base %d: %R",
4113 base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 return NULL;
4115 }
4116 return PyLong_FromString(string, NULL, base);
4117 }
4118 else {
4119 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004120 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 return NULL;
4122 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123}
4124
Guido van Rossumbef14172001-08-29 15:47:46 +00004125/* Wimpy, slow approach to tp_new calls for subtypes of long:
4126 first create a regular long from whatever arguments we got,
4127 then allocate a subtype instance and initialize it from
4128 the regular long. The regular long is then thrown away.
4129*/
4130static PyObject *
4131long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 PyLongObject *tmp, *newobj;
4134 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 assert(PyType_IsSubtype(type, &PyLong_Type));
4137 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4138 if (tmp == NULL)
4139 return NULL;
4140 assert(PyLong_CheckExact(tmp));
4141 n = Py_SIZE(tmp);
4142 if (n < 0)
4143 n = -n;
4144 newobj = (PyLongObject *)type->tp_alloc(type, n);
4145 if (newobj == NULL) {
4146 Py_DECREF(tmp);
4147 return NULL;
4148 }
4149 assert(PyLong_Check(newobj));
4150 Py_SIZE(newobj) = Py_SIZE(tmp);
4151 for (i = 0; i < n; i++)
4152 newobj->ob_digit[i] = tmp->ob_digit[i];
4153 Py_DECREF(tmp);
4154 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004155}
4156
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004157static PyObject *
4158long_getnewargs(PyLongObject *v)
4159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004161}
4162
Guido van Rossumb43daf72007-08-01 18:08:08 +00004163static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004164long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004166}
4167
4168static PyObject *
4169long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004171}
4172
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004173static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004174long__format__(PyObject *self, PyObject *args)
4175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4179 return NULL;
4180 return _PyLong_FormatAdvanced(self,
4181 PyUnicode_AS_UNICODE(format_spec),
4182 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004183}
4184
Eric Smith8c663262007-08-25 02:26:07 +00004185static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004186long_round(PyObject *self, PyObject *args)
4187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 PyObject *o_ndigits=NULL, *temp;
4189 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
4190 int errcode;
4191 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
4194 the straightforward method is:
Mark Dickinson1124e712009-01-28 21:25:58 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 (1) divide by 10**n
4197 (2) round to nearest integer (round to even in case of tie)
4198 (3) multiply result by 10**n.
Mark Dickinson1124e712009-01-28 21:25:58 +00004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 But the rounding step involves examining the fractional part of the
4201 quotient to see whether it's greater than 0.5 or not. Since we
4202 want to do the whole calculation in integer arithmetic, it's
4203 simpler to do:
Mark Dickinson1124e712009-01-28 21:25:58 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 (1) divide by (10**n)/2
4206 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
4207 (3) multiply result by (10**n)/2.
Mark Dickinson1124e712009-01-28 21:25:58 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 Then all we need to know about the fractional part of the quotient
4210 arising in step (2) is whether it's zero or not.
Mark Dickinson1124e712009-01-28 21:25:58 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 Doing both a multiplication and division is wasteful, and is easily
4213 avoided if we just figure out how much to adjust the original input
4214 by to do the rounding.
Mark Dickinson1124e712009-01-28 21:25:58 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 Here's the whole algorithm expressed in Python.
Mark Dickinson1124e712009-01-28 21:25:58 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 def round(self, ndigits = None):
4219 """round(int, int) -> int"""
4220 if ndigits is None or ndigits >= 0:
4221 return self
4222 pow = 10**-ndigits >> 1
4223 q, r = divmod(self, pow)
4224 self -= r
4225 if (q & 1 != 0):
4226 if (q & 2 == r == 0):
4227 self -= pow
4228 else:
4229 self += pow
4230 return self
Mark Dickinson1124e712009-01-28 21:25:58 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 */
4233 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4234 return NULL;
4235 if (o_ndigits == NULL)
4236 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
4239 if (ndigits == NULL)
4240 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 if (Py_SIZE(ndigits) >= 0) {
4243 Py_DECREF(ndigits);
4244 return long_long(self);
4245 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 Py_INCREF(self); /* to keep refcounting simple */
4248 /* we now own references to self, ndigits */
Mark Dickinson1124e712009-01-28 21:25:58 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 /* pow = 10 ** -ndigits >> 1 */
4251 pow = (PyLongObject *)PyLong_FromLong(10L);
4252 if (pow == NULL)
4253 goto error;
4254 temp = long_neg(ndigits);
4255 Py_DECREF(ndigits);
4256 ndigits = (PyLongObject *)temp;
4257 if (ndigits == NULL)
4258 goto error;
4259 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4260 Py_DECREF(pow);
4261 pow = (PyLongObject *)temp;
4262 if (pow == NULL)
4263 goto error;
4264 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4265 one = (PyLongObject *)PyLong_FromLong(1L);
4266 if (one == NULL)
4267 goto error;
4268 temp = long_rshift(pow, one);
4269 Py_DECREF(one);
4270 Py_DECREF(pow);
4271 pow = (PyLongObject *)temp;
4272 if (pow == NULL)
4273 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 /* q, r = divmod(self, pow) */
4276 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4277 if (errcode == -1)
4278 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 /* self -= r */
4281 temp = long_sub((PyLongObject *)self, r);
4282 Py_DECREF(self);
4283 self = temp;
4284 if (self == NULL)
4285 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 /* get value of quotient modulo 4 */
4288 if (Py_SIZE(q) == 0)
4289 q_mod_4 = 0;
4290 else if (Py_SIZE(q) > 0)
4291 q_mod_4 = q->ob_digit[0] & 3;
4292 else
4293 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
Mark Dickinson1124e712009-01-28 21:25:58 +00004294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 if ((q_mod_4 & 1) == 1) {
4296 /* q is odd; round self up or down by adding or subtracting pow */
4297 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4298 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4299 else
4300 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4301 Py_DECREF(self);
4302 self = temp;
4303 if (self == NULL)
4304 goto error;
4305 }
4306 Py_DECREF(q);
4307 Py_DECREF(r);
4308 Py_DECREF(pow);
4309 Py_DECREF(ndigits);
4310 return self;
Mark Dickinson1124e712009-01-28 21:25:58 +00004311
4312 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 Py_XDECREF(q);
4314 Py_XDECREF(r);
4315 Py_XDECREF(pow);
4316 Py_XDECREF(self);
4317 Py_XDECREF(ndigits);
4318 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004319}
4320
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004321static PyObject *
4322long_sizeof(PyLongObject *v)
4323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4327 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004328}
4329
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004330static PyObject *
4331long_bit_length(PyLongObject *v)
4332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 PyLongObject *result, *x, *y;
4334 Py_ssize_t ndigits, msd_bits = 0;
4335 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 assert(v != NULL);
4338 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 ndigits = ABS(Py_SIZE(v));
4341 if (ndigits == 0)
4342 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 msd = v->ob_digit[ndigits-1];
4345 while (msd >= 32) {
4346 msd_bits += 6;
4347 msd >>= 6;
4348 }
4349 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4352 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 /* expression above may overflow; use Python integers instead */
4355 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4356 if (result == NULL)
4357 return NULL;
4358 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4359 if (x == NULL)
4360 goto error;
4361 y = (PyLongObject *)long_mul(result, x);
4362 Py_DECREF(x);
4363 if (y == NULL)
4364 goto error;
4365 Py_DECREF(result);
4366 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4369 if (x == NULL)
4370 goto error;
4371 y = (PyLongObject *)long_add(result, x);
4372 Py_DECREF(x);
4373 if (y == NULL)
4374 goto error;
4375 Py_DECREF(result);
4376 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004379
Mark Dickinson22b20182010-05-10 21:27:53 +00004380 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 Py_DECREF(result);
4382 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004383}
4384
4385PyDoc_STRVAR(long_bit_length_doc,
4386"int.bit_length() -> int\n\
4387\n\
4388Number of bits necessary to represent self in binary.\n\
4389>>> bin(37)\n\
4390'0b100101'\n\
4391>>> (37).bit_length()\n\
43926");
4393
Christian Heimes53876d92008-04-19 00:31:39 +00004394#if 0
4395static PyObject *
4396long_is_finite(PyObject *v)
4397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004399}
4400#endif
4401
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004402
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004403static PyObject *
4404long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 PyObject *byteorder_str;
4407 PyObject *is_signed_obj = NULL;
4408 Py_ssize_t length;
4409 int little_endian;
4410 int is_signed;
4411 PyObject *bytes;
4412 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4415 &length, &byteorder_str,
4416 &is_signed_obj))
4417 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 if (args != NULL && Py_SIZE(args) > 2) {
4420 PyErr_SetString(PyExc_TypeError,
4421 "'signed' is a keyword-only argument");
4422 return NULL;
4423 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4426 little_endian = 1;
4427 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4428 little_endian = 0;
4429 else {
4430 PyErr_SetString(PyExc_ValueError,
4431 "byteorder must be either 'little' or 'big'");
4432 return NULL;
4433 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (is_signed_obj != NULL) {
4436 int cmp = PyObject_IsTrue(is_signed_obj);
4437 if (cmp < 0)
4438 return NULL;
4439 is_signed = cmp ? 1 : 0;
4440 }
4441 else {
4442 /* If the signed argument was omitted, use False as the
4443 default. */
4444 is_signed = 0;
4445 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 if (length < 0) {
4448 PyErr_SetString(PyExc_ValueError,
4449 "length argument must be non-negative");
4450 return NULL;
4451 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 bytes = PyBytes_FromStringAndSize(NULL, length);
4454 if (bytes == NULL)
4455 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4458 length, little_endian, is_signed) < 0) {
4459 Py_DECREF(bytes);
4460 return NULL;
4461 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004464}
4465
Mark Dickinson078c2532010-01-30 18:06:17 +00004466PyDoc_STRVAR(long_to_bytes_doc,
4467"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004468\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004469Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004470\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004472raised if the integer is not representable with the given number of\n\
4473bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004474\n\
4475The byteorder argument determines the byte order used to represent the\n\
4476integer. If byteorder is 'big', the most significant byte is at the\n\
4477beginning of the byte array. If byteorder is 'little', the most\n\
4478significant byte is at the end of the byte array. To request the native\n\
4479byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4480\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004481The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004483is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004484
4485static PyObject *
4486long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488 PyObject *byteorder_str;
4489 PyObject *is_signed_obj = NULL;
4490 int little_endian;
4491 int is_signed;
4492 PyObject *obj;
4493 PyObject *bytes;
4494 PyObject *long_obj;
4495 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4498 &obj, &byteorder_str,
4499 &is_signed_obj))
4500 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 if (args != NULL && Py_SIZE(args) > 2) {
4503 PyErr_SetString(PyExc_TypeError,
4504 "'signed' is a keyword-only argument");
4505 return NULL;
4506 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4509 little_endian = 1;
4510 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4511 little_endian = 0;
4512 else {
4513 PyErr_SetString(PyExc_ValueError,
4514 "byteorder must be either 'little' or 'big'");
4515 return NULL;
4516 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 if (is_signed_obj != NULL) {
4519 int cmp = PyObject_IsTrue(is_signed_obj);
4520 if (cmp < 0)
4521 return NULL;
4522 is_signed = cmp ? 1 : 0;
4523 }
4524 else {
4525 /* If the signed argument was omitted, use False as the
4526 default. */
4527 is_signed = 0;
4528 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 bytes = PyObject_Bytes(obj);
4531 if (bytes == NULL)
4532 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 long_obj = _PyLong_FromByteArray(
4535 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4536 little_endian, is_signed);
4537 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 /* If from_bytes() was used on subclass, allocate new subclass
4540 * instance, initialize it with decoded long value and return it.
4541 */
4542 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4543 PyLongObject *newobj;
4544 int i;
4545 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 newobj = (PyLongObject *)type->tp_alloc(type, n);
4548 if (newobj == NULL) {
4549 Py_DECREF(long_obj);
4550 return NULL;
4551 }
4552 assert(PyLong_Check(newobj));
4553 Py_SIZE(newobj) = Py_SIZE(long_obj);
4554 for (i = 0; i < n; i++) {
4555 newobj->ob_digit[i] =
4556 ((PyLongObject *)long_obj)->ob_digit[i];
4557 }
4558 Py_DECREF(long_obj);
4559 return (PyObject *)newobj;
4560 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004563}
4564
Mark Dickinson078c2532010-01-30 18:06:17 +00004565PyDoc_STRVAR(long_from_bytes_doc,
4566"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4567\n\
4568Return the integer represented by the given array of bytes.\n\
4569\n\
4570The bytes argument must either support the buffer protocol or be an\n\
4571iterable object producing bytes. Bytes and bytearray are examples of\n\
4572built-in objects that support the buffer protocol.\n\
4573\n\
4574The byteorder argument determines the byte order used to represent the\n\
4575integer. If byteorder is 'big', the most significant byte is at the\n\
4576beginning of the byte array. If byteorder is 'little', the most\n\
4577significant byte is at the end of the byte array. To request the native\n\
4578byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4579\n\
4580The signed keyword-only argument indicates whether two's complement is\n\
4581used to represent the integer.");
4582
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004583static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4585 "Returns self, the complex conjugate of any int."},
4586 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4587 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004588#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4590 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004591#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 {"to_bytes", (PyCFunction)long_to_bytes,
4593 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4594 {"from_bytes", (PyCFunction)long_from_bytes,
4595 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4596 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4597 "Truncating an Integral returns itself."},
4598 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4599 "Flooring an Integral returns itself."},
4600 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4601 "Ceiling of an Integral returns itself."},
4602 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4603 "Rounding an Integral returns itself.\n"
4604 "Rounding with an ndigits argument also returns an integer."},
4605 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4606 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4607 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4608 "Returns size in memory, in bytes"},
4609 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004610};
4611
Guido van Rossumb43daf72007-08-01 18:08:08 +00004612static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004613 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004614 (getter)long_long, (setter)NULL,
4615 "the real part of a complex number",
4616 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004617 {"imag",
4618 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004619 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004620 NULL},
4621 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004622 (getter)long_long, (setter)NULL,
4623 "the numerator of a rational number in lowest terms",
4624 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004625 {"denominator",
4626 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004627 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004628 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004629 {NULL} /* Sentinel */
4630};
4631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004632PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004633"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004635Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636point argument will be truncated towards zero (this does not include a\n\
4637string representation of a floating point number!) When converting a\n\
4638string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004639converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004641static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004642 (binaryfunc)long_add, /*nb_add*/
4643 (binaryfunc)long_sub, /*nb_subtract*/
4644 (binaryfunc)long_mul, /*nb_multiply*/
4645 long_mod, /*nb_remainder*/
4646 long_divmod, /*nb_divmod*/
4647 long_pow, /*nb_power*/
4648 (unaryfunc)long_neg, /*nb_negative*/
4649 (unaryfunc)long_long, /*tp_positive*/
4650 (unaryfunc)long_abs, /*tp_absolute*/
4651 (inquiry)long_bool, /*tp_bool*/
4652 (unaryfunc)long_invert, /*nb_invert*/
4653 long_lshift, /*nb_lshift*/
4654 (binaryfunc)long_rshift, /*nb_rshift*/
4655 long_and, /*nb_and*/
4656 long_xor, /*nb_xor*/
4657 long_or, /*nb_or*/
4658 long_long, /*nb_int*/
4659 0, /*nb_reserved*/
4660 long_float, /*nb_float*/
4661 0, /* nb_inplace_add */
4662 0, /* nb_inplace_subtract */
4663 0, /* nb_inplace_multiply */
4664 0, /* nb_inplace_remainder */
4665 0, /* nb_inplace_power */
4666 0, /* nb_inplace_lshift */
4667 0, /* nb_inplace_rshift */
4668 0, /* nb_inplace_and */
4669 0, /* nb_inplace_xor */
4670 0, /* nb_inplace_or */
4671 long_div, /* nb_floor_divide */
4672 long_true_divide, /* nb_true_divide */
4673 0, /* nb_inplace_floor_divide */
4674 0, /* nb_inplace_true_divide */
4675 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004676};
4677
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004678PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4680 "int", /* tp_name */
4681 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4682 sizeof(digit), /* tp_itemsize */
4683 long_dealloc, /* tp_dealloc */
4684 0, /* tp_print */
4685 0, /* tp_getattr */
4686 0, /* tp_setattr */
4687 0, /* tp_reserved */
4688 long_to_decimal_string, /* tp_repr */
4689 &long_as_number, /* tp_as_number */
4690 0, /* tp_as_sequence */
4691 0, /* tp_as_mapping */
4692 (hashfunc)long_hash, /* tp_hash */
4693 0, /* tp_call */
4694 long_to_decimal_string, /* tp_str */
4695 PyObject_GenericGetAttr, /* tp_getattro */
4696 0, /* tp_setattro */
4697 0, /* tp_as_buffer */
4698 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4699 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4700 long_doc, /* tp_doc */
4701 0, /* tp_traverse */
4702 0, /* tp_clear */
4703 long_richcompare, /* tp_richcompare */
4704 0, /* tp_weaklistoffset */
4705 0, /* tp_iter */
4706 0, /* tp_iternext */
4707 long_methods, /* tp_methods */
4708 0, /* tp_members */
4709 long_getset, /* tp_getset */
4710 0, /* tp_base */
4711 0, /* tp_dict */
4712 0, /* tp_descr_get */
4713 0, /* tp_descr_set */
4714 0, /* tp_dictoffset */
4715 0, /* tp_init */
4716 0, /* tp_alloc */
4717 long_new, /* tp_new */
4718 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004719};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004720
Mark Dickinsonbd792642009-03-18 20:06:12 +00004721static PyTypeObject Int_InfoType;
4722
4723PyDoc_STRVAR(int_info__doc__,
4724"sys.int_info\n\
4725\n\
4726A struct sequence that holds information about Python's\n\
4727internal representation of integers. The attributes are read only.");
4728
4729static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004731 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004733};
4734
4735static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 "sys.int_info", /* name */
4737 int_info__doc__, /* doc */
4738 int_info_fields, /* fields */
4739 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004740};
4741
4742PyObject *
4743PyLong_GetInfo(void)
4744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 PyObject* int_info;
4746 int field = 0;
4747 int_info = PyStructSequence_New(&Int_InfoType);
4748 if (int_info == NULL)
4749 return NULL;
4750 PyStructSequence_SET_ITEM(int_info, field++,
4751 PyLong_FromLong(PyLong_SHIFT));
4752 PyStructSequence_SET_ITEM(int_info, field++,
4753 PyLong_FromLong(sizeof(digit)));
4754 if (PyErr_Occurred()) {
4755 Py_CLEAR(int_info);
4756 return NULL;
4757 }
4758 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004759}
4760
Guido van Rossumddefaf32007-01-14 03:31:43 +00004761int
4762_PyLong_Init(void)
4763{
4764#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 int ival, size;
4766 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4769 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4770 if (Py_TYPE(v) == &PyLong_Type) {
4771 /* The element is already initialized, most likely
4772 * the Python interpreter was initialized before.
4773 */
4774 Py_ssize_t refcnt;
4775 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4778 _Py_NewReference(op);
4779 /* _Py_NewReference sets the ref count to 1 but
4780 * the ref count might be larger. Set the refcnt
4781 * to the original refcnt + 1 */
4782 Py_REFCNT(op) = refcnt + 1;
4783 assert(Py_SIZE(op) == size);
4784 assert(v->ob_digit[0] == abs(ival));
4785 }
4786 else {
4787 PyObject_INIT(v, &PyLong_Type);
4788 }
4789 Py_SIZE(v) = size;
4790 v->ob_digit[0] = abs(ival);
4791 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004792#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 /* initialize int_info */
4794 if (Int_InfoType.tp_name == 0)
4795 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004798}
4799
4800void
4801PyLong_Fini(void)
4802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 /* Integers are currently statically allocated. Py_DECREF is not
4804 needed, but Python must forget about the reference or multiple
4805 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004806#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 int i;
4808 PyLongObject *v = small_ints;
4809 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4810 _Py_DEC_REFTOTAL;
4811 _Py_ForgetReference((PyObject*)v);
4812 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004813#endif
4814}