blob: 2aac8e4051547988b8ace1b0747eb79e3679657a [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000437/* Get a Py_ssize_t from a long int object.
438 Returns -1 and sets an error condition if overflow occurs. */
439
440Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register PyLongObject *v;
443 size_t x, prev;
444 Py_ssize_t i;
445 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (vv == NULL) {
448 PyErr_BadInternalCall();
449 return -1;
450 }
451 if (!PyLong_Check(vv)) {
452 PyErr_SetString(PyExc_TypeError, "an integer is required");
453 return -1;
454 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 v = (PyLongObject *)vv;
457 i = Py_SIZE(v);
458 switch (i) {
459 case -1: return -(sdigit)v->ob_digit[0];
460 case 0: return 0;
461 case 1: return v->ob_digit[0];
462 }
463 sign = 1;
464 x = 0;
465 if (i < 0) {
466 sign = -1;
467 i = -(i);
468 }
469 while (--i >= 0) {
470 prev = x;
471 x = (x << PyLong_SHIFT) | v->ob_digit[i];
472 if ((x >> PyLong_SHIFT) != prev)
473 goto overflow;
474 }
475 /* Haven't lost any bits, but casting to a signed type requires
476 * extra care (see comment above).
477 */
478 if (x <= (size_t)PY_SSIZE_T_MAX) {
479 return (Py_ssize_t)x * sign;
480 }
481 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
482 return PY_SSIZE_T_MIN;
483 }
484 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485
Mark Dickinson22b20182010-05-10 21:27:53 +0000486 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C ssize_t");
489 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490}
491
Guido van Rossumd8c80482002-08-13 00:24:58 +0000492/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 Returns -1 and sets an error condition if overflow occurs. */
494
495unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000496PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 register PyLongObject *v;
499 unsigned long x, prev;
500 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (vv == NULL) {
503 PyErr_BadInternalCall();
504 return (unsigned long)-1;
505 }
506 if (!PyLong_Check(vv)) {
507 PyErr_SetString(PyExc_TypeError, "an integer is required");
508 return (unsigned long)-1;
509 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 v = (PyLongObject *)vv;
512 i = Py_SIZE(v);
513 x = 0;
514 if (i < 0) {
515 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000516 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return (unsigned long) -1;
518 }
519 switch (i) {
520 case 0: return 0;
521 case 1: return v->ob_digit[0];
522 }
523 while (--i >= 0) {
524 prev = x;
525 x = (x << PyLong_SHIFT) | v->ob_digit[i];
526 if ((x >> PyLong_SHIFT) != prev) {
527 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000528 "python int too large to convert "
529 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 }
533 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534}
535
Stefan Krahb77c6c62011-09-12 16:22:47 +0200536/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
537 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
539size_t
540PyLong_AsSize_t(PyObject *vv)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 register PyLongObject *v;
543 size_t x, prev;
544 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (vv == NULL) {
547 PyErr_BadInternalCall();
548 return (size_t) -1;
549 }
550 if (!PyLong_Check(vv)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return (size_t)-1;
553 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 v = (PyLongObject *)vv;
556 i = Py_SIZE(v);
557 x = 0;
558 if (i < 0) {
559 PyErr_SetString(PyExc_OverflowError,
560 "can't convert negative value to size_t");
561 return (size_t) -1;
562 }
563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
567 while (--i >= 0) {
568 prev = x;
569 x = (x << PyLong_SHIFT) | v->ob_digit[i];
570 if ((x >> PyLong_SHIFT) != prev) {
571 PyErr_SetString(PyExc_OverflowError,
572 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200573 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
576 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000577}
578
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579/* Get a C unsigned long int from a long int object, ignoring the high bits.
580 Returns -1 and sets an error condition if an error occurs. */
581
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582static unsigned long
583_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 register PyLongObject *v;
586 unsigned long x;
587 Py_ssize_t i;
588 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (vv == NULL || !PyLong_Check(vv)) {
591 PyErr_BadInternalCall();
592 return (unsigned long) -1;
593 }
594 v = (PyLongObject *)vv;
595 i = Py_SIZE(v);
596 switch (i) {
597 case 0: return 0;
598 case 1: return v->ob_digit[0];
599 }
600 sign = 1;
601 x = 0;
602 if (i < 0) {
603 sign = -1;
604 i = -i;
605 }
606 while (--i >= 0) {
607 x = (x << PyLong_SHIFT) | v->ob_digit[i];
608 }
609 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000610}
611
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612unsigned long
613PyLong_AsUnsignedLongMask(register PyObject *op)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyNumberMethods *nb;
616 PyLongObject *lo;
617 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op && PyLong_Check(op))
620 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
623 nb->nb_int == NULL) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (unsigned long)-1;
626 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 lo = (PyLongObject*) (*nb->nb_int) (op);
629 if (lo == NULL)
630 return (unsigned long)-1;
631 if (PyLong_Check(lo)) {
632 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
633 Py_DECREF(lo);
634 if (PyErr_Occurred())
635 return (unsigned long)-1;
636 return val;
637 }
638 else
639 {
640 Py_DECREF(lo);
641 PyErr_SetString(PyExc_TypeError,
642 "nb_int should return int object");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645}
646
Tim Peters5b8132f2003-01-31 15:52:05 +0000647int
648_PyLong_Sign(PyObject *vv)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 assert(v != NULL);
653 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000656}
657
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658size_t
659_PyLong_NumBits(PyObject *vv)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *v = (PyLongObject *)vv;
662 size_t result = 0;
663 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
667 ndigits = ABS(Py_SIZE(v));
668 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
669 if (ndigits > 0) {
670 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100671 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100673 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 do {
675 ++result;
676 if (result == 0)
677 goto Overflow;
678 msd >>= 1;
679 } while (msd);
680 }
681 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682
Mark Dickinson22b20182010-05-10 21:27:53 +0000683 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
685 "to express in a platform size_t");
686 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000687}
688
Tim Peters2a9b3672001-06-11 21:23:58 +0000689PyObject *
690_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000692{
Mark Dickinson22b20182010-05-10 21:27:53 +0000693 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int incr; /* direction to move pstartbyte */
695 const unsigned char* pendbyte; /* MSB of bytes */
696 size_t numsignificantbytes; /* number of bytes that matter */
697 Py_ssize_t ndigits; /* number of Python long digits */
698 PyLongObject* v; /* result */
699 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (n == 0)
702 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (little_endian) {
705 pstartbyte = bytes;
706 pendbyte = bytes + n - 1;
707 incr = 1;
708 }
709 else {
710 pstartbyte = bytes + n - 1;
711 pendbyte = bytes;
712 incr = -1;
713 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (is_signed)
716 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200719 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 is positive, and leading 0xff bytes if negative. */
721 {
722 size_t i;
723 const unsigned char* p = pendbyte;
724 const int pincr = -incr; /* search MSB to LSB */
725 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 for (i = 0; i < n; ++i, p += pincr) {
728 if (*p != insignficant)
729 break;
730 }
731 numsignificantbytes = n - i;
732 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
733 actually has 2 significant bytes. OTOH, 0xff0001 ==
734 -0x00ffff, so we wouldn't *need* to bump it there; but we
735 do for 0xffff = -0x0001. To be safe without bothering to
736 check every case, bump it regardless. */
737 if (is_signed && numsignificantbytes < n)
738 ++numsignificantbytes;
739 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* How many Python long digits do we need? We have
742 8*numsignificantbytes bits, and each Python long digit has
743 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
744 /* catch overflow before it happens */
745 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
746 PyErr_SetString(PyExc_OverflowError,
747 "byte array too long to convert to int");
748 return NULL;
749 }
750 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
751 v = _PyLong_New(ndigits);
752 if (v == NULL)
753 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Copy the bits over. The tricky parts are computing 2's-comp on
756 the fly for signed numbers, and dealing with the mismatch between
757 8-bit bytes and (probably) 15-bit Python digits.*/
758 {
759 size_t i;
760 twodigits carry = 1; /* for 2's-comp calculation */
761 twodigits accum = 0; /* sliding register */
762 unsigned int accumbits = 0; /* number of bits in accum */
763 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
766 twodigits thisbyte = *p;
767 /* Compute correction for 2's comp, if needed. */
768 if (is_signed) {
769 thisbyte = (0xff ^ thisbyte) + carry;
770 carry = thisbyte >> 8;
771 thisbyte &= 0xff;
772 }
773 /* Because we're going LSB to MSB, thisbyte is
774 more significant than what's already in accum,
775 so needs to be prepended to accum. */
776 accum |= (twodigits)thisbyte << accumbits;
777 accumbits += 8;
778 if (accumbits >= PyLong_SHIFT) {
779 /* There's enough to fill a Python digit. */
780 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000781 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 ++idigit;
783 accum >>= PyLong_SHIFT;
784 accumbits -= PyLong_SHIFT;
785 assert(accumbits < PyLong_SHIFT);
786 }
787 }
788 assert(accumbits < PyLong_SHIFT);
789 if (accumbits) {
790 assert(idigit < ndigits);
791 v->ob_digit[idigit] = (digit)accum;
792 ++idigit;
793 }
794 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 Py_SIZE(v) = is_signed ? -idigit : idigit;
797 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000798}
799
800int
801_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 unsigned char* bytes, size_t n,
803 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000806 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000808 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
810 digit carry; /* for computing 2's-comp */
811 size_t j; /* # bytes filled */
812 unsigned char* p; /* pointer to next byte in bytes */
813 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (Py_SIZE(v) < 0) {
818 ndigits = -(Py_SIZE(v));
819 if (!is_signed) {
820 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000821 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return -1;
823 }
824 do_twos_comp = 1;
825 }
826 else {
827 ndigits = Py_SIZE(v);
828 do_twos_comp = 0;
829 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (little_endian) {
832 p = bytes;
833 pincr = 1;
834 }
835 else {
836 p = bytes + n - 1;
837 pincr = -1;
838 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Copy over all the Python digits.
841 It's crucial that every Python digit except for the MSD contribute
842 exactly PyLong_SHIFT bits to the total, so first assert that the long is
843 normalized. */
844 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
845 j = 0;
846 accum = 0;
847 accumbits = 0;
848 carry = do_twos_comp ? 1 : 0;
849 for (i = 0; i < ndigits; ++i) {
850 digit thisdigit = v->ob_digit[i];
851 if (do_twos_comp) {
852 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
853 carry = thisdigit >> PyLong_SHIFT;
854 thisdigit &= PyLong_MASK;
855 }
856 /* Because we're going LSB to MSB, thisdigit is more
857 significant than what's already in accum, so needs to be
858 prepended to accum. */
859 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* The most-significant digit may be (probably is) at least
862 partly empty. */
863 if (i == ndigits - 1) {
864 /* Count # of sign bits -- they needn't be stored,
865 * although for signed conversion we need later to
866 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000867 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 while (s != 0) {
869 s >>= 1;
870 accumbits++;
871 }
872 }
873 else
874 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Store as many bytes as possible. */
877 while (accumbits >= 8) {
878 if (j >= n)
879 goto Overflow;
880 ++j;
881 *p = (unsigned char)(accum & 0xff);
882 p += pincr;
883 accumbits -= 8;
884 accum >>= 8;
885 }
886 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Store the straggler (if any). */
889 assert(accumbits < 8);
890 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
891 if (accumbits > 0) {
892 if (j >= n)
893 goto Overflow;
894 ++j;
895 if (do_twos_comp) {
896 /* Fill leading bits of the byte with sign bits
897 (appropriately pretending that the long had an
898 infinite supply of sign bits). */
899 accum |= (~(twodigits)0) << accumbits;
900 }
901 *p = (unsigned char)(accum & 0xff);
902 p += pincr;
903 }
904 else if (j == n && n > 0 && is_signed) {
905 /* The main loop filled the byte array exactly, so the code
906 just above didn't get to ensure there's a sign bit, and the
907 loop below wouldn't add one either. Make sure a sign bit
908 exists. */
909 unsigned char msb = *(p - pincr);
910 int sign_bit_set = msb >= 0x80;
911 assert(accumbits == 0);
912 if (sign_bit_set == do_twos_comp)
913 return 0;
914 else
915 goto Overflow;
916 }
Tim Peters05607ad2001-06-13 21:01:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Fill remaining bytes with copies of the sign bit. */
919 {
920 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
921 for ( ; j < n; ++j, p += pincr)
922 *p = signbyte;
923 }
Tim Peters05607ad2001-06-13 21:01:27 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000926
Mark Dickinson22b20182010-05-10 21:27:53 +0000927 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
929 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000930
Tim Peters2a9b3672001-06-11 21:23:58 +0000931}
932
Mark Dickinson8d48b432011-10-23 20:47:14 +0100933/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000934
935PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000936PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000937{
Tim Peters70128a12001-06-16 08:48:40 +0000938#ifndef HAVE_LONG_LONG
939# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
940#endif
941#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000942# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000943#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* special-case null pointer */
945 if (!p)
946 return PyLong_FromLong(0);
947 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000948
Guido van Rossum78694d91998-09-18 14:14:13 +0000949}
950
Mark Dickinson8d48b432011-10-23 20:47:14 +0100951/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000952
953void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000954PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000955{
Tim Peters70128a12001-06-16 08:48:40 +0000956#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
960 x = PyLong_AsLong(vv);
961 else
962 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000963#else
Tim Peters70128a12001-06-16 08:48:40 +0000964
965#ifndef HAVE_LONG_LONG
966# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
967#endif
968#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000969# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000970#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
974 x = PyLong_AsLongLong(vv);
975 else
976 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000977
978#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (x == -1 && PyErr_Occurred())
981 return NULL;
982 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000983}
984
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000985#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000986
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000987/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000988 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000989 */
990
Tim Peterscf37dfc2001-06-14 18:42:50 +0000991#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000992#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000993
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000994/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995
996PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyLongObject *v;
1000 unsigned PY_LONG_LONG abs_ival;
1001 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1002 int ndigits = 0;
1003 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 CHECK_SMALL_INT(ival);
1006 if (ival < 0) {
1007 /* avoid signed overflow on negation; see comments
1008 in PyLong_FromLong above. */
1009 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1010 negative = 1;
1011 }
1012 else {
1013 abs_ival = (unsigned PY_LONG_LONG)ival;
1014 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* Count the number of Python digits.
1017 We used to pick 5 ("big enough for anything"), but that's a
1018 waste of time and space given that 5*15 = 75 bits are rarely
1019 needed. */
1020 t = abs_ival;
1021 while (t) {
1022 ++ndigits;
1023 t >>= PyLong_SHIFT;
1024 }
1025 v = _PyLong_New(ndigits);
1026 if (v != NULL) {
1027 digit *p = v->ob_digit;
1028 Py_SIZE(v) = negative ? -ndigits : ndigits;
1029 t = abs_ival;
1030 while (t) {
1031 *p++ = (digit)(t & PyLong_MASK);
1032 t >>= PyLong_SHIFT;
1033 }
1034 }
1035 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036}
1037
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001038/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001039
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyLongObject *v;
1044 unsigned PY_LONG_LONG t;
1045 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (ival < PyLong_BASE)
1048 return PyLong_FromLong((long)ival);
1049 /* Count the number of Python digits. */
1050 t = (unsigned PY_LONG_LONG)ival;
1051 while (t) {
1052 ++ndigits;
1053 t >>= PyLong_SHIFT;
1054 }
1055 v = _PyLong_New(ndigits);
1056 if (v != NULL) {
1057 digit *p = v->ob_digit;
1058 Py_SIZE(v) = ndigits;
1059 while (ival) {
1060 *p++ = (digit)(ival & PyLong_MASK);
1061 ival >>= PyLong_SHIFT;
1062 }
1063 }
1064 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065}
1066
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067/* Create a new long int object from a C Py_ssize_t. */
1068
1069PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001070PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyLongObject *v;
1073 size_t abs_ival;
1074 size_t t; /* unsigned so >> doesn't propagate sign bit */
1075 int ndigits = 0;
1076 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 CHECK_SMALL_INT(ival);
1079 if (ival < 0) {
1080 /* avoid signed overflow when ival = SIZE_T_MIN */
1081 abs_ival = (size_t)(-1-ival)+1;
1082 negative = 1;
1083 }
1084 else {
1085 abs_ival = (size_t)ival;
1086 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 /* Count the number of Python digits. */
1089 t = abs_ival;
1090 while (t) {
1091 ++ndigits;
1092 t >>= PyLong_SHIFT;
1093 }
1094 v = _PyLong_New(ndigits);
1095 if (v != NULL) {
1096 digit *p = v->ob_digit;
1097 Py_SIZE(v) = negative ? -ndigits : ndigits;
1098 t = abs_ival;
1099 while (t) {
1100 *p++ = (digit)(t & PyLong_MASK);
1101 t >>= PyLong_SHIFT;
1102 }
1103 }
1104 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105}
1106
1107/* Create a new long int object from a C size_t. */
1108
1109PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001110PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyLongObject *v;
1113 size_t t;
1114 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (ival < PyLong_BASE)
1117 return PyLong_FromLong((long)ival);
1118 /* Count the number of Python digits. */
1119 t = ival;
1120 while (t) {
1121 ++ndigits;
1122 t >>= PyLong_SHIFT;
1123 }
1124 v = _PyLong_New(ndigits);
1125 if (v != NULL) {
1126 digit *p = v->ob_digit;
1127 Py_SIZE(v) = ndigits;
1128 while (ival) {
1129 *p++ = (digit)(ival & PyLong_MASK);
1130 ival >>= PyLong_SHIFT;
1131 }
1132 }
1133 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134}
1135
Mark Dickinson8d48b432011-10-23 20:47:14 +01001136/* Get a C long long int from a long int object or any object that has an
1137 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001139PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001140PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyLongObject *v;
1143 PY_LONG_LONG bytes;
1144 int one = 1;
1145 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (vv == NULL) {
1148 PyErr_BadInternalCall();
1149 return -1;
1150 }
1151 if (!PyLong_Check(vv)) {
1152 PyNumberMethods *nb;
1153 PyObject *io;
1154 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1155 nb->nb_int == NULL) {
1156 PyErr_SetString(PyExc_TypeError, "an integer is required");
1157 return -1;
1158 }
1159 io = (*nb->nb_int) (vv);
1160 if (io == NULL)
1161 return -1;
1162 if (PyLong_Check(io)) {
1163 bytes = PyLong_AsLongLong(io);
1164 Py_DECREF(io);
1165 return bytes;
1166 }
1167 Py_DECREF(io);
1168 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1169 return -1;
1170 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 v = (PyLongObject*)vv;
1173 switch(Py_SIZE(v)) {
1174 case -1: return -(sdigit)v->ob_digit[0];
1175 case 0: return 0;
1176 case 1: return v->ob_digit[0];
1177 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001178 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1179 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1182 if (res < 0)
1183 return (PY_LONG_LONG)-1;
1184 else
1185 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001186}
1187
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001188/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001189 Return -1 and set an error if overflow occurs. */
1190
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001191unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001192PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyLongObject *v;
1195 unsigned PY_LONG_LONG bytes;
1196 int one = 1;
1197 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001198
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001199 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyErr_BadInternalCall();
1201 return (unsigned PY_LONG_LONG)-1;
1202 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001203 if (!PyLong_Check(vv)) {
1204 PyErr_SetString(PyExc_TypeError, "an integer is required");
1205 return (unsigned PY_LONG_LONG)-1;
1206 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 v = (PyLongObject*)vv;
1209 switch(Py_SIZE(v)) {
1210 case 0: return 0;
1211 case 1: return v->ob_digit[0];
1212 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001213
Mark Dickinson22b20182010-05-10 21:27:53 +00001214 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1215 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1218 if (res < 0)
1219 return (unsigned PY_LONG_LONG)res;
1220 else
1221 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001222}
Tim Petersd1a7da62001-06-13 00:35:57 +00001223
Thomas Hellera4ea6032003-04-17 18:55:45 +00001224/* Get a C unsigned long int from a long int object, ignoring the high bits.
1225 Returns -1 and sets an error condition if an error occurs. */
1226
Guido van Rossumddefaf32007-01-14 03:31:43 +00001227static unsigned PY_LONG_LONG
1228_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 register PyLongObject *v;
1231 unsigned PY_LONG_LONG x;
1232 Py_ssize_t i;
1233 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (vv == NULL || !PyLong_Check(vv)) {
1236 PyErr_BadInternalCall();
1237 return (unsigned long) -1;
1238 }
1239 v = (PyLongObject *)vv;
1240 switch(Py_SIZE(v)) {
1241 case 0: return 0;
1242 case 1: return v->ob_digit[0];
1243 }
1244 i = Py_SIZE(v);
1245 sign = 1;
1246 x = 0;
1247 if (i < 0) {
1248 sign = -1;
1249 i = -i;
1250 }
1251 while (--i >= 0) {
1252 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1253 }
1254 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001255}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001256
1257unsigned PY_LONG_LONG
1258PyLong_AsUnsignedLongLongMask(register PyObject *op)
1259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyNumberMethods *nb;
1261 PyLongObject *lo;
1262 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (op && PyLong_Check(op))
1265 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1268 nb->nb_int == NULL) {
1269 PyErr_SetString(PyExc_TypeError, "an integer is required");
1270 return (unsigned PY_LONG_LONG)-1;
1271 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 lo = (PyLongObject*) (*nb->nb_int) (op);
1274 if (lo == NULL)
1275 return (unsigned PY_LONG_LONG)-1;
1276 if (PyLong_Check(lo)) {
1277 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1278 Py_DECREF(lo);
1279 if (PyErr_Occurred())
1280 return (unsigned PY_LONG_LONG)-1;
1281 return val;
1282 }
1283 else
1284 {
1285 Py_DECREF(lo);
1286 PyErr_SetString(PyExc_TypeError,
1287 "nb_int should return int object");
1288 return (unsigned PY_LONG_LONG)-1;
1289 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001290}
Tim Petersd1a7da62001-06-13 00:35:57 +00001291#undef IS_LITTLE_ENDIAN
1292
Mark Dickinson8d48b432011-10-23 20:47:14 +01001293/* Get a C long long int from a long int object or any object that has an
1294 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001295
Mark Dickinson8d48b432011-10-23 20:47:14 +01001296 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1297 the result. Otherwise *overflow is 0.
1298
1299 For other errors (e.g., TypeError), return -1 and set an error condition.
1300 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001301*/
1302
1303PY_LONG_LONG
1304PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 /* This version by Tim Peters */
1307 register PyLongObject *v;
1308 unsigned PY_LONG_LONG x, prev;
1309 PY_LONG_LONG res;
1310 Py_ssize_t i;
1311 int sign;
1312 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 *overflow = 0;
1315 if (vv == NULL) {
1316 PyErr_BadInternalCall();
1317 return -1;
1318 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!PyLong_Check(vv)) {
1321 PyNumberMethods *nb;
1322 nb = vv->ob_type->tp_as_number;
1323 if (nb == NULL || nb->nb_int == NULL) {
1324 PyErr_SetString(PyExc_TypeError,
1325 "an integer is required");
1326 return -1;
1327 }
1328 vv = (*nb->nb_int) (vv);
1329 if (vv == NULL)
1330 return -1;
1331 do_decref = 1;
1332 if (!PyLong_Check(vv)) {
1333 Py_DECREF(vv);
1334 PyErr_SetString(PyExc_TypeError,
1335 "nb_int should return int object");
1336 return -1;
1337 }
1338 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 res = -1;
1341 v = (PyLongObject *)vv;
1342 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 switch (i) {
1345 case -1:
1346 res = -(sdigit)v->ob_digit[0];
1347 break;
1348 case 0:
1349 res = 0;
1350 break;
1351 case 1:
1352 res = v->ob_digit[0];
1353 break;
1354 default:
1355 sign = 1;
1356 x = 0;
1357 if (i < 0) {
1358 sign = -1;
1359 i = -(i);
1360 }
1361 while (--i >= 0) {
1362 prev = x;
1363 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1364 if ((x >> PyLong_SHIFT) != prev) {
1365 *overflow = sign;
1366 goto exit;
1367 }
1368 }
1369 /* Haven't lost any bits, but casting to long requires extra
1370 * care (see comment above).
1371 */
1372 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1373 res = (PY_LONG_LONG)x * sign;
1374 }
1375 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1376 res = PY_LLONG_MIN;
1377 }
1378 else {
1379 *overflow = sign;
1380 /* res is already set to -1 */
1381 }
1382 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001383 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (do_decref) {
1385 Py_DECREF(vv);
1386 }
1387 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001388}
1389
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001390#endif /* HAVE_LONG_LONG */
1391
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001392#define CHECK_BINOP(v,w) \
1393 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001394 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1395 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001396 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001397
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001398/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1399 2**k if d is nonzero, else 0. */
1400
1401static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1403 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001404};
1405
1406static int
1407bits_in_digit(digit d)
1408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 int d_bits = 0;
1410 while (d >= 32) {
1411 d_bits += 6;
1412 d >>= 6;
1413 }
1414 d_bits += (int)BitLengthTable[d];
1415 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001416}
1417
Tim Peters877a2122002-08-12 05:09:36 +00001418/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1419 * is modified in place, by adding y to it. Carries are propagated as far as
1420 * x[m-1], and the remaining carry (0 or 1) is returned.
1421 */
1422static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 Py_ssize_t i;
1426 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 assert(m >= n);
1429 for (i = 0; i < n; ++i) {
1430 carry += x[i] + y[i];
1431 x[i] = carry & PyLong_MASK;
1432 carry >>= PyLong_SHIFT;
1433 assert((carry & 1) == carry);
1434 }
1435 for (; carry && i < m; ++i) {
1436 carry += x[i];
1437 x[i] = carry & PyLong_MASK;
1438 carry >>= PyLong_SHIFT;
1439 assert((carry & 1) == carry);
1440 }
1441 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001442}
1443
1444/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1445 * is modified in place, by subtracting y from it. Borrows are propagated as
1446 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1447 */
1448static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001449v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 Py_ssize_t i;
1452 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 assert(m >= n);
1455 for (i = 0; i < n; ++i) {
1456 borrow = x[i] - y[i] - borrow;
1457 x[i] = borrow & PyLong_MASK;
1458 borrow >>= PyLong_SHIFT;
1459 borrow &= 1; /* keep only 1 sign bit */
1460 }
1461 for (; borrow && i < m; ++i) {
1462 borrow = x[i] - borrow;
1463 x[i] = borrow & PyLong_MASK;
1464 borrow >>= PyLong_SHIFT;
1465 borrow &= 1;
1466 }
1467 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001468}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001469
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001470/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1471 * result in z[0:m], and return the d bits shifted out of the top.
1472 */
1473static digit
1474v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 Py_ssize_t i;
1477 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 assert(0 <= d && d < PyLong_SHIFT);
1480 for (i=0; i < m; i++) {
1481 twodigits acc = (twodigits)a[i] << d | carry;
1482 z[i] = (digit)acc & PyLong_MASK;
1483 carry = (digit)(acc >> PyLong_SHIFT);
1484 }
1485 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001486}
1487
1488/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1489 * result in z[0:m], and return the d bits shifted out of the bottom.
1490 */
1491static digit
1492v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 Py_ssize_t i;
1495 digit carry = 0;
1496 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 assert(0 <= d && d < PyLong_SHIFT);
1499 for (i=m; i-- > 0;) {
1500 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1501 carry = (digit)acc & mask;
1502 z[i] = (digit)(acc >> d);
1503 }
1504 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505}
1506
Tim Peters212e6142001-07-14 12:23:19 +00001507/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1508 in pout, and returning the remainder. pin and pout point at the LSD.
1509 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001510 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001511 immutable. */
1512
1513static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001514inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(n > 0 && n <= PyLong_MASK);
1519 pin += size;
1520 pout += size;
1521 while (--size >= 0) {
1522 digit hi;
1523 rem = (rem << PyLong_SHIFT) | *--pin;
1524 *--pout = hi = (digit)(rem / n);
1525 rem -= (twodigits)hi * n;
1526 }
1527 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001528}
1529
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001530/* Divide a long integer by a digit, returning both the quotient
1531 (as function result) and the remainder (through *prem).
1532 The sign of a is ignored; n should not be zero. */
1533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001535divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 const Py_ssize_t size = ABS(Py_SIZE(a));
1538 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 assert(n > 0 && n <= PyLong_MASK);
1541 z = _PyLong_New(size);
1542 if (z == NULL)
1543 return NULL;
1544 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1545 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001546}
1547
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001548/* Convert a long integer to a base 10 string. Returns a new non-shared
1549 string. (Return value is non-shared so that callers can modify the
1550 returned value if necessary.) */
1551
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552static int
1553long_to_decimal_string_internal(PyObject *aa,
1554 PyObject **p_output,
1555 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyLongObject *scratch, *a;
1558 PyObject *str;
1559 Py_ssize_t size, strlen, size_a, i, j;
1560 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001562 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 a = (PyLongObject *)aa;
1565 if (a == NULL || !PyLong_Check(a)) {
1566 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001567 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
1569 size_a = ABS(Py_SIZE(a));
1570 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* quick and dirty upper bound for the number of digits
1573 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 But log2(a) < size_a * PyLong_SHIFT, and
1578 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1579 > 3 * _PyLong_DECIMAL_SHIFT
1580 */
1581 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1582 PyErr_SetString(PyExc_OverflowError,
1583 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001584 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
1586 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1587 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1588 scratch = _PyLong_New(size);
1589 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001590 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* convert array of base _PyLong_BASE digits in pin to an array of
1593 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1594 Volume 2 (3rd edn), section 4.4, Method 1b). */
1595 pin = a->ob_digit;
1596 pout = scratch->ob_digit;
1597 size = 0;
1598 for (i = size_a; --i >= 0; ) {
1599 digit hi = pin[i];
1600 for (j = 0; j < size; j++) {
1601 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1602 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1603 pout[j] = (digit)(z - (twodigits)hi *
1604 _PyLong_DECIMAL_BASE);
1605 }
1606 while (hi) {
1607 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1608 hi /= _PyLong_DECIMAL_BASE;
1609 }
1610 /* check for keyboard interrupt */
1611 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001612 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001613 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001614 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 }
1616 /* pout should have at least one digit, so that the case when a = 0
1617 works correctly */
1618 if (size == 0)
1619 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* calculate exact length of output string, and allocate */
1622 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1623 tenpow = 10;
1624 rem = pout[size-1];
1625 while (rem >= tenpow) {
1626 tenpow *= 10;
1627 strlen++;
1628 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001629 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001630 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1631 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001632 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001633 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001634 kind = writer->kind;
1635 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001637 else {
1638 str = PyUnicode_New(strlen, '9');
1639 if (str == NULL) {
1640 Py_DECREF(scratch);
1641 return -1;
1642 }
1643 kind = PyUnicode_KIND(str);
1644 }
1645
1646#define WRITE_DIGITS(TYPE) \
1647 do { \
1648 if (writer) \
1649 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1650 else \
1651 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1652 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001653 /* pout[0] through pout[size-2] contribute exactly \
1654 _PyLong_DECIMAL_SHIFT digits each */ \
1655 for (i=0; i < size - 1; i++) { \
1656 rem = pout[i]; \
1657 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1658 *--p = '0' + rem % 10; \
1659 rem /= 10; \
1660 } \
1661 } \
1662 /* pout[size-1]: always produce at least one decimal digit */ \
1663 rem = pout[i]; \
1664 do { \
1665 *--p = '0' + rem % 10; \
1666 rem /= 10; \
1667 } while (rem != 0); \
1668 \
1669 /* and sign */ \
1670 if (negative) \
1671 *--p = '-'; \
1672 \
1673 /* check we've counted correctly */ \
1674 if (writer) \
1675 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1676 else \
1677 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1678 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001681 if (kind == PyUnicode_1BYTE_KIND) {
1682 Py_UCS1 *p;
1683 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001685 else if (kind == PyUnicode_2BYTE_KIND) {
1686 Py_UCS2 *p;
1687 WRITE_DIGITS(Py_UCS2);
1688 }
1689 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001690 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001691 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001692 WRITE_DIGITS(Py_UCS4);
1693 }
1694#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001697 if (writer) {
1698 writer->pos += strlen;
1699 }
1700 else {
1701 assert(_PyUnicode_CheckConsistency(str, 1));
1702 *p_output = (PyObject *)str;
1703 }
1704 return 0;
1705}
1706
1707static PyObject *
1708long_to_decimal_string(PyObject *aa)
1709{
1710 PyObject *v;
1711 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1712 return NULL;
1713 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001714}
1715
Mark Dickinsoncd068122009-09-18 14:53:08 +00001716/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 which should be one of 2, 8 or 16. Return a string object.
1718 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1719 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001720
Victor Stinnerd3f08822012-05-29 12:57:52 +02001721static int
1722long_format_binary(PyObject *aa, int base, int alternate,
1723 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001726 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001727 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001729 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001730 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001732
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (a == NULL || !PyLong_Check(a)) {
1735 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001736 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
1738 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001739 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 /* Compute a rough upper bound for the length of the string */
1742 switch (base) {
1743 case 16:
1744 bits = 4;
1745 break;
1746 case 8:
1747 bits = 3;
1748 break;
1749 case 2:
1750 bits = 1;
1751 break;
1752 default:
1753 assert(0); /* shouldn't ever get here */
1754 bits = 0; /* to silence gcc warning */
1755 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001756
Mark Dickinsone2846542012-04-20 21:21:24 +01001757 /* Compute exact length 'sz' of output string. */
1758 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001759 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001760 }
1761 else {
1762 Py_ssize_t size_a_in_bits;
1763 /* Ensure overflow doesn't occur during computation of sz. */
1764 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1765 PyErr_SetString(PyExc_OverflowError,
1766 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001768 }
1769 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1770 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001771 /* Allow 1 character for a '-' sign. */
1772 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1773 }
1774 if (alternate) {
1775 /* 2 characters for prefix */
1776 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001777 }
1778
Victor Stinnerd3f08822012-05-29 12:57:52 +02001779 if (writer) {
1780 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1781 return -1;
1782 kind = writer->kind;
1783 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
1785 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 v = PyUnicode_New(sz, 'x');
1787 if (v == NULL)
1788 return -1;
1789 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001791
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792#define WRITE_DIGITS(TYPE) \
1793 do { \
1794 if (writer) \
1795 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1796 else \
1797 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1798 \
1799 if (size_a == 0) { \
1800 *--p = '0'; \
1801 } \
1802 else { \
1803 /* JRH: special case for power-of-2 bases */ \
1804 twodigits accum = 0; \
1805 int accumbits = 0; /* # of bits in accum */ \
1806 Py_ssize_t i; \
1807 for (i = 0; i < size_a; ++i) { \
1808 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1809 accumbits += PyLong_SHIFT; \
1810 assert(accumbits >= bits); \
1811 do { \
1812 char cdigit; \
1813 cdigit = (char)(accum & (base - 1)); \
1814 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1815 *--p = cdigit; \
1816 accumbits -= bits; \
1817 accum >>= bits; \
1818 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1819 } \
1820 } \
1821 \
1822 if (alternate) { \
1823 if (base == 16) \
1824 *--p = 'x'; \
1825 else if (base == 8) \
1826 *--p = 'o'; \
1827 else /* (base == 2) */ \
1828 *--p = 'b'; \
1829 *--p = '0'; \
1830 } \
1831 if (negative) \
1832 *--p = '-'; \
1833 if (writer) \
1834 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1835 else \
1836 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1837 } while (0)
1838
1839 if (kind == PyUnicode_1BYTE_KIND) {
1840 Py_UCS1 *p;
1841 WRITE_DIGITS(Py_UCS1);
1842 }
1843 else if (kind == PyUnicode_2BYTE_KIND) {
1844 Py_UCS2 *p;
1845 WRITE_DIGITS(Py_UCS2);
1846 }
1847 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001848 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001849 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001850 WRITE_DIGITS(Py_UCS4);
1851 }
1852#undef WRITE_DIGITS
1853
1854 if (writer) {
1855 writer->pos += sz;
1856 }
1857 else {
1858 assert(_PyUnicode_CheckConsistency(v, 1));
1859 *p_output = v;
1860 }
1861 return 0;
1862}
1863
1864PyObject *
1865_PyLong_Format(PyObject *obj, int base)
1866{
1867 PyObject *str;
1868 int err;
1869 if (base == 10)
1870 err = long_to_decimal_string_internal(obj, &str, NULL);
1871 else
1872 err = long_format_binary(obj, base, 1, &str, NULL);
1873 if (err == -1)
1874 return NULL;
1875 return str;
1876}
1877
1878int
1879_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1880 PyObject *obj,
1881 int base, int alternate)
1882{
1883 if (base == 10)
1884 return long_to_decimal_string_internal(obj, NULL, writer);
1885 else
1886 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001887}
1888
Thomas Wouters477c8d52006-05-27 19:21:47 +00001889/* Table of digit values for 8-bit string -> integer conversion.
1890 * '0' maps to 0, ..., '9' maps to 9.
1891 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1892 * All other indices map to 37.
1893 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001894 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001895 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001896unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1898 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1899 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1900 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1901 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1902 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1903 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1904 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1905 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1906 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1907 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1908 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1909 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1910 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1911 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1912 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913};
1914
1915/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001916 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1917 * non-digit (which may be *str!). A normalized long is returned.
1918 * The point to this routine is that it takes time linear in the number of
1919 * string characters.
1920 */
1921static PyLongObject *
1922long_from_binary_base(char **str, int base)
1923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 char *p = *str;
1925 char *start = p;
1926 int bits_per_char;
1927 Py_ssize_t n;
1928 PyLongObject *z;
1929 twodigits accum;
1930 int bits_in_accum;
1931 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1934 n = base;
1935 for (bits_per_char = -1; n; ++bits_per_char)
1936 n >>= 1;
1937 /* n <- total # of bits needed, while setting p to end-of-string */
1938 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1939 ++p;
1940 *str = p;
1941 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1942 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1943 if (n / bits_per_char < p - start) {
1944 PyErr_SetString(PyExc_ValueError,
1945 "int string too large to convert");
1946 return NULL;
1947 }
1948 n = n / PyLong_SHIFT;
1949 z = _PyLong_New(n);
1950 if (z == NULL)
1951 return NULL;
1952 /* Read string from right, and fill in long from left; i.e.,
1953 * from least to most significant in both.
1954 */
1955 accum = 0;
1956 bits_in_accum = 0;
1957 pdigit = z->ob_digit;
1958 while (--p >= start) {
1959 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1960 assert(k >= 0 && k < base);
1961 accum |= (twodigits)k << bits_in_accum;
1962 bits_in_accum += bits_per_char;
1963 if (bits_in_accum >= PyLong_SHIFT) {
1964 *pdigit++ = (digit)(accum & PyLong_MASK);
1965 assert(pdigit - z->ob_digit <= n);
1966 accum >>= PyLong_SHIFT;
1967 bits_in_accum -= PyLong_SHIFT;
1968 assert(bits_in_accum < PyLong_SHIFT);
1969 }
1970 }
1971 if (bits_in_accum) {
1972 assert(bits_in_accum <= PyLong_SHIFT);
1973 *pdigit++ = (digit)accum;
1974 assert(pdigit - z->ob_digit <= n);
1975 }
1976 while (pdigit - z->ob_digit < n)
1977 *pdigit++ = 0;
1978 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001979}
1980
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001981PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001982PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 int sign = 1, error_if_nonzero = 0;
1985 char *start, *orig_str = str;
1986 PyLongObject *z = NULL;
1987 PyObject *strobj;
1988 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if ((base != 0 && base < 2) || base > 36) {
1991 PyErr_SetString(PyExc_ValueError,
1992 "int() arg 2 must be >= 2 and <= 36");
1993 return NULL;
1994 }
1995 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1996 str++;
1997 if (*str == '+')
1998 ++str;
1999 else if (*str == '-') {
2000 ++str;
2001 sign = -1;
2002 }
2003 if (base == 0) {
2004 if (str[0] != '0')
2005 base = 10;
2006 else if (str[1] == 'x' || str[1] == 'X')
2007 base = 16;
2008 else if (str[1] == 'o' || str[1] == 'O')
2009 base = 8;
2010 else if (str[1] == 'b' || str[1] == 'B')
2011 base = 2;
2012 else {
2013 /* "old" (C-style) octal literal, now invalid.
2014 it might still be zero though */
2015 error_if_nonzero = 1;
2016 base = 10;
2017 }
2018 }
2019 if (str[0] == '0' &&
2020 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2021 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2022 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2023 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 start = str;
2026 if ((base & (base - 1)) == 0)
2027 z = long_from_binary_base(&str, base);
2028 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029/***
2030Binary bases can be converted in time linear in the number of digits, because
2031Python's representation base is binary. Other bases (including decimal!) use
2032the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002033
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034First some math: the largest integer that can be expressed in N base-B digits
2035is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2036case number of Python digits needed to hold it is the smallest integer n s.t.
2037
2038 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2039 BASE**n >= B**N [taking logs to base BASE]
2040 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2041
2042The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2043this quickly. A Python long with that much space is reserved near the start,
2044and the result is computed into it.
2045
2046The input string is actually treated as being in base base**i (i.e., i digits
2047are processed at a time), where two more static arrays hold:
2048
2049 convwidth_base[base] = the largest integer i such that base**i <= BASE
2050 convmultmax_base[base] = base ** convwidth_base[base]
2051
2052The first of these is the largest i such that i consecutive input digits
2053must fit in a single Python digit. The second is effectively the input
2054base we're really using.
2055
2056Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2057convmultmax_base[base], the result is "simply"
2058
2059 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2060
2061where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002062
2063Error analysis: as above, the number of Python digits `n` needed is worst-
2064case
2065
2066 n >= N * log(B)/log(BASE)
2067
2068where `N` is the number of input digits in base `B`. This is computed via
2069
2070 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2071
2072below. Two numeric concerns are how much space this can waste, and whether
2073the computed result can be too small. To be concrete, assume BASE = 2**15,
2074which is the default (and it's unlikely anyone changes that).
2075
2076Waste isn't a problem: provided the first input digit isn't 0, the difference
2077between the worst-case input with N digits and the smallest input with N
2078digits is about a factor of B, but B is small compared to BASE so at most
2079one allocated Python digit can remain unused on that count. If
2080N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2081and adding 1 returns a result 1 larger than necessary. However, that can't
2082happen: whenever B is a power of 2, long_from_binary_base() is called
2083instead, and it's impossible for B**i to be an integer power of 2**15 when
2084B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2085an exact integer when B is not a power of 2, since B**i has a prime factor
2086other than 2 in that case, but (2**15)**j's only prime factor is 2).
2087
2088The computed result can be too small if the true value of N*log(B)/log(BASE)
2089is a little bit larger than an exact integer, but due to roundoff errors (in
2090computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2091yields a numeric result a little less than that integer. Unfortunately, "how
2092close can a transcendental function get to an integer over some range?"
2093questions are generally theoretically intractable. Computer analysis via
2094continued fractions is practical: expand log(B)/log(BASE) via continued
2095fractions, giving a sequence i/j of "the best" rational approximations. Then
2096j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2097we can get very close to being in trouble, but very rarely. For example,
209876573 is a denominator in one of the continued-fraction approximations to
2099log(10)/log(2**15), and indeed:
2100
2101 >>> log(10)/log(2**15)*76573
2102 16958.000000654003
2103
2104is very close to an integer. If we were working with IEEE single-precision,
2105rounding errors could kill us. Finding worst cases in IEEE double-precision
2106requires better-than-double-precision log() functions, and Tim didn't bother.
2107Instead the code checks to see whether the allocated space is enough as each
2108new Python digit is added, and copies the whole thing to a larger long if not.
2109This should happen extremely rarely, and in fact I don't have a test case
2110that triggers it(!). Instead the code was tested by artificially allocating
2111just 1 digit at the start, so that the copying code was exercised for every
2112digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002113***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 register twodigits c; /* current input character */
2115 Py_ssize_t size_z;
2116 int i;
2117 int convwidth;
2118 twodigits convmultmax, convmult;
2119 digit *pz, *pzstop;
2120 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 static double log_base_BASE[37] = {0.0e0,};
2123 static int convwidth_base[37] = {0,};
2124 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (log_base_BASE[base] == 0.0) {
2127 twodigits convmax = base;
2128 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129
Mark Dickinson22b20182010-05-10 21:27:53 +00002130 log_base_BASE[base] = (log((double)base) /
2131 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 for (;;) {
2133 twodigits next = convmax * base;
2134 if (next > PyLong_BASE)
2135 break;
2136 convmax = next;
2137 ++i;
2138 }
2139 convmultmax_base[base] = convmax;
2140 assert(i > 0);
2141 convwidth_base[base] = i;
2142 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 /* Find length of the string of numeric characters. */
2145 scan = str;
2146 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2147 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* Create a long object that can contain the largest possible
2150 * integer with this base and length. Note that there's no
2151 * need to initialize z->ob_digit -- no slot is read up before
2152 * being stored into.
2153 */
2154 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2155 /* Uncomment next line to test exceedingly rare copy code */
2156 /* size_z = 1; */
2157 assert(size_z > 0);
2158 z = _PyLong_New(size_z);
2159 if (z == NULL)
2160 return NULL;
2161 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* `convwidth` consecutive input digits are treated as a single
2164 * digit in base `convmultmax`.
2165 */
2166 convwidth = convwidth_base[base];
2167 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* Work ;-) */
2170 while (str < scan) {
2171 /* grab up to convwidth digits from the input string */
2172 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2173 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2174 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002175 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 assert(c < PyLong_BASE);
2177 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 convmult = convmultmax;
2180 /* Calculate the shift only if we couldn't get
2181 * convwidth digits.
2182 */
2183 if (i != convwidth) {
2184 convmult = base;
2185 for ( ; i > 1; --i)
2186 convmult *= base;
2187 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 /* Multiply z by convmult, and add c. */
2190 pz = z->ob_digit;
2191 pzstop = pz + Py_SIZE(z);
2192 for (; pz < pzstop; ++pz) {
2193 c += (twodigits)*pz * convmult;
2194 *pz = (digit)(c & PyLong_MASK);
2195 c >>= PyLong_SHIFT;
2196 }
2197 /* carry off the current end? */
2198 if (c) {
2199 assert(c < PyLong_BASE);
2200 if (Py_SIZE(z) < size_z) {
2201 *pz = (digit)c;
2202 ++Py_SIZE(z);
2203 }
2204 else {
2205 PyLongObject *tmp;
2206 /* Extremely rare. Get more space. */
2207 assert(Py_SIZE(z) == size_z);
2208 tmp = _PyLong_New(size_z + 1);
2209 if (tmp == NULL) {
2210 Py_DECREF(z);
2211 return NULL;
2212 }
2213 memcpy(tmp->ob_digit,
2214 z->ob_digit,
2215 sizeof(digit) * size_z);
2216 Py_DECREF(z);
2217 z = tmp;
2218 z->ob_digit[size_z] = (digit)c;
2219 ++size_z;
2220 }
2221 }
2222 }
2223 }
2224 if (z == NULL)
2225 return NULL;
2226 if (error_if_nonzero) {
2227 /* reset the base to 0, else the exception message
2228 doesn't make too much sense */
2229 base = 0;
2230 if (Py_SIZE(z) != 0)
2231 goto onError;
2232 /* there might still be other problems, therefore base
2233 remains zero here for the same reason */
2234 }
2235 if (str == start)
2236 goto onError;
2237 if (sign < 0)
2238 Py_SIZE(z) = -(Py_SIZE(z));
2239 while (*str && isspace(Py_CHARMASK(*str)))
2240 str++;
2241 if (*str != '\0')
2242 goto onError;
2243 if (pend)
2244 *pend = str;
2245 long_normalize(z);
2246 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002247
Mark Dickinson22b20182010-05-10 21:27:53 +00002248 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 Py_XDECREF(z);
2250 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2251 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2252 if (strobj == NULL)
2253 return NULL;
2254 PyErr_Format(PyExc_ValueError,
2255 "invalid literal for int() with base %d: %R",
2256 base, strobj);
2257 Py_DECREF(strobj);
2258 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002259}
2260
2261PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002262PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002263{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2265 if (unicode == NULL)
2266 return NULL;
2267 v = PyLong_FromUnicodeObject(unicode, base);
2268 Py_DECREF(unicode);
2269 return v;
2270}
2271
2272PyObject *
2273PyLong_FromUnicodeObject(PyObject *u, int base)
2274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002276 PyObject *asciidig;
2277 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002279
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002280 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002281 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002283 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002284 if (buffer == NULL) {
2285 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 return NULL;
2287 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002288 result = PyLong_FromString(buffer, &end, base);
2289 if (result != NULL && end != buffer + buflen) {
2290 PyErr_SetString(PyExc_ValueError,
2291 "null byte in argument for int()");
2292 Py_DECREF(result);
2293 result = NULL;
2294 }
2295 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002297}
2298
Tim Peters9f688bf2000-07-07 15:53:28 +00002299/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002300static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002302static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002303
2304/* Long division with remainder, top-level routine */
2305
Guido van Rossume32e0141992-01-19 16:31:05 +00002306static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002307long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2311 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (size_b == 0) {
2314 PyErr_SetString(PyExc_ZeroDivisionError,
2315 "integer division or modulo by zero");
2316 return -1;
2317 }
2318 if (size_a < size_b ||
2319 (size_a == size_b &&
2320 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2321 /* |a| < |b|. */
2322 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2323 if (*pdiv == NULL)
2324 return -1;
2325 Py_INCREF(a);
2326 *prem = (PyLongObject *) a;
2327 return 0;
2328 }
2329 if (size_b == 1) {
2330 digit rem = 0;
2331 z = divrem1(a, b->ob_digit[0], &rem);
2332 if (z == NULL)
2333 return -1;
2334 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2335 if (*prem == NULL) {
2336 Py_DECREF(z);
2337 return -1;
2338 }
2339 }
2340 else {
2341 z = x_divrem(a, b, prem);
2342 if (z == NULL)
2343 return -1;
2344 }
2345 /* Set the signs.
2346 The quotient z has the sign of a*b;
2347 the remainder r has the sign of a,
2348 so a = b*z + r. */
2349 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2350 NEGATE(z);
2351 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2352 NEGATE(*prem);
2353 *pdiv = maybe_small_long(z);
2354 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002355}
2356
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002357/* Unsigned long division with remainder -- the algorithm. The arguments v1
2358 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002359
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002361x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 PyLongObject *v, *w, *a;
2364 Py_ssize_t i, k, size_v, size_w;
2365 int d;
2366 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2367 twodigits vv;
2368 sdigit zhi;
2369 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2372 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2373 handle the special case when the initial estimate q for a quotient
2374 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2375 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* allocate space; w will also be used to hold the final remainder */
2378 size_v = ABS(Py_SIZE(v1));
2379 size_w = ABS(Py_SIZE(w1));
2380 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2381 v = _PyLong_New(size_v+1);
2382 if (v == NULL) {
2383 *prem = NULL;
2384 return NULL;
2385 }
2386 w = _PyLong_New(size_w);
2387 if (w == NULL) {
2388 Py_DECREF(v);
2389 *prem = NULL;
2390 return NULL;
2391 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2394 shift v1 left by the same amount. Results go into w and v. */
2395 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2396 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2397 assert(carry == 0);
2398 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2399 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2400 v->ob_digit[size_v] = carry;
2401 size_v++;
2402 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2405 at most (and usually exactly) k = size_v - size_w digits. */
2406 k = size_v - size_w;
2407 assert(k >= 0);
2408 a = _PyLong_New(k);
2409 if (a == NULL) {
2410 Py_DECREF(w);
2411 Py_DECREF(v);
2412 *prem = NULL;
2413 return NULL;
2414 }
2415 v0 = v->ob_digit;
2416 w0 = w->ob_digit;
2417 wm1 = w0[size_w-1];
2418 wm2 = w0[size_w-2];
2419 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2420 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2421 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002424 Py_DECREF(a);
2425 Py_DECREF(w);
2426 Py_DECREF(v);
2427 *prem = NULL;
2428 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002429 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* estimate quotient digit q; may overestimate by 1 (rare) */
2432 vtop = vk[size_w];
2433 assert(vtop <= wm1);
2434 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2435 q = (digit)(vv / wm1);
2436 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2437 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2438 | vk[size_w-2])) {
2439 --q;
2440 r += wm1;
2441 if (r >= PyLong_BASE)
2442 break;
2443 }
2444 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2447 zhi = 0;
2448 for (i = 0; i < size_w; ++i) {
2449 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2450 -PyLong_BASE * q <= z < PyLong_BASE */
2451 z = (sdigit)vk[i] + zhi -
2452 (stwodigits)q * (stwodigits)w0[i];
2453 vk[i] = (digit)z & PyLong_MASK;
2454 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002455 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* add w back if q was too large (this branch taken rarely) */
2459 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2460 if ((sdigit)vtop + zhi < 0) {
2461 carry = 0;
2462 for (i = 0; i < size_w; ++i) {
2463 carry += vk[i] + w0[i];
2464 vk[i] = carry & PyLong_MASK;
2465 carry >>= PyLong_SHIFT;
2466 }
2467 --q;
2468 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* store quotient digit */
2471 assert(q < PyLong_BASE);
2472 *--ak = q;
2473 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* unshift remainder; we reuse w to store the result */
2476 carry = v_rshift(w0, v0, size_w, d);
2477 assert(carry==0);
2478 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 *prem = long_normalize(w);
2481 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002482}
2483
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002484/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2485 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2486 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2487 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2488 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2489 -1.0. */
2490
2491/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2492#if DBL_MANT_DIG == 53
2493#define EXP2_DBL_MANT_DIG 9007199254740992.0
2494#else
2495#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2496#endif
2497
2498double
2499_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2502 /* See below for why x_digits is always large enough. */
2503 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2504 double dx;
2505 /* Correction term for round-half-to-even rounding. For a digit x,
2506 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2507 multiple of 4, rounding ties to a multiple of 8. */
2508 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 a_size = ABS(Py_SIZE(a));
2511 if (a_size == 0) {
2512 /* Special case for 0: significand 0.0, exponent 0. */
2513 *e = 0;
2514 return 0.0;
2515 }
2516 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2517 /* The following is an overflow-free version of the check
2518 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2519 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2520 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2521 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002522 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2526 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 Number of digits needed for result: write // for floor division.
2529 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2538 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2541 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2542 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 in both cases.
2549 */
2550 if (a_bits <= DBL_MANT_DIG + 2) {
2551 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2552 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2553 x_size = 0;
2554 while (x_size < shift_digits)
2555 x_digits[x_size++] = 0;
2556 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2557 (int)shift_bits);
2558 x_size += a_size;
2559 x_digits[x_size++] = rem;
2560 }
2561 else {
2562 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2563 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2564 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2565 a_size - shift_digits, (int)shift_bits);
2566 x_size = a_size - shift_digits;
2567 /* For correct rounding below, we need the least significant
2568 bit of x to be 'sticky' for this shift: if any of the bits
2569 shifted out was nonzero, we set the least significant bit
2570 of x. */
2571 if (rem)
2572 x_digits[0] |= 1;
2573 else
2574 while (shift_digits > 0)
2575 if (a->ob_digit[--shift_digits]) {
2576 x_digits[0] |= 1;
2577 break;
2578 }
2579 }
Victor Stinner63941882011-09-29 00:42:28 +02002580 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 /* Round, and convert to double. */
2583 x_digits[0] += half_even_correction[x_digits[0] & 7];
2584 dx = x_digits[--x_size];
2585 while (x_size > 0)
2586 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 /* Rescale; make correction if result is 1.0. */
2589 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2590 if (dx == 1.0) {
2591 if (a_bits == PY_SSIZE_T_MAX)
2592 goto overflow;
2593 dx = 0.5;
2594 a_bits += 1;
2595 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 *e = a_bits;
2598 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002599
2600 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 /* exponent > PY_SSIZE_T_MAX */
2602 PyErr_SetString(PyExc_OverflowError,
2603 "huge integer: number of bits overflows a Py_ssize_t");
2604 *e = 0;
2605 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002606}
2607
2608/* Get a C double from a long int object. Rounds to the nearest double,
2609 using the round-half-to-even rule in the case of a tie. */
2610
2611double
2612PyLong_AsDouble(PyObject *v)
2613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 Py_ssize_t exponent;
2615 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002617 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyErr_BadInternalCall();
2619 return -1.0;
2620 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002621 if (!PyLong_Check(v)) {
2622 PyErr_SetString(PyExc_TypeError, "an integer is required");
2623 return -1.0;
2624 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2626 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2627 PyErr_SetString(PyExc_OverflowError,
2628 "long int too large to convert to float");
2629 return -1.0;
2630 }
2631 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002632}
2633
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002634/* Methods */
2635
2636static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002637long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002640}
2641
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002642static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002643long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 if (Py_SIZE(a) != Py_SIZE(b)) {
2648 sign = Py_SIZE(a) - Py_SIZE(b);
2649 }
2650 else {
2651 Py_ssize_t i = ABS(Py_SIZE(a));
2652 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2653 ;
2654 if (i < 0)
2655 sign = 0;
2656 else {
2657 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2658 if (Py_SIZE(a) < 0)
2659 sign = -sign;
2660 }
2661 }
2662 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002663}
2664
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002665#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002667
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002668static PyObject *
2669long_richcompare(PyObject *self, PyObject *other, int op)
2670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 int result;
2672 PyObject *v;
2673 CHECK_BINOP(self, other);
2674 if (self == other)
2675 result = 0;
2676 else
2677 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2678 /* Convert the return value to a Boolean */
2679 switch (op) {
2680 case Py_EQ:
2681 v = TEST_COND(result == 0);
2682 break;
2683 case Py_NE:
2684 v = TEST_COND(result != 0);
2685 break;
2686 case Py_LE:
2687 v = TEST_COND(result <= 0);
2688 break;
2689 case Py_GE:
2690 v = TEST_COND(result >= 0);
2691 break;
2692 case Py_LT:
2693 v = TEST_COND(result == -1);
2694 break;
2695 case Py_GT:
2696 v = TEST_COND(result == 1);
2697 break;
2698 default:
2699 PyErr_BadArgument();
2700 return NULL;
2701 }
2702 Py_INCREF(v);
2703 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002704}
2705
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002706static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002707long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002708{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002709 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 Py_ssize_t i;
2711 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 i = Py_SIZE(v);
2714 switch(i) {
2715 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2716 case 0: return 0;
2717 case 1: return v->ob_digit[0];
2718 }
2719 sign = 1;
2720 x = 0;
2721 if (i < 0) {
2722 sign = -1;
2723 i = -(i);
2724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002726 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2727 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2728 _PyHASH_MODULUS.
2729
2730 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2731 amounts to a rotation of the bits of x. To see this, write
2732
2733 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2734
2735 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2736 PyLong_SHIFT bits of x (those that are shifted out of the
2737 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2738 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2739 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2740 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2741 congruent to y modulo _PyHASH_MODULUS. So
2742
2743 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2744
2745 The right-hand side is just the result of rotating the
2746 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2747 not all _PyHASH_BITS bits of x are 1s, the same is true
2748 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2749 the reduction of x*2**PyLong_SHIFT modulo
2750 _PyHASH_MODULUS. */
2751 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2752 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002754 if (x >= _PyHASH_MODULUS)
2755 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 }
2757 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002758 if (x == (Py_uhash_t)-1)
2759 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002760 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002761}
2762
2763
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002764/* Add the absolute values of two long integers. */
2765
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002766static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002767x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2770 PyLongObject *z;
2771 Py_ssize_t i;
2772 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 /* Ensure a is the larger of the two: */
2775 if (size_a < size_b) {
2776 { PyLongObject *temp = a; a = b; b = temp; }
2777 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002778 size_a = size_b;
2779 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 }
2781 z = _PyLong_New(size_a+1);
2782 if (z == NULL)
2783 return NULL;
2784 for (i = 0; i < size_b; ++i) {
2785 carry += a->ob_digit[i] + b->ob_digit[i];
2786 z->ob_digit[i] = carry & PyLong_MASK;
2787 carry >>= PyLong_SHIFT;
2788 }
2789 for (; i < size_a; ++i) {
2790 carry += a->ob_digit[i];
2791 z->ob_digit[i] = carry & PyLong_MASK;
2792 carry >>= PyLong_SHIFT;
2793 }
2794 z->ob_digit[i] = carry;
2795 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002796}
2797
2798/* Subtract the absolute values of two integers. */
2799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002800static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002801x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2804 PyLongObject *z;
2805 Py_ssize_t i;
2806 int sign = 1;
2807 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 /* Ensure a is the larger of the two: */
2810 if (size_a < size_b) {
2811 sign = -1;
2812 { PyLongObject *temp = a; a = b; b = temp; }
2813 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002814 size_a = size_b;
2815 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 }
2817 else if (size_a == size_b) {
2818 /* Find highest digit where a and b differ: */
2819 i = size_a;
2820 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2821 ;
2822 if (i < 0)
2823 return (PyLongObject *)PyLong_FromLong(0);
2824 if (a->ob_digit[i] < b->ob_digit[i]) {
2825 sign = -1;
2826 { PyLongObject *temp = a; a = b; b = temp; }
2827 }
2828 size_a = size_b = i+1;
2829 }
2830 z = _PyLong_New(size_a);
2831 if (z == NULL)
2832 return NULL;
2833 for (i = 0; i < size_b; ++i) {
2834 /* The following assumes unsigned arithmetic
2835 works module 2**N for some N>PyLong_SHIFT. */
2836 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2837 z->ob_digit[i] = borrow & PyLong_MASK;
2838 borrow >>= PyLong_SHIFT;
2839 borrow &= 1; /* Keep only one sign bit */
2840 }
2841 for (; i < size_a; ++i) {
2842 borrow = a->ob_digit[i] - borrow;
2843 z->ob_digit[i] = borrow & PyLong_MASK;
2844 borrow >>= PyLong_SHIFT;
2845 borrow &= 1; /* Keep only one sign bit */
2846 }
2847 assert(borrow == 0);
2848 if (sign < 0)
2849 NEGATE(z);
2850 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002851}
2852
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002853static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002854long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2861 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2862 MEDIUM_VALUE(b));
2863 return result;
2864 }
2865 if (Py_SIZE(a) < 0) {
2866 if (Py_SIZE(b) < 0) {
2867 z = x_add(a, b);
2868 if (z != NULL && Py_SIZE(z) != 0)
2869 Py_SIZE(z) = -(Py_SIZE(z));
2870 }
2871 else
2872 z = x_sub(b, a);
2873 }
2874 else {
2875 if (Py_SIZE(b) < 0)
2876 z = x_sub(a, b);
2877 else
2878 z = x_add(a, b);
2879 }
2880 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002881}
2882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002883static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002884long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2891 PyObject* r;
2892 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2893 return r;
2894 }
2895 if (Py_SIZE(a) < 0) {
2896 if (Py_SIZE(b) < 0)
2897 z = x_sub(a, b);
2898 else
2899 z = x_add(a, b);
2900 if (z != NULL && Py_SIZE(z) != 0)
2901 Py_SIZE(z) = -(Py_SIZE(z));
2902 }
2903 else {
2904 if (Py_SIZE(b) < 0)
2905 z = x_add(a, b);
2906 else
2907 z = x_sub(a, b);
2908 }
2909 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002910}
2911
Tim Peters5af4e6c2002-08-12 02:31:19 +00002912/* Grade school multiplication, ignoring the signs.
2913 * Returns the absolute value of the product, or NULL if error.
2914 */
2915static PyLongObject *
2916x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 PyLongObject *z;
2919 Py_ssize_t size_a = ABS(Py_SIZE(a));
2920 Py_ssize_t size_b = ABS(Py_SIZE(b));
2921 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 z = _PyLong_New(size_a + size_b);
2924 if (z == NULL)
2925 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2928 if (a == b) {
2929 /* Efficient squaring per HAC, Algorithm 14.16:
2930 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2931 * Gives slightly less than a 2x speedup when a == b,
2932 * via exploiting that each entry in the multiplication
2933 * pyramid appears twice (except for the size_a squares).
2934 */
2935 for (i = 0; i < size_a; ++i) {
2936 twodigits carry;
2937 twodigits f = a->ob_digit[i];
2938 digit *pz = z->ob_digit + (i << 1);
2939 digit *pa = a->ob_digit + i + 1;
2940 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002943 Py_DECREF(z);
2944 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002945 });
Tim Peters0973b992004-08-29 22:16:50 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 carry = *pz + f * f;
2948 *pz++ = (digit)(carry & PyLong_MASK);
2949 carry >>= PyLong_SHIFT;
2950 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* Now f is added in twice in each column of the
2953 * pyramid it appears. Same as adding f<<1 once.
2954 */
2955 f <<= 1;
2956 while (pa < paend) {
2957 carry += *pz + *pa++ * f;
2958 *pz++ = (digit)(carry & PyLong_MASK);
2959 carry >>= PyLong_SHIFT;
2960 assert(carry <= (PyLong_MASK << 1));
2961 }
2962 if (carry) {
2963 carry += *pz;
2964 *pz++ = (digit)(carry & PyLong_MASK);
2965 carry >>= PyLong_SHIFT;
2966 }
2967 if (carry)
2968 *pz += (digit)(carry & PyLong_MASK);
2969 assert((carry >> PyLong_SHIFT) == 0);
2970 }
2971 }
2972 else { /* a is not the same as b -- gradeschool long mult */
2973 for (i = 0; i < size_a; ++i) {
2974 twodigits carry = 0;
2975 twodigits f = a->ob_digit[i];
2976 digit *pz = z->ob_digit + i;
2977 digit *pb = b->ob_digit;
2978 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002981 Py_DECREF(z);
2982 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002983 });
Tim Peters0973b992004-08-29 22:16:50 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 while (pb < pbend) {
2986 carry += *pz + *pb++ * f;
2987 *pz++ = (digit)(carry & PyLong_MASK);
2988 carry >>= PyLong_SHIFT;
2989 assert(carry <= PyLong_MASK);
2990 }
2991 if (carry)
2992 *pz += (digit)(carry & PyLong_MASK);
2993 assert((carry >> PyLong_SHIFT) == 0);
2994 }
2995 }
2996 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002997}
2998
2999/* A helper for Karatsuba multiplication (k_mul).
3000 Takes a long "n" and an integer "size" representing the place to
3001 split, and sets low and high such that abs(n) == (high << size) + low,
3002 viewing the shift as being by digits. The sign bit is ignored, and
3003 the return values are >= 0.
3004 Returns 0 on success, -1 on failure.
3005*/
3006static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003007kmul_split(PyLongObject *n,
3008 Py_ssize_t size,
3009 PyLongObject **high,
3010 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 PyLongObject *hi, *lo;
3013 Py_ssize_t size_lo, size_hi;
3014 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 size_lo = MIN(size_n, size);
3017 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 if ((hi = _PyLong_New(size_hi)) == NULL)
3020 return -1;
3021 if ((lo = _PyLong_New(size_lo)) == NULL) {
3022 Py_DECREF(hi);
3023 return -1;
3024 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3027 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 *high = long_normalize(hi);
3030 *low = long_normalize(lo);
3031 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003032}
3033
Tim Peters60004642002-08-12 22:01:34 +00003034static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3035
Tim Peters5af4e6c2002-08-12 02:31:19 +00003036/* Karatsuba multiplication. Ignores the input signs, and returns the
3037 * absolute value of the product (or NULL if error).
3038 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3039 */
3040static PyLongObject *
3041k_mul(PyLongObject *a, PyLongObject *b)
3042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 Py_ssize_t asize = ABS(Py_SIZE(a));
3044 Py_ssize_t bsize = ABS(Py_SIZE(b));
3045 PyLongObject *ah = NULL;
3046 PyLongObject *al = NULL;
3047 PyLongObject *bh = NULL;
3048 PyLongObject *bl = NULL;
3049 PyLongObject *ret = NULL;
3050 PyLongObject *t1, *t2, *t3;
3051 Py_ssize_t shift; /* the number of digits we split off */
3052 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3055 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3056 * Then the original product is
3057 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3058 * By picking X to be a power of 2, "*X" is just shifting, and it's
3059 * been reduced to 3 multiplies on numbers half the size.
3060 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* We want to split based on the larger number; fiddle so that b
3063 * is largest.
3064 */
3065 if (asize > bsize) {
3066 t1 = a;
3067 a = b;
3068 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 i = asize;
3071 asize = bsize;
3072 bsize = i;
3073 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 /* Use gradeschool math when either number is too small. */
3076 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3077 if (asize <= i) {
3078 if (asize == 0)
3079 return (PyLongObject *)PyLong_FromLong(0);
3080 else
3081 return x_mul(a, b);
3082 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 /* If a is small compared to b, splitting on b gives a degenerate
3085 * case with ah==0, and Karatsuba may be (even much) less efficient
3086 * than "grade school" then. However, we can still win, by viewing
3087 * b as a string of "big digits", each of width a->ob_size. That
3088 * leads to a sequence of balanced calls to k_mul.
3089 */
3090 if (2 * asize <= bsize)
3091 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 /* Split a & b into hi & lo pieces. */
3094 shift = bsize >> 1;
3095 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3096 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 if (a == b) {
3099 bh = ah;
3100 bl = al;
3101 Py_INCREF(bh);
3102 Py_INCREF(bl);
3103 }
3104 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 /* The plan:
3107 * 1. Allocate result space (asize + bsize digits: that's always
3108 * enough).
3109 * 2. Compute ah*bh, and copy into result at 2*shift.
3110 * 3. Compute al*bl, and copy into result at 0. Note that this
3111 * can't overlap with #2.
3112 * 4. Subtract al*bl from the result, starting at shift. This may
3113 * underflow (borrow out of the high digit), but we don't care:
3114 * we're effectively doing unsigned arithmetic mod
3115 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3116 * borrows and carries out of the high digit can be ignored.
3117 * 5. Subtract ah*bh from the result, starting at shift.
3118 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3119 * at shift.
3120 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 /* 1. Allocate result space. */
3123 ret = _PyLong_New(asize + bsize);
3124 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003125#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 /* Fill with trash, to catch reference to uninitialized digits. */
3127 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003128#endif
Tim Peters44121a62002-08-12 06:17:58 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3131 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3132 assert(Py_SIZE(t1) >= 0);
3133 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3134 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3135 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 /* Zero-out the digits higher than the ah*bh copy. */
3138 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3139 if (i)
3140 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3141 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 /* 3. t2 <- al*bl, and copy into the low digits. */
3144 if ((t2 = k_mul(al, bl)) == NULL) {
3145 Py_DECREF(t1);
3146 goto fail;
3147 }
3148 assert(Py_SIZE(t2) >= 0);
3149 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3150 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 /* Zero out remaining digits. */
3153 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3154 if (i)
3155 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3158 * because it's fresher in cache.
3159 */
3160 i = Py_SIZE(ret) - shift; /* # digits after shift */
3161 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3162 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3165 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3168 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3169 Py_DECREF(ah);
3170 Py_DECREF(al);
3171 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 if (a == b) {
3174 t2 = t1;
3175 Py_INCREF(t2);
3176 }
3177 else if ((t2 = x_add(bh, bl)) == NULL) {
3178 Py_DECREF(t1);
3179 goto fail;
3180 }
3181 Py_DECREF(bh);
3182 Py_DECREF(bl);
3183 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 t3 = k_mul(t1, t2);
3186 Py_DECREF(t1);
3187 Py_DECREF(t2);
3188 if (t3 == NULL) goto fail;
3189 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 /* Add t3. It's not obvious why we can't run out of room here.
3192 * See the (*) comment after this function.
3193 */
3194 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3195 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003198
Mark Dickinson22b20182010-05-10 21:27:53 +00003199 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 Py_XDECREF(ret);
3201 Py_XDECREF(ah);
3202 Py_XDECREF(al);
3203 Py_XDECREF(bh);
3204 Py_XDECREF(bl);
3205 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206}
3207
Tim Petersd6974a52002-08-13 20:37:51 +00003208/* (*) Why adding t3 can't "run out of room" above.
3209
Tim Petersab86c2b2002-08-15 20:06:00 +00003210Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3211to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003212
Tim Petersab86c2b2002-08-15 20:06:00 +000032131. For any integer i, i = c(i/2) + f(i/2). In particular,
3214 bsize = c(bsize/2) + f(bsize/2).
32152. shift = f(bsize/2)
32163. asize <= bsize
32174. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3218 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003219
Tim Petersab86c2b2002-08-15 20:06:00 +00003220We allocated asize + bsize result digits, and add t3 into them at an offset
3221of shift. This leaves asize+bsize-shift allocated digit positions for t3
3222to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3223asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003224
Tim Petersab86c2b2002-08-15 20:06:00 +00003225bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3226at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003227
Tim Petersab86c2b2002-08-15 20:06:00 +00003228If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3229digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3230most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003231
Tim Petersab86c2b2002-08-15 20:06:00 +00003232The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003233
Tim Petersab86c2b2002-08-15 20:06:00 +00003234 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003235
Tim Petersab86c2b2002-08-15 20:06:00 +00003236and we have asize + c(bsize/2) available digit positions. We need to show
3237this is always enough. An instance of c(bsize/2) cancels out in both, so
3238the question reduces to whether asize digits is enough to hold
3239(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3240then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3241asize 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 +00003242digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003243asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003244c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3245is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3246bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003247
Tim Peters48d52c02002-08-14 17:07:32 +00003248Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3249clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3250ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003251*/
3252
Tim Peters60004642002-08-12 22:01:34 +00003253/* b has at least twice the digits of a, and a is big enough that Karatsuba
3254 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3255 * of slices, each with a->ob_size digits, and multiply the slices by a,
3256 * one at a time. This gives k_mul balanced inputs to work with, and is
3257 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003258 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003259 * single-width slice overlap between successive partial sums).
3260 */
3261static PyLongObject *
3262k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 const Py_ssize_t asize = ABS(Py_SIZE(a));
3265 Py_ssize_t bsize = ABS(Py_SIZE(b));
3266 Py_ssize_t nbdone; /* # of b digits already multiplied */
3267 PyLongObject *ret;
3268 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 assert(asize > KARATSUBA_CUTOFF);
3271 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 /* Allocate result space, and zero it out. */
3274 ret = _PyLong_New(asize + bsize);
3275 if (ret == NULL)
3276 return NULL;
3277 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 /* Successive slices of b are copied into bslice. */
3280 bslice = _PyLong_New(asize);
3281 if (bslice == NULL)
3282 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 nbdone = 0;
3285 while (bsize > 0) {
3286 PyLongObject *product;
3287 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 /* Multiply the next slice of b by a. */
3290 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3291 nbtouse * sizeof(digit));
3292 Py_SIZE(bslice) = nbtouse;
3293 product = k_mul(a, bslice);
3294 if (product == NULL)
3295 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* Add into result. */
3298 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3299 product->ob_digit, Py_SIZE(product));
3300 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 bsize -= nbtouse;
3303 nbdone += nbtouse;
3304 }
Tim Peters60004642002-08-12 22:01:34 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 Py_DECREF(bslice);
3307 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003308
Mark Dickinson22b20182010-05-10 21:27:53 +00003309 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 Py_DECREF(ret);
3311 Py_XDECREF(bslice);
3312 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003313}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003314
3315static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003316long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 /* fast path for single-digit multiplication */
3323 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3324 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003325#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003327#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 /* if we don't have long long then we're almost certainly
3329 using 15-bit digits, so v will fit in a long. In the
3330 unlikely event that we're using 30-bit digits on a platform
3331 without long long, a large v will just cause us to fall
3332 through to the general multiplication code below. */
3333 if (v >= LONG_MIN && v <= LONG_MAX)
3334 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003335#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 z = k_mul(a, b);
3339 /* Negate if exactly one of the inputs is negative. */
3340 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3341 NEGATE(z);
3342 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003343}
3344
Guido van Rossume32e0141992-01-19 16:31:05 +00003345/* The / and % operators are now defined in terms of divmod().
3346 The expression a mod b has the value a - b*floor(a/b).
3347 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003348 |a| by |b|, with the sign of a. This is also expressed
3349 as a - b*trunc(a/b), if trunc truncates towards zero.
3350 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 a b a rem b a mod b
3352 13 10 3 3
3353 -13 10 -3 7
3354 13 -10 3 -7
3355 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003356 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003357 have different signs. We then subtract one from the 'div'
3358 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003359
Tim Peters47e52ee2004-08-30 02:44:38 +00003360/* Compute
3361 * *pdiv, *pmod = divmod(v, w)
3362 * NULL can be passed for pdiv or pmod, in which case that part of
3363 * the result is simply thrown away. The caller owns a reference to
3364 * each of these it requests (does not pass NULL for).
3365 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003366static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003367l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 if (long_divrem(v, w, &div, &mod) < 0)
3373 return -1;
3374 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3375 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3376 PyLongObject *temp;
3377 PyLongObject *one;
3378 temp = (PyLongObject *) long_add(mod, w);
3379 Py_DECREF(mod);
3380 mod = temp;
3381 if (mod == NULL) {
3382 Py_DECREF(div);
3383 return -1;
3384 }
3385 one = (PyLongObject *) PyLong_FromLong(1L);
3386 if (one == NULL ||
3387 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3388 Py_DECREF(mod);
3389 Py_DECREF(div);
3390 Py_XDECREF(one);
3391 return -1;
3392 }
3393 Py_DECREF(one);
3394 Py_DECREF(div);
3395 div = temp;
3396 }
3397 if (pdiv != NULL)
3398 *pdiv = div;
3399 else
3400 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 if (pmod != NULL)
3403 *pmod = mod;
3404 else
3405 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003408}
3409
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003410static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003411long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 CHECK_BINOP(a, b);
3416 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3417 div = NULL;
3418 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003419}
3420
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003421/* PyLong/PyLong -> float, with correctly rounded result. */
3422
3423#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3424#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003426static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003427long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 PyLongObject *a, *b, *x;
3430 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3431 digit mask, low;
3432 int inexact, negate, a_is_small, b_is_small;
3433 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 CHECK_BINOP(v, w);
3436 a = (PyLongObject *)v;
3437 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 /*
3440 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3443 1. choose a suitable integer 'shift'
3444 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3445 3. adjust x for correct rounding
3446 4. convert x to a double dx with the same value
3447 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3452 returns either 0.0 or -0.0, depending on the sign of b. For a and
3453 b both nonzero, ignore signs of a and b, and add the sign back in
3454 at the end. Now write a_bits and b_bits for the bit lengths of a
3455 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3456 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3461 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3462 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3463 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 1. The integer 'shift' is chosen so that x has the right number of
3468 bits for a double, plus two or three extra bits that will be used
3469 in the rounding decisions. Writing a_bits and b_bits for the
3470 number of significant bits in a and b respectively, a
3471 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 This is fine in the usual case, but if a/b is smaller than the
3476 smallest normal float then it can lead to double rounding on an
3477 IEEE 754 platform, giving incorrectly rounded results. So we
3478 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 2. The quantity x is computed by first shifting a (left -shift bits
3483 if shift <= 0, right shift bits if shift > 0) and then dividing by
3484 b. For both the shift and the division, we keep track of whether
3485 the result is inexact, in a flag 'inexact'; this information is
3486 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 With the choice of shift above, together with our assumption that
3489 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3490 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3493 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 For float representability, we need x/2**extra_bits <
3498 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3499 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 To round, we just modify the bottom digit of x in-place; this can
3504 end up giving a digit with value > PyLONG_MASK, but that's not a
3505 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 With the original choices for shift above, extra_bits will always
3508 be 2 or 3. Then rounding under the round-half-to-even rule, we
3509 round up iff the most significant of the extra bits is 1, and
3510 either: (a) the computation of x in step 2 had an inexact result,
3511 or (b) at least one other of the extra bits is 1, or (c) the least
3512 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 4. Conversion to a double is straightforward; all floating-point
3515 operations involved in the conversion are exact, so there's no
3516 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3519 The result will always be exactly representable as a double, except
3520 in the case that it overflows. To avoid dependence on the exact
3521 behaviour of ldexp on overflow, we check for overflow before
3522 applying ldexp. The result of ldexp is adjusted for sign before
3523 returning.
3524 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 /* Reduce to case where a and b are both positive. */
3527 a_size = ABS(Py_SIZE(a));
3528 b_size = ABS(Py_SIZE(b));
3529 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3530 if (b_size == 0) {
3531 PyErr_SetString(PyExc_ZeroDivisionError,
3532 "division by zero");
3533 goto error;
3534 }
3535 if (a_size == 0)
3536 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 /* Fast path for a and b small (exactly representable in a double).
3539 Relies on floating-point division being correctly rounded; results
3540 may be subject to double rounding on x86 machines that operate with
3541 the x87 FPU set to 64-bit precision. */
3542 a_is_small = a_size <= MANT_DIG_DIGITS ||
3543 (a_size == MANT_DIG_DIGITS+1 &&
3544 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3545 b_is_small = b_size <= MANT_DIG_DIGITS ||
3546 (b_size == MANT_DIG_DIGITS+1 &&
3547 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3548 if (a_is_small && b_is_small) {
3549 double da, db;
3550 da = a->ob_digit[--a_size];
3551 while (a_size > 0)
3552 da = da * PyLong_BASE + a->ob_digit[--a_size];
3553 db = b->ob_digit[--b_size];
3554 while (b_size > 0)
3555 db = db * PyLong_BASE + b->ob_digit[--b_size];
3556 result = da / db;
3557 goto success;
3558 }
Tim Peterse2a60002001-09-04 06:17:36 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 /* Catch obvious cases of underflow and overflow */
3561 diff = a_size - b_size;
3562 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3563 /* Extreme overflow */
3564 goto overflow;
3565 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3566 /* Extreme underflow */
3567 goto underflow_or_zero;
3568 /* Next line is now safe from overflowing a Py_ssize_t */
3569 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3570 bits_in_digit(b->ob_digit[b_size - 1]);
3571 /* Now diff = a_bits - b_bits. */
3572 if (diff > DBL_MAX_EXP)
3573 goto overflow;
3574 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3575 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 /* Choose value for shift; see comments for step 1 above. */
3578 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 /* x = abs(a * 2**-shift) */
3583 if (shift <= 0) {
3584 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3585 digit rem;
3586 /* x = a << -shift */
3587 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3588 /* In practice, it's probably impossible to end up
3589 here. Both a and b would have to be enormous,
3590 using close to SIZE_T_MAX bytes of memory each. */
3591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003592 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 goto error;
3594 }
3595 x = _PyLong_New(a_size + shift_digits + 1);
3596 if (x == NULL)
3597 goto error;
3598 for (i = 0; i < shift_digits; i++)
3599 x->ob_digit[i] = 0;
3600 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3601 a_size, -shift % PyLong_SHIFT);
3602 x->ob_digit[a_size + shift_digits] = rem;
3603 }
3604 else {
3605 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3606 digit rem;
3607 /* x = a >> shift */
3608 assert(a_size >= shift_digits);
3609 x = _PyLong_New(a_size - shift_digits);
3610 if (x == NULL)
3611 goto error;
3612 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3613 a_size - shift_digits, shift % PyLong_SHIFT);
3614 /* set inexact if any of the bits shifted out is nonzero */
3615 if (rem)
3616 inexact = 1;
3617 while (!inexact && shift_digits > 0)
3618 if (a->ob_digit[--shift_digits])
3619 inexact = 1;
3620 }
3621 long_normalize(x);
3622 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3625 reference to x, so it's safe to modify it in-place. */
3626 if (b_size == 1) {
3627 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3628 b->ob_digit[0]);
3629 long_normalize(x);
3630 if (rem)
3631 inexact = 1;
3632 }
3633 else {
3634 PyLongObject *div, *rem;
3635 div = x_divrem(x, b, &rem);
3636 Py_DECREF(x);
3637 x = div;
3638 if (x == NULL)
3639 goto error;
3640 if (Py_SIZE(rem))
3641 inexact = 1;
3642 Py_DECREF(rem);
3643 }
3644 x_size = ABS(Py_SIZE(x));
3645 assert(x_size > 0); /* result of division is never zero */
3646 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* The number of extra bits that have to be rounded away. */
3649 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3650 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 /* Round by directly modifying the low digit of x. */
3653 mask = (digit)1 << (extra_bits - 1);
3654 low = x->ob_digit[0] | inexact;
3655 if (low & mask && low & (3*mask-1))
3656 low += mask;
3657 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 /* Convert x to a double dx; the conversion is exact. */
3660 dx = x->ob_digit[--x_size];
3661 while (x_size > 0)
3662 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3663 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 /* Check whether ldexp result will overflow a double. */
3666 if (shift + x_bits >= DBL_MAX_EXP &&
3667 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3668 goto overflow;
3669 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003670
3671 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003673
3674 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003676
3677 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 PyErr_SetString(PyExc_OverflowError,
3679 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003680 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003682}
3683
3684static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003685long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 CHECK_BINOP(a, b);
3690
3691 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3692 mod = NULL;
3693 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003694}
3695
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003696static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003697long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 PyLongObject *div, *mod;
3700 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3705 return NULL;
3706 }
3707 z = PyTuple_New(2);
3708 if (z != NULL) {
3709 PyTuple_SetItem(z, 0, (PyObject *) div);
3710 PyTuple_SetItem(z, 1, (PyObject *) mod);
3711 }
3712 else {
3713 Py_DECREF(div);
3714 Py_DECREF(mod);
3715 }
3716 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003717}
3718
Tim Peters47e52ee2004-08-30 02:44:38 +00003719/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003720static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003721long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3724 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 PyLongObject *z = NULL; /* accumulated result */
3727 Py_ssize_t i, j, k; /* counters */
3728 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 /* 5-ary values. If the exponent is large enough, table is
3731 * precomputed so that table[i] == a**i % c for i in range(32).
3732 */
3733 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3734 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 /* a, b, c = v, w, x */
3737 CHECK_BINOP(v, w);
3738 a = (PyLongObject*)v; Py_INCREF(a);
3739 b = (PyLongObject*)w; Py_INCREF(b);
3740 if (PyLong_Check(x)) {
3741 c = (PyLongObject *)x;
3742 Py_INCREF(x);
3743 }
3744 else if (x == Py_None)
3745 c = NULL;
3746 else {
3747 Py_DECREF(a);
3748 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003749 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 }
Tim Peters4c483c42001-09-05 06:24:58 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3753 if (c) {
3754 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003755 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 goto Error;
3757 }
3758 else {
3759 /* else return a float. This works because we know
3760 that this calls float_pow() which converts its
3761 arguments to double. */
3762 Py_DECREF(a);
3763 Py_DECREF(b);
3764 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3765 }
3766 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 if (c) {
3769 /* if modulus == 0:
3770 raise ValueError() */
3771 if (Py_SIZE(c) == 0) {
3772 PyErr_SetString(PyExc_ValueError,
3773 "pow() 3rd argument cannot be 0");
3774 goto Error;
3775 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 /* if modulus < 0:
3778 negativeOutput = True
3779 modulus = -modulus */
3780 if (Py_SIZE(c) < 0) {
3781 negativeOutput = 1;
3782 temp = (PyLongObject *)_PyLong_Copy(c);
3783 if (temp == NULL)
3784 goto Error;
3785 Py_DECREF(c);
3786 c = temp;
3787 temp = NULL;
3788 NEGATE(c);
3789 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 /* if modulus == 1:
3792 return 0 */
3793 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3794 z = (PyLongObject *)PyLong_FromLong(0L);
3795 goto Done;
3796 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 /* if base < 0:
3799 base = base % modulus
3800 Having the base positive just makes things easier. */
3801 if (Py_SIZE(a) < 0) {
3802 if (l_divmod(a, c, NULL, &temp) < 0)
3803 goto Error;
3804 Py_DECREF(a);
3805 a = temp;
3806 temp = NULL;
3807 }
3808 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 /* At this point a, b, and c are guaranteed non-negative UNLESS
3811 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 z = (PyLongObject *)PyLong_FromLong(1L);
3814 if (z == NULL)
3815 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 /* Perform a modular reduction, X = X % c, but leave X alone if c
3818 * is NULL.
3819 */
3820#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003821 do { \
3822 if (c != NULL) { \
3823 if (l_divmod(X, c, NULL, &temp) < 0) \
3824 goto Error; \
3825 Py_XDECREF(X); \
3826 X = temp; \
3827 temp = NULL; \
3828 } \
3829 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 /* Multiply two values, then reduce the result:
3832 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003833#define MULT(X, Y, result) \
3834 do { \
3835 temp = (PyLongObject *)long_mul(X, Y); \
3836 if (temp == NULL) \
3837 goto Error; \
3838 Py_XDECREF(result); \
3839 result = temp; \
3840 temp = NULL; \
3841 REDUCE(result); \
3842 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3845 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3846 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3847 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3848 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003851 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003853 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 }
3855 }
3856 }
3857 else {
3858 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3859 Py_INCREF(z); /* still holds 1L */
3860 table[0] = z;
3861 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003862 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3865 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3868 const int index = (bi >> j) & 0x1f;
3869 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003870 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003872 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 }
3874 }
3875 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 if (negativeOutput && (Py_SIZE(z) != 0)) {
3878 temp = (PyLongObject *)long_sub(z, c);
3879 if (temp == NULL)
3880 goto Error;
3881 Py_DECREF(z);
3882 z = temp;
3883 temp = NULL;
3884 }
3885 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003886
Mark Dickinson22b20182010-05-10 21:27:53 +00003887 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 if (z != NULL) {
3889 Py_DECREF(z);
3890 z = NULL;
3891 }
3892 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003893 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3895 for (i = 0; i < 32; ++i)
3896 Py_XDECREF(table[i]);
3897 }
3898 Py_DECREF(a);
3899 Py_DECREF(b);
3900 Py_XDECREF(c);
3901 Py_XDECREF(temp);
3902 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003903}
3904
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003905static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003906long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* Implement ~x as -(x+1) */
3909 PyLongObject *x;
3910 PyLongObject *w;
3911 if (ABS(Py_SIZE(v)) <=1)
3912 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3913 w = (PyLongObject *)PyLong_FromLong(1L);
3914 if (w == NULL)
3915 return NULL;
3916 x = (PyLongObject *) long_add(v, w);
3917 Py_DECREF(w);
3918 if (x == NULL)
3919 return NULL;
3920 Py_SIZE(x) = -(Py_SIZE(x));
3921 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003922}
3923
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003924static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003925long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 PyLongObject *z;
3928 if (ABS(Py_SIZE(v)) <= 1)
3929 return PyLong_FromLong(-MEDIUM_VALUE(v));
3930 z = (PyLongObject *)_PyLong_Copy(v);
3931 if (z != NULL)
3932 Py_SIZE(z) = -(Py_SIZE(v));
3933 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003934}
3935
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003936static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003937long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 if (Py_SIZE(v) < 0)
3940 return long_neg(v);
3941 else
3942 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003943}
3944
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003945static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003946long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003949}
3950
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003951static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003952long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 PyLongObject *z = NULL;
3955 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3956 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 if (Py_SIZE(a) < 0) {
3961 /* Right shifting negative numbers is harder */
3962 PyLongObject *a1, *a2;
3963 a1 = (PyLongObject *) long_invert(a);
3964 if (a1 == NULL)
3965 goto rshift_error;
3966 a2 = (PyLongObject *) long_rshift(a1, b);
3967 Py_DECREF(a1);
3968 if (a2 == NULL)
3969 goto rshift_error;
3970 z = (PyLongObject *) long_invert(a2);
3971 Py_DECREF(a2);
3972 }
3973 else {
3974 shiftby = PyLong_AsSsize_t((PyObject *)b);
3975 if (shiftby == -1L && PyErr_Occurred())
3976 goto rshift_error;
3977 if (shiftby < 0) {
3978 PyErr_SetString(PyExc_ValueError,
3979 "negative shift count");
3980 goto rshift_error;
3981 }
3982 wordshift = shiftby / PyLong_SHIFT;
3983 newsize = ABS(Py_SIZE(a)) - wordshift;
3984 if (newsize <= 0)
3985 return PyLong_FromLong(0);
3986 loshift = shiftby % PyLong_SHIFT;
3987 hishift = PyLong_SHIFT - loshift;
3988 lomask = ((digit)1 << hishift) - 1;
3989 himask = PyLong_MASK ^ lomask;
3990 z = _PyLong_New(newsize);
3991 if (z == NULL)
3992 goto rshift_error;
3993 if (Py_SIZE(a) < 0)
3994 Py_SIZE(z) = -(Py_SIZE(z));
3995 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3996 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3997 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003998 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 }
4000 z = long_normalize(z);
4001 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004002 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004004
Guido van Rossumc6913e71991-11-19 20:26:46 +00004005}
4006
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004007static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004008long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 /* This version due to Tim Peters */
4011 PyLongObject *a = (PyLongObject*)v;
4012 PyLongObject *b = (PyLongObject*)w;
4013 PyLongObject *z = NULL;
4014 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4015 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 shiftby = PyLong_AsSsize_t((PyObject *)b);
4020 if (shiftby == -1L && PyErr_Occurred())
4021 goto lshift_error;
4022 if (shiftby < 0) {
4023 PyErr_SetString(PyExc_ValueError, "negative shift count");
4024 goto lshift_error;
4025 }
4026 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4027 wordshift = shiftby / PyLong_SHIFT;
4028 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 oldsize = ABS(Py_SIZE(a));
4031 newsize = oldsize + wordshift;
4032 if (remshift)
4033 ++newsize;
4034 z = _PyLong_New(newsize);
4035 if (z == NULL)
4036 goto lshift_error;
4037 if (Py_SIZE(a) < 0)
4038 NEGATE(z);
4039 for (i = 0; i < wordshift; i++)
4040 z->ob_digit[i] = 0;
4041 accum = 0;
4042 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4043 accum |= (twodigits)a->ob_digit[j] << remshift;
4044 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4045 accum >>= PyLong_SHIFT;
4046 }
4047 if (remshift)
4048 z->ob_digit[newsize-1] = (digit)accum;
4049 else
4050 assert(!accum);
4051 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004052 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004054}
4055
Mark Dickinson27a87a22009-10-25 20:43:34 +00004056/* Compute two's complement of digit vector a[0:m], writing result to
4057 z[0:m]. The digit vector a need not be normalized, but should not
4058 be entirely zero. a and z may point to the same digit vector. */
4059
4060static void
4061v_complement(digit *z, digit *a, Py_ssize_t m)
4062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 Py_ssize_t i;
4064 digit carry = 1;
4065 for (i = 0; i < m; ++i) {
4066 carry += a[i] ^ PyLong_MASK;
4067 z[i] = carry & PyLong_MASK;
4068 carry >>= PyLong_SHIFT;
4069 }
4070 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004071}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004072
4073/* Bitwise and/xor/or operations */
4074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004075static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004076long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004078 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 int nega, negb, negz;
4081 Py_ssize_t size_a, size_b, size_z, i;
4082 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 /* Bitwise operations for negative numbers operate as though
4085 on a two's complement representation. So convert arguments
4086 from sign-magnitude to two's complement, and convert the
4087 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 /* If a is negative, replace it by its two's complement. */
4090 size_a = ABS(Py_SIZE(a));
4091 nega = Py_SIZE(a) < 0;
4092 if (nega) {
4093 z = _PyLong_New(size_a);
4094 if (z == NULL)
4095 return NULL;
4096 v_complement(z->ob_digit, a->ob_digit, size_a);
4097 a = z;
4098 }
4099 else
4100 /* Keep reference count consistent. */
4101 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* Same for b. */
4104 size_b = ABS(Py_SIZE(b));
4105 negb = Py_SIZE(b) < 0;
4106 if (negb) {
4107 z = _PyLong_New(size_b);
4108 if (z == NULL) {
4109 Py_DECREF(a);
4110 return NULL;
4111 }
4112 v_complement(z->ob_digit, b->ob_digit, size_b);
4113 b = z;
4114 }
4115 else
4116 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 /* Swap a and b if necessary to ensure size_a >= size_b. */
4119 if (size_a < size_b) {
4120 z = a; a = b; b = z;
4121 size_z = size_a; size_a = size_b; size_b = size_z;
4122 negz = nega; nega = negb; negb = negz;
4123 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 /* JRH: The original logic here was to allocate the result value (z)
4126 as the longer of the two operands. However, there are some cases
4127 where the result is guaranteed to be shorter than that: AND of two
4128 positives, OR of two negatives: use the shorter number. AND with
4129 mixed signs: use the positive number. OR with mixed signs: use the
4130 negative number.
4131 */
4132 switch (op) {
4133 case '^':
4134 negz = nega ^ negb;
4135 size_z = size_a;
4136 break;
4137 case '&':
4138 negz = nega & negb;
4139 size_z = negb ? size_a : size_b;
4140 break;
4141 case '|':
4142 negz = nega | negb;
4143 size_z = negb ? size_b : size_a;
4144 break;
4145 default:
4146 PyErr_BadArgument();
4147 return NULL;
4148 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 /* We allow an extra digit if z is negative, to make sure that
4151 the final two's complement of z doesn't overflow. */
4152 z = _PyLong_New(size_z + negz);
4153 if (z == NULL) {
4154 Py_DECREF(a);
4155 Py_DECREF(b);
4156 return NULL;
4157 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 /* Compute digits for overlap of a and b. */
4160 switch(op) {
4161 case '&':
4162 for (i = 0; i < size_b; ++i)
4163 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4164 break;
4165 case '|':
4166 for (i = 0; i < size_b; ++i)
4167 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4168 break;
4169 case '^':
4170 for (i = 0; i < size_b; ++i)
4171 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4172 break;
4173 default:
4174 PyErr_BadArgument();
4175 return NULL;
4176 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 /* Copy any remaining digits of a, inverting if necessary. */
4179 if (op == '^' && negb)
4180 for (; i < size_z; ++i)
4181 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4182 else if (i < size_z)
4183 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4184 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 /* Complement result if negative. */
4187 if (negz) {
4188 Py_SIZE(z) = -(Py_SIZE(z));
4189 z->ob_digit[size_z] = PyLong_MASK;
4190 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4191 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 Py_DECREF(a);
4194 Py_DECREF(b);
4195 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004196}
4197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004198static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004199long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 PyObject *c;
4202 CHECK_BINOP(a, b);
4203 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4204 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004205}
4206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004207static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004208long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 PyObject *c;
4211 CHECK_BINOP(a, b);
4212 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4213 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004214}
4215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004216static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004217long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 PyObject *c;
4220 CHECK_BINOP(a, b);
4221 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4222 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004223}
4224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004225static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004226long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 if (PyLong_CheckExact(v))
4229 Py_INCREF(v);
4230 else
4231 v = _PyLong_Copy((PyLongObject *)v);
4232 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004233}
4234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004235static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004236long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 double result;
4239 result = PyLong_AsDouble(v);
4240 if (result == -1.0 && PyErr_Occurred())
4241 return NULL;
4242 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004243}
4244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004245static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004246long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004247
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248static PyObject *
4249long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4250{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004251 PyObject *obase = NULL, *x = NULL;
4252 long base;
4253 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 if (type != &PyLong_Type)
4257 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004258 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4259 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 return NULL;
4261 if (x == NULL)
4262 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004263 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004265
4266 base = PyLong_AsLongAndOverflow(obase, &overflow);
4267 if (base == -1 && PyErr_Occurred())
4268 return NULL;
4269 if (overflow || (base != 0 && base < 2) || base > 36) {
4270 PyErr_SetString(PyExc_ValueError,
4271 "int() arg 2 must be >= 2 and <= 36");
4272 return NULL;
4273 }
4274
4275 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004276 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4278 /* Since PyLong_FromString doesn't have a length parameter,
4279 * check here for possible NULs in the string. */
4280 char *string;
4281 Py_ssize_t size = Py_SIZE(x);
4282 if (PyByteArray_Check(x))
4283 string = PyByteArray_AS_STRING(x);
4284 else
4285 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004286 if (strlen(string) != (size_t)size || !size) {
4287 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 x is a bytes or buffer, *and* a base is given. */
4289 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004290 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004291 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 return NULL;
4293 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004294 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 }
4296 else {
4297 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004298 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 return NULL;
4300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301}
4302
Guido van Rossumbef14172001-08-29 15:47:46 +00004303/* Wimpy, slow approach to tp_new calls for subtypes of long:
4304 first create a regular long from whatever arguments we got,
4305 then allocate a subtype instance and initialize it from
4306 the regular long. The regular long is then thrown away.
4307*/
4308static PyObject *
4309long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 PyLongObject *tmp, *newobj;
4312 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 assert(PyType_IsSubtype(type, &PyLong_Type));
4315 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4316 if (tmp == NULL)
4317 return NULL;
4318 assert(PyLong_CheckExact(tmp));
4319 n = Py_SIZE(tmp);
4320 if (n < 0)
4321 n = -n;
4322 newobj = (PyLongObject *)type->tp_alloc(type, n);
4323 if (newobj == NULL) {
4324 Py_DECREF(tmp);
4325 return NULL;
4326 }
4327 assert(PyLong_Check(newobj));
4328 Py_SIZE(newobj) = Py_SIZE(tmp);
4329 for (i = 0; i < n; i++)
4330 newobj->ob_digit[i] = tmp->ob_digit[i];
4331 Py_DECREF(tmp);
4332 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004333}
4334
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004335static PyObject *
4336long_getnewargs(PyLongObject *v)
4337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004339}
4340
Guido van Rossumb43daf72007-08-01 18:08:08 +00004341static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004342long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004344}
4345
4346static PyObject *
4347long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004349}
4350
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004351static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004352long__format__(PyObject *self, PyObject *args)
4353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004355 _PyUnicodeWriter writer;
4356 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4359 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004360
4361 _PyUnicodeWriter_Init(&writer, 0);
4362 ret = _PyLong_FormatAdvancedWriter(
4363 &writer,
4364 self,
4365 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4366 if (ret == -1) {
4367 _PyUnicodeWriter_Dealloc(&writer);
4368 return NULL;
4369 }
4370 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004371}
4372
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004373/* Return a pair (q, r) such that a = b * q + r, and
4374 abs(r) <= abs(b)/2, with equality possible only if q is even.
4375 In other words, q == a / b, rounded to the nearest integer using
4376 round-half-to-even. */
4377
4378PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004379_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004380{
4381 PyLongObject *quo = NULL, *rem = NULL;
4382 PyObject *one = NULL, *twice_rem, *result, *temp;
4383 int cmp, quo_is_odd, quo_is_neg;
4384
4385 /* Equivalent Python code:
4386
4387 def divmod_near(a, b):
4388 q, r = divmod(a, b)
4389 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4390 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4391 # positive, 2 * r < b if b negative.
4392 greater_than_half = 2*r > b if b > 0 else 2*r < b
4393 exactly_half = 2*r == b
4394 if greater_than_half or exactly_half and q % 2 == 1:
4395 q += 1
4396 r -= b
4397 return q, r
4398
4399 */
4400 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4401 PyErr_SetString(PyExc_TypeError,
4402 "non-integer arguments in division");
4403 return NULL;
4404 }
4405
4406 /* Do a and b have different signs? If so, quotient is negative. */
4407 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4408
4409 one = PyLong_FromLong(1L);
4410 if (one == NULL)
4411 return NULL;
4412
4413 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4414 goto error;
4415
4416 /* compare twice the remainder with the divisor, to see
4417 if we need to adjust the quotient and remainder */
4418 twice_rem = long_lshift((PyObject *)rem, one);
4419 if (twice_rem == NULL)
4420 goto error;
4421 if (quo_is_neg) {
4422 temp = long_neg((PyLongObject*)twice_rem);
4423 Py_DECREF(twice_rem);
4424 twice_rem = temp;
4425 if (twice_rem == NULL)
4426 goto error;
4427 }
4428 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4429 Py_DECREF(twice_rem);
4430
4431 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4432 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4433 /* fix up quotient */
4434 if (quo_is_neg)
4435 temp = long_sub(quo, (PyLongObject *)one);
4436 else
4437 temp = long_add(quo, (PyLongObject *)one);
4438 Py_DECREF(quo);
4439 quo = (PyLongObject *)temp;
4440 if (quo == NULL)
4441 goto error;
4442 /* and remainder */
4443 if (quo_is_neg)
4444 temp = long_add(rem, (PyLongObject *)b);
4445 else
4446 temp = long_sub(rem, (PyLongObject *)b);
4447 Py_DECREF(rem);
4448 rem = (PyLongObject *)temp;
4449 if (rem == NULL)
4450 goto error;
4451 }
4452
4453 result = PyTuple_New(2);
4454 if (result == NULL)
4455 goto error;
4456
4457 /* PyTuple_SET_ITEM steals references */
4458 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4459 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4460 Py_DECREF(one);
4461 return result;
4462
4463 error:
4464 Py_XDECREF(quo);
4465 Py_XDECREF(rem);
4466 Py_XDECREF(one);
4467 return NULL;
4468}
4469
Eric Smith8c663262007-08-25 02:26:07 +00004470static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004471long_round(PyObject *self, PyObject *args)
4472{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004473 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004474
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004475 /* To round an integer m to the nearest 10**n (n positive), we make use of
4476 * the divmod_near operation, defined by:
4477 *
4478 * divmod_near(a, b) = (q, r)
4479 *
4480 * where q is the nearest integer to the quotient a / b (the
4481 * nearest even integer in the case of a tie) and r == a - q * b.
4482 * Hence q * b = a - r is the nearest multiple of b to a,
4483 * preferring even multiples in the case of a tie.
4484 *
4485 * So the nearest multiple of 10**n to m is:
4486 *
4487 * m - divmod_near(m, 10**n)[1].
4488 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4490 return NULL;
4491 if (o_ndigits == NULL)
4492 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004493
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004494 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 if (ndigits == NULL)
4496 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004497
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004498 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 if (Py_SIZE(ndigits) >= 0) {
4500 Py_DECREF(ndigits);
4501 return long_long(self);
4502 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004503
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004504 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4505 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004507 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004509 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004510
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004511 result = PyLong_FromLong(10L);
4512 if (result == NULL) {
4513 Py_DECREF(ndigits);
4514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004516
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004517 temp = long_pow(result, ndigits, Py_None);
4518 Py_DECREF(ndigits);
4519 Py_DECREF(result);
4520 result = temp;
4521 if (result == NULL)
4522 return NULL;
4523
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004524 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004525 Py_DECREF(result);
4526 result = temp;
4527 if (result == NULL)
4528 return NULL;
4529
4530 temp = long_sub((PyLongObject *)self,
4531 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4532 Py_DECREF(result);
4533 result = temp;
4534
4535 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004536}
4537
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004538static PyObject *
4539long_sizeof(PyLongObject *v)
4540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4544 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004545}
4546
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004547static PyObject *
4548long_bit_length(PyLongObject *v)
4549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 PyLongObject *result, *x, *y;
4551 Py_ssize_t ndigits, msd_bits = 0;
4552 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 assert(v != NULL);
4555 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 ndigits = ABS(Py_SIZE(v));
4558 if (ndigits == 0)
4559 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 msd = v->ob_digit[ndigits-1];
4562 while (msd >= 32) {
4563 msd_bits += 6;
4564 msd >>= 6;
4565 }
4566 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4569 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 /* expression above may overflow; use Python integers instead */
4572 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4573 if (result == NULL)
4574 return NULL;
4575 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4576 if (x == NULL)
4577 goto error;
4578 y = (PyLongObject *)long_mul(result, x);
4579 Py_DECREF(x);
4580 if (y == NULL)
4581 goto error;
4582 Py_DECREF(result);
4583 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4586 if (x == NULL)
4587 goto error;
4588 y = (PyLongObject *)long_add(result, x);
4589 Py_DECREF(x);
4590 if (y == NULL)
4591 goto error;
4592 Py_DECREF(result);
4593 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004596
Mark Dickinson22b20182010-05-10 21:27:53 +00004597 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 Py_DECREF(result);
4599 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004600}
4601
4602PyDoc_STRVAR(long_bit_length_doc,
4603"int.bit_length() -> int\n\
4604\n\
4605Number of bits necessary to represent self in binary.\n\
4606>>> bin(37)\n\
4607'0b100101'\n\
4608>>> (37).bit_length()\n\
46096");
4610
Christian Heimes53876d92008-04-19 00:31:39 +00004611#if 0
4612static PyObject *
4613long_is_finite(PyObject *v)
4614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004616}
4617#endif
4618
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004619
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004620static PyObject *
4621long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 PyObject *byteorder_str;
4624 PyObject *is_signed_obj = NULL;
4625 Py_ssize_t length;
4626 int little_endian;
4627 int is_signed;
4628 PyObject *bytes;
4629 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4632 &length, &byteorder_str,
4633 &is_signed_obj))
4634 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 if (args != NULL && Py_SIZE(args) > 2) {
4637 PyErr_SetString(PyExc_TypeError,
4638 "'signed' is a keyword-only argument");
4639 return NULL;
4640 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4643 little_endian = 1;
4644 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4645 little_endian = 0;
4646 else {
4647 PyErr_SetString(PyExc_ValueError,
4648 "byteorder must be either 'little' or 'big'");
4649 return NULL;
4650 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (is_signed_obj != NULL) {
4653 int cmp = PyObject_IsTrue(is_signed_obj);
4654 if (cmp < 0)
4655 return NULL;
4656 is_signed = cmp ? 1 : 0;
4657 }
4658 else {
4659 /* If the signed argument was omitted, use False as the
4660 default. */
4661 is_signed = 0;
4662 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 if (length < 0) {
4665 PyErr_SetString(PyExc_ValueError,
4666 "length argument must be non-negative");
4667 return NULL;
4668 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 bytes = PyBytes_FromStringAndSize(NULL, length);
4671 if (bytes == NULL)
4672 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4675 length, little_endian, is_signed) < 0) {
4676 Py_DECREF(bytes);
4677 return NULL;
4678 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004681}
4682
Mark Dickinson078c2532010-01-30 18:06:17 +00004683PyDoc_STRVAR(long_to_bytes_doc,
4684"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004685\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004686Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004687\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004689raised if the integer is not representable with the given number of\n\
4690bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004691\n\
4692The byteorder argument determines the byte order used to represent the\n\
4693integer. If byteorder is 'big', the most significant byte is at the\n\
4694beginning of the byte array. If byteorder is 'little', the most\n\
4695significant byte is at the end of the byte array. To request the native\n\
4696byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4697\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004698The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004700is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004701
4702static PyObject *
4703long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 PyObject *byteorder_str;
4706 PyObject *is_signed_obj = NULL;
4707 int little_endian;
4708 int is_signed;
4709 PyObject *obj;
4710 PyObject *bytes;
4711 PyObject *long_obj;
4712 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4715 &obj, &byteorder_str,
4716 &is_signed_obj))
4717 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 if (args != NULL && Py_SIZE(args) > 2) {
4720 PyErr_SetString(PyExc_TypeError,
4721 "'signed' is a keyword-only argument");
4722 return NULL;
4723 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4726 little_endian = 1;
4727 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4728 little_endian = 0;
4729 else {
4730 PyErr_SetString(PyExc_ValueError,
4731 "byteorder must be either 'little' or 'big'");
4732 return NULL;
4733 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 if (is_signed_obj != NULL) {
4736 int cmp = PyObject_IsTrue(is_signed_obj);
4737 if (cmp < 0)
4738 return NULL;
4739 is_signed = cmp ? 1 : 0;
4740 }
4741 else {
4742 /* If the signed argument was omitted, use False as the
4743 default. */
4744 is_signed = 0;
4745 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 bytes = PyObject_Bytes(obj);
4748 if (bytes == NULL)
4749 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 long_obj = _PyLong_FromByteArray(
4752 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4753 little_endian, is_signed);
4754 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 /* If from_bytes() was used on subclass, allocate new subclass
4757 * instance, initialize it with decoded long value and return it.
4758 */
4759 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4760 PyLongObject *newobj;
4761 int i;
4762 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 newobj = (PyLongObject *)type->tp_alloc(type, n);
4765 if (newobj == NULL) {
4766 Py_DECREF(long_obj);
4767 return NULL;
4768 }
4769 assert(PyLong_Check(newobj));
4770 Py_SIZE(newobj) = Py_SIZE(long_obj);
4771 for (i = 0; i < n; i++) {
4772 newobj->ob_digit[i] =
4773 ((PyLongObject *)long_obj)->ob_digit[i];
4774 }
4775 Py_DECREF(long_obj);
4776 return (PyObject *)newobj;
4777 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004780}
4781
Mark Dickinson078c2532010-01-30 18:06:17 +00004782PyDoc_STRVAR(long_from_bytes_doc,
4783"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4784\n\
4785Return the integer represented by the given array of bytes.\n\
4786\n\
4787The bytes argument must either support the buffer protocol or be an\n\
4788iterable object producing bytes. Bytes and bytearray are examples of\n\
4789built-in objects that support the buffer protocol.\n\
4790\n\
4791The byteorder argument determines the byte order used to represent the\n\
4792integer. If byteorder is 'big', the most significant byte is at the\n\
4793beginning of the byte array. If byteorder is 'little', the most\n\
4794significant byte is at the end of the byte array. To request the native\n\
4795byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4796\n\
4797The signed keyword-only argument indicates whether two's complement is\n\
4798used to represent the integer.");
4799
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004800static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4802 "Returns self, the complex conjugate of any int."},
4803 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4804 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004805#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4807 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004808#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 {"to_bytes", (PyCFunction)long_to_bytes,
4810 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4811 {"from_bytes", (PyCFunction)long_from_bytes,
4812 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4813 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4814 "Truncating an Integral returns itself."},
4815 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4816 "Flooring an Integral returns itself."},
4817 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4818 "Ceiling of an Integral returns itself."},
4819 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4820 "Rounding an Integral returns itself.\n"
4821 "Rounding with an ndigits argument also returns an integer."},
4822 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4823 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4824 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4825 "Returns size in memory, in bytes"},
4826 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004827};
4828
Guido van Rossumb43daf72007-08-01 18:08:08 +00004829static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004830 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004831 (getter)long_long, (setter)NULL,
4832 "the real part of a complex number",
4833 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004834 {"imag",
4835 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004836 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004837 NULL},
4838 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004839 (getter)long_long, (setter)NULL,
4840 "the numerator of a rational number in lowest terms",
4841 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004842 {"denominator",
4843 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004844 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004845 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004846 {NULL} /* Sentinel */
4847};
4848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004849PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004850"int(x=0) -> integer\n\
4851int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004853Convert a number or string to an integer, or return 0 if no arguments\n\
4854are given. If x is a number, return x.__int__(). For floating point\n\
4855numbers, this truncates towards zero.\n\
4856\n\
4857If x is not a number or if base is given, then x must be a string,\n\
4858bytes, or bytearray instance representing an integer literal in the\n\
4859given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4860by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4861Base 0 means to interpret the base from the string as an integer literal.\n\
4862>>> int('0b100', base=0)\n\
48634");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004864
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004865static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004866 (binaryfunc)long_add, /*nb_add*/
4867 (binaryfunc)long_sub, /*nb_subtract*/
4868 (binaryfunc)long_mul, /*nb_multiply*/
4869 long_mod, /*nb_remainder*/
4870 long_divmod, /*nb_divmod*/
4871 long_pow, /*nb_power*/
4872 (unaryfunc)long_neg, /*nb_negative*/
4873 (unaryfunc)long_long, /*tp_positive*/
4874 (unaryfunc)long_abs, /*tp_absolute*/
4875 (inquiry)long_bool, /*tp_bool*/
4876 (unaryfunc)long_invert, /*nb_invert*/
4877 long_lshift, /*nb_lshift*/
4878 (binaryfunc)long_rshift, /*nb_rshift*/
4879 long_and, /*nb_and*/
4880 long_xor, /*nb_xor*/
4881 long_or, /*nb_or*/
4882 long_long, /*nb_int*/
4883 0, /*nb_reserved*/
4884 long_float, /*nb_float*/
4885 0, /* nb_inplace_add */
4886 0, /* nb_inplace_subtract */
4887 0, /* nb_inplace_multiply */
4888 0, /* nb_inplace_remainder */
4889 0, /* nb_inplace_power */
4890 0, /* nb_inplace_lshift */
4891 0, /* nb_inplace_rshift */
4892 0, /* nb_inplace_and */
4893 0, /* nb_inplace_xor */
4894 0, /* nb_inplace_or */
4895 long_div, /* nb_floor_divide */
4896 long_true_divide, /* nb_true_divide */
4897 0, /* nb_inplace_floor_divide */
4898 0, /* nb_inplace_true_divide */
4899 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004900};
4901
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004902PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4904 "int", /* tp_name */
4905 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4906 sizeof(digit), /* tp_itemsize */
4907 long_dealloc, /* tp_dealloc */
4908 0, /* tp_print */
4909 0, /* tp_getattr */
4910 0, /* tp_setattr */
4911 0, /* tp_reserved */
4912 long_to_decimal_string, /* tp_repr */
4913 &long_as_number, /* tp_as_number */
4914 0, /* tp_as_sequence */
4915 0, /* tp_as_mapping */
4916 (hashfunc)long_hash, /* tp_hash */
4917 0, /* tp_call */
4918 long_to_decimal_string, /* tp_str */
4919 PyObject_GenericGetAttr, /* tp_getattro */
4920 0, /* tp_setattro */
4921 0, /* tp_as_buffer */
4922 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4923 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4924 long_doc, /* tp_doc */
4925 0, /* tp_traverse */
4926 0, /* tp_clear */
4927 long_richcompare, /* tp_richcompare */
4928 0, /* tp_weaklistoffset */
4929 0, /* tp_iter */
4930 0, /* tp_iternext */
4931 long_methods, /* tp_methods */
4932 0, /* tp_members */
4933 long_getset, /* tp_getset */
4934 0, /* tp_base */
4935 0, /* tp_dict */
4936 0, /* tp_descr_get */
4937 0, /* tp_descr_set */
4938 0, /* tp_dictoffset */
4939 0, /* tp_init */
4940 0, /* tp_alloc */
4941 long_new, /* tp_new */
4942 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004943};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004944
Mark Dickinsonbd792642009-03-18 20:06:12 +00004945static PyTypeObject Int_InfoType;
4946
4947PyDoc_STRVAR(int_info__doc__,
4948"sys.int_info\n\
4949\n\
4950A struct sequence that holds information about Python's\n\
4951internal representation of integers. The attributes are read only.");
4952
4953static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004955 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004957};
4958
4959static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 "sys.int_info", /* name */
4961 int_info__doc__, /* doc */
4962 int_info_fields, /* fields */
4963 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004964};
4965
4966PyObject *
4967PyLong_GetInfo(void)
4968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 PyObject* int_info;
4970 int field = 0;
4971 int_info = PyStructSequence_New(&Int_InfoType);
4972 if (int_info == NULL)
4973 return NULL;
4974 PyStructSequence_SET_ITEM(int_info, field++,
4975 PyLong_FromLong(PyLong_SHIFT));
4976 PyStructSequence_SET_ITEM(int_info, field++,
4977 PyLong_FromLong(sizeof(digit)));
4978 if (PyErr_Occurred()) {
4979 Py_CLEAR(int_info);
4980 return NULL;
4981 }
4982 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004983}
4984
Guido van Rossumddefaf32007-01-14 03:31:43 +00004985int
4986_PyLong_Init(void)
4987{
4988#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 int ival, size;
4990 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4993 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4994 if (Py_TYPE(v) == &PyLong_Type) {
4995 /* The element is already initialized, most likely
4996 * the Python interpreter was initialized before.
4997 */
4998 Py_ssize_t refcnt;
4999 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5002 _Py_NewReference(op);
5003 /* _Py_NewReference sets the ref count to 1 but
5004 * the ref count might be larger. Set the refcnt
5005 * to the original refcnt + 1 */
5006 Py_REFCNT(op) = refcnt + 1;
5007 assert(Py_SIZE(op) == size);
5008 assert(v->ob_digit[0] == abs(ival));
5009 }
5010 else {
5011 PyObject_INIT(v, &PyLong_Type);
5012 }
5013 Py_SIZE(v) = size;
5014 v->ob_digit[0] = abs(ival);
5015 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005016#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 /* initialize int_info */
5018 if (Int_InfoType.tp_name == 0)
5019 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005022}
5023
5024void
5025PyLong_Fini(void)
5026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 /* Integers are currently statically allocated. Py_DECREF is not
5028 needed, but Python must forget about the reference or multiple
5029 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005030#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 int i;
5032 PyLongObject *v = small_ints;
5033 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5034 _Py_DEC_REFTOTAL;
5035 _Py_ForgetReference((PyObject*)v);
5036 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005037#endif
5038}