blob: 4cc080f2b5da5676729f993c427febe400f674d5 [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 \
1653 *p = '\0'; \
1654 /* pout[0] through pout[size-2] contribute exactly \
1655 _PyLong_DECIMAL_SHIFT digits each */ \
1656 for (i=0; i < size - 1; i++) { \
1657 rem = pout[i]; \
1658 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1659 *--p = '0' + rem % 10; \
1660 rem /= 10; \
1661 } \
1662 } \
1663 /* pout[size-1]: always produce at least one decimal digit */ \
1664 rem = pout[i]; \
1665 do { \
1666 *--p = '0' + rem % 10; \
1667 rem /= 10; \
1668 } while (rem != 0); \
1669 \
1670 /* and sign */ \
1671 if (negative) \
1672 *--p = '-'; \
1673 \
1674 /* check we've counted correctly */ \
1675 if (writer) \
1676 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1677 else \
1678 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1679 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001682 if (kind == PyUnicode_1BYTE_KIND) {
1683 Py_UCS1 *p;
1684 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001686 else if (kind == PyUnicode_2BYTE_KIND) {
1687 Py_UCS2 *p;
1688 WRITE_DIGITS(Py_UCS2);
1689 }
1690 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001691 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001692 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001693 WRITE_DIGITS(Py_UCS4);
1694 }
1695#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001698 if (writer) {
1699 writer->pos += strlen;
1700 }
1701 else {
1702 assert(_PyUnicode_CheckConsistency(str, 1));
1703 *p_output = (PyObject *)str;
1704 }
1705 return 0;
1706}
1707
1708static PyObject *
1709long_to_decimal_string(PyObject *aa)
1710{
1711 PyObject *v;
1712 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1713 return NULL;
1714 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001715}
1716
Mark Dickinsoncd068122009-09-18 14:53:08 +00001717/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001718 which should be one of 2, 8 or 16. Return a string object.
1719 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1720 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001721
Victor Stinnerd3f08822012-05-29 12:57:52 +02001722static int
1723long_format_binary(PyObject *aa, int base, int alternate,
1724 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001727 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001728 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001730 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001731 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001733
Victor Stinnerd3f08822012-05-29 12:57:52 +02001734 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (a == NULL || !PyLong_Check(a)) {
1736 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001737 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 }
1739 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001740 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* Compute a rough upper bound for the length of the string */
1743 switch (base) {
1744 case 16:
1745 bits = 4;
1746 break;
1747 case 8:
1748 bits = 3;
1749 break;
1750 case 2:
1751 bits = 1;
1752 break;
1753 default:
1754 assert(0); /* shouldn't ever get here */
1755 bits = 0; /* to silence gcc warning */
1756 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001757
Mark Dickinsone2846542012-04-20 21:21:24 +01001758 /* Compute exact length 'sz' of output string. */
1759 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 }
1762 else {
1763 Py_ssize_t size_a_in_bits;
1764 /* Ensure overflow doesn't occur during computation of sz. */
1765 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1766 PyErr_SetString(PyExc_OverflowError,
1767 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001768 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001769 }
1770 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1771 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001772 /* Allow 1 character for a '-' sign. */
1773 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1774 }
1775 if (alternate) {
1776 /* 2 characters for prefix */
1777 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001778 }
1779
Victor Stinnerd3f08822012-05-29 12:57:52 +02001780 if (writer) {
1781 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1782 return -1;
1783 kind = writer->kind;
1784 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 }
1786 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001787 v = PyUnicode_New(sz, 'x');
1788 if (v == NULL)
1789 return -1;
1790 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001792
Victor Stinnerd3f08822012-05-29 12:57:52 +02001793#define WRITE_DIGITS(TYPE) \
1794 do { \
1795 if (writer) \
1796 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1797 else \
1798 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1799 \
1800 if (size_a == 0) { \
1801 *--p = '0'; \
1802 } \
1803 else { \
1804 /* JRH: special case for power-of-2 bases */ \
1805 twodigits accum = 0; \
1806 int accumbits = 0; /* # of bits in accum */ \
1807 Py_ssize_t i; \
1808 for (i = 0; i < size_a; ++i) { \
1809 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1810 accumbits += PyLong_SHIFT; \
1811 assert(accumbits >= bits); \
1812 do { \
1813 char cdigit; \
1814 cdigit = (char)(accum & (base - 1)); \
1815 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1816 *--p = cdigit; \
1817 accumbits -= bits; \
1818 accum >>= bits; \
1819 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1820 } \
1821 } \
1822 \
1823 if (alternate) { \
1824 if (base == 16) \
1825 *--p = 'x'; \
1826 else if (base == 8) \
1827 *--p = 'o'; \
1828 else /* (base == 2) */ \
1829 *--p = 'b'; \
1830 *--p = '0'; \
1831 } \
1832 if (negative) \
1833 *--p = '-'; \
1834 if (writer) \
1835 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1836 else \
1837 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1838 } while (0)
1839
1840 if (kind == PyUnicode_1BYTE_KIND) {
1841 Py_UCS1 *p;
1842 WRITE_DIGITS(Py_UCS1);
1843 }
1844 else if (kind == PyUnicode_2BYTE_KIND) {
1845 Py_UCS2 *p;
1846 WRITE_DIGITS(Py_UCS2);
1847 }
1848 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001849 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001850 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001851 WRITE_DIGITS(Py_UCS4);
1852 }
1853#undef WRITE_DIGITS
1854
1855 if (writer) {
1856 writer->pos += sz;
1857 }
1858 else {
1859 assert(_PyUnicode_CheckConsistency(v, 1));
1860 *p_output = v;
1861 }
1862 return 0;
1863}
1864
1865PyObject *
1866_PyLong_Format(PyObject *obj, int base)
1867{
1868 PyObject *str;
1869 int err;
1870 if (base == 10)
1871 err = long_to_decimal_string_internal(obj, &str, NULL);
1872 else
1873 err = long_format_binary(obj, base, 1, &str, NULL);
1874 if (err == -1)
1875 return NULL;
1876 return str;
1877}
1878
1879int
1880_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1881 PyObject *obj,
1882 int base, int alternate)
1883{
1884 if (base == 10)
1885 return long_to_decimal_string_internal(obj, NULL, writer);
1886 else
1887 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001888}
1889
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890/* Table of digit values for 8-bit string -> integer conversion.
1891 * '0' maps to 0, ..., '9' maps to 9.
1892 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1893 * All other indices map to 37.
1894 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001895 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001897unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1901 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1902 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1903 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1904 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1905 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
1913 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914};
1915
1916/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001917 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1918 * non-digit (which may be *str!). A normalized long is returned.
1919 * The point to this routine is that it takes time linear in the number of
1920 * string characters.
1921 */
1922static PyLongObject *
1923long_from_binary_base(char **str, int base)
1924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 char *p = *str;
1926 char *start = p;
1927 int bits_per_char;
1928 Py_ssize_t n;
1929 PyLongObject *z;
1930 twodigits accum;
1931 int bits_in_accum;
1932 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1935 n = base;
1936 for (bits_per_char = -1; n; ++bits_per_char)
1937 n >>= 1;
1938 /* n <- total # of bits needed, while setting p to end-of-string */
1939 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1940 ++p;
1941 *str = p;
1942 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1943 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1944 if (n / bits_per_char < p - start) {
1945 PyErr_SetString(PyExc_ValueError,
1946 "int string too large to convert");
1947 return NULL;
1948 }
1949 n = n / PyLong_SHIFT;
1950 z = _PyLong_New(n);
1951 if (z == NULL)
1952 return NULL;
1953 /* Read string from right, and fill in long from left; i.e.,
1954 * from least to most significant in both.
1955 */
1956 accum = 0;
1957 bits_in_accum = 0;
1958 pdigit = z->ob_digit;
1959 while (--p >= start) {
1960 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1961 assert(k >= 0 && k < base);
1962 accum |= (twodigits)k << bits_in_accum;
1963 bits_in_accum += bits_per_char;
1964 if (bits_in_accum >= PyLong_SHIFT) {
1965 *pdigit++ = (digit)(accum & PyLong_MASK);
1966 assert(pdigit - z->ob_digit <= n);
1967 accum >>= PyLong_SHIFT;
1968 bits_in_accum -= PyLong_SHIFT;
1969 assert(bits_in_accum < PyLong_SHIFT);
1970 }
1971 }
1972 if (bits_in_accum) {
1973 assert(bits_in_accum <= PyLong_SHIFT);
1974 *pdigit++ = (digit)accum;
1975 assert(pdigit - z->ob_digit <= n);
1976 }
1977 while (pdigit - z->ob_digit < n)
1978 *pdigit++ = 0;
1979 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001980}
1981
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001982PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001983PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 int sign = 1, error_if_nonzero = 0;
1986 char *start, *orig_str = str;
1987 PyLongObject *z = NULL;
1988 PyObject *strobj;
1989 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if ((base != 0 && base < 2) || base > 36) {
1992 PyErr_SetString(PyExc_ValueError,
1993 "int() arg 2 must be >= 2 and <= 36");
1994 return NULL;
1995 }
1996 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1997 str++;
1998 if (*str == '+')
1999 ++str;
2000 else if (*str == '-') {
2001 ++str;
2002 sign = -1;
2003 }
2004 if (base == 0) {
2005 if (str[0] != '0')
2006 base = 10;
2007 else if (str[1] == 'x' || str[1] == 'X')
2008 base = 16;
2009 else if (str[1] == 'o' || str[1] == 'O')
2010 base = 8;
2011 else if (str[1] == 'b' || str[1] == 'B')
2012 base = 2;
2013 else {
2014 /* "old" (C-style) octal literal, now invalid.
2015 it might still be zero though */
2016 error_if_nonzero = 1;
2017 base = 10;
2018 }
2019 }
2020 if (str[0] == '0' &&
2021 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2022 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2023 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2024 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 start = str;
2027 if ((base & (base - 1)) == 0)
2028 z = long_from_binary_base(&str, base);
2029 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002030/***
2031Binary bases can be converted in time linear in the number of digits, because
2032Python's representation base is binary. Other bases (including decimal!) use
2033the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002034
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035First some math: the largest integer that can be expressed in N base-B digits
2036is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2037case number of Python digits needed to hold it is the smallest integer n s.t.
2038
2039 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2040 BASE**n >= B**N [taking logs to base BASE]
2041 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2042
2043The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2044this quickly. A Python long with that much space is reserved near the start,
2045and the result is computed into it.
2046
2047The input string is actually treated as being in base base**i (i.e., i digits
2048are processed at a time), where two more static arrays hold:
2049
2050 convwidth_base[base] = the largest integer i such that base**i <= BASE
2051 convmultmax_base[base] = base ** convwidth_base[base]
2052
2053The first of these is the largest i such that i consecutive input digits
2054must fit in a single Python digit. The second is effectively the input
2055base we're really using.
2056
2057Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2058convmultmax_base[base], the result is "simply"
2059
2060 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2061
2062where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002063
2064Error analysis: as above, the number of Python digits `n` needed is worst-
2065case
2066
2067 n >= N * log(B)/log(BASE)
2068
2069where `N` is the number of input digits in base `B`. This is computed via
2070
2071 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2072
2073below. Two numeric concerns are how much space this can waste, and whether
2074the computed result can be too small. To be concrete, assume BASE = 2**15,
2075which is the default (and it's unlikely anyone changes that).
2076
2077Waste isn't a problem: provided the first input digit isn't 0, the difference
2078between the worst-case input with N digits and the smallest input with N
2079digits is about a factor of B, but B is small compared to BASE so at most
2080one allocated Python digit can remain unused on that count. If
2081N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2082and adding 1 returns a result 1 larger than necessary. However, that can't
2083happen: whenever B is a power of 2, long_from_binary_base() is called
2084instead, and it's impossible for B**i to be an integer power of 2**15 when
2085B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2086an exact integer when B is not a power of 2, since B**i has a prime factor
2087other than 2 in that case, but (2**15)**j's only prime factor is 2).
2088
2089The computed result can be too small if the true value of N*log(B)/log(BASE)
2090is a little bit larger than an exact integer, but due to roundoff errors (in
2091computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2092yields a numeric result a little less than that integer. Unfortunately, "how
2093close can a transcendental function get to an integer over some range?"
2094questions are generally theoretically intractable. Computer analysis via
2095continued fractions is practical: expand log(B)/log(BASE) via continued
2096fractions, giving a sequence i/j of "the best" rational approximations. Then
2097j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2098we can get very close to being in trouble, but very rarely. For example,
209976573 is a denominator in one of the continued-fraction approximations to
2100log(10)/log(2**15), and indeed:
2101
2102 >>> log(10)/log(2**15)*76573
2103 16958.000000654003
2104
2105is very close to an integer. If we were working with IEEE single-precision,
2106rounding errors could kill us. Finding worst cases in IEEE double-precision
2107requires better-than-double-precision log() functions, and Tim didn't bother.
2108Instead the code checks to see whether the allocated space is enough as each
2109new Python digit is added, and copies the whole thing to a larger long if not.
2110This should happen extremely rarely, and in fact I don't have a test case
2111that triggers it(!). Instead the code was tested by artificially allocating
2112just 1 digit at the start, so that the copying code was exercised for every
2113digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002114***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 register twodigits c; /* current input character */
2116 Py_ssize_t size_z;
2117 int i;
2118 int convwidth;
2119 twodigits convmultmax, convmult;
2120 digit *pz, *pzstop;
2121 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 static double log_base_BASE[37] = {0.0e0,};
2124 static int convwidth_base[37] = {0,};
2125 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (log_base_BASE[base] == 0.0) {
2128 twodigits convmax = base;
2129 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130
Mark Dickinson22b20182010-05-10 21:27:53 +00002131 log_base_BASE[base] = (log((double)base) /
2132 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 for (;;) {
2134 twodigits next = convmax * base;
2135 if (next > PyLong_BASE)
2136 break;
2137 convmax = next;
2138 ++i;
2139 }
2140 convmultmax_base[base] = convmax;
2141 assert(i > 0);
2142 convwidth_base[base] = i;
2143 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* Find length of the string of numeric characters. */
2146 scan = str;
2147 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2148 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 /* Create a long object that can contain the largest possible
2151 * integer with this base and length. Note that there's no
2152 * need to initialize z->ob_digit -- no slot is read up before
2153 * being stored into.
2154 */
2155 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2156 /* Uncomment next line to test exceedingly rare copy code */
2157 /* size_z = 1; */
2158 assert(size_z > 0);
2159 z = _PyLong_New(size_z);
2160 if (z == NULL)
2161 return NULL;
2162 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* `convwidth` consecutive input digits are treated as a single
2165 * digit in base `convmultmax`.
2166 */
2167 convwidth = convwidth_base[base];
2168 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* Work ;-) */
2171 while (str < scan) {
2172 /* grab up to convwidth digits from the input string */
2173 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2174 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2175 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002176 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 assert(c < PyLong_BASE);
2178 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 convmult = convmultmax;
2181 /* Calculate the shift only if we couldn't get
2182 * convwidth digits.
2183 */
2184 if (i != convwidth) {
2185 convmult = base;
2186 for ( ; i > 1; --i)
2187 convmult *= base;
2188 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* Multiply z by convmult, and add c. */
2191 pz = z->ob_digit;
2192 pzstop = pz + Py_SIZE(z);
2193 for (; pz < pzstop; ++pz) {
2194 c += (twodigits)*pz * convmult;
2195 *pz = (digit)(c & PyLong_MASK);
2196 c >>= PyLong_SHIFT;
2197 }
2198 /* carry off the current end? */
2199 if (c) {
2200 assert(c < PyLong_BASE);
2201 if (Py_SIZE(z) < size_z) {
2202 *pz = (digit)c;
2203 ++Py_SIZE(z);
2204 }
2205 else {
2206 PyLongObject *tmp;
2207 /* Extremely rare. Get more space. */
2208 assert(Py_SIZE(z) == size_z);
2209 tmp = _PyLong_New(size_z + 1);
2210 if (tmp == NULL) {
2211 Py_DECREF(z);
2212 return NULL;
2213 }
2214 memcpy(tmp->ob_digit,
2215 z->ob_digit,
2216 sizeof(digit) * size_z);
2217 Py_DECREF(z);
2218 z = tmp;
2219 z->ob_digit[size_z] = (digit)c;
2220 ++size_z;
2221 }
2222 }
2223 }
2224 }
2225 if (z == NULL)
2226 return NULL;
2227 if (error_if_nonzero) {
2228 /* reset the base to 0, else the exception message
2229 doesn't make too much sense */
2230 base = 0;
2231 if (Py_SIZE(z) != 0)
2232 goto onError;
2233 /* there might still be other problems, therefore base
2234 remains zero here for the same reason */
2235 }
2236 if (str == start)
2237 goto onError;
2238 if (sign < 0)
2239 Py_SIZE(z) = -(Py_SIZE(z));
2240 while (*str && isspace(Py_CHARMASK(*str)))
2241 str++;
2242 if (*str != '\0')
2243 goto onError;
2244 if (pend)
2245 *pend = str;
2246 long_normalize(z);
2247 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002248
Mark Dickinson22b20182010-05-10 21:27:53 +00002249 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 Py_XDECREF(z);
2251 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2252 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2253 if (strobj == NULL)
2254 return NULL;
2255 PyErr_Format(PyExc_ValueError,
2256 "invalid literal for int() with base %d: %R",
2257 base, strobj);
2258 Py_DECREF(strobj);
2259 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002260}
2261
2262PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002263PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2266 if (unicode == NULL)
2267 return NULL;
2268 v = PyLong_FromUnicodeObject(unicode, base);
2269 Py_DECREF(unicode);
2270 return v;
2271}
2272
2273PyObject *
2274PyLong_FromUnicodeObject(PyObject *u, int base)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002277 PyObject *asciidig;
2278 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002279 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002282 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002284 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002285 if (buffer == NULL) {
2286 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 return NULL;
2288 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002289 result = PyLong_FromString(buffer, &end, base);
2290 if (result != NULL && end != buffer + buflen) {
2291 PyErr_SetString(PyExc_ValueError,
2292 "null byte in argument for int()");
2293 Py_DECREF(result);
2294 result = NULL;
2295 }
2296 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002298}
2299
Tim Peters9f688bf2000-07-07 15:53:28 +00002300/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002301static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002303static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002304
2305/* Long division with remainder, top-level routine */
2306
Guido van Rossume32e0141992-01-19 16:31:05 +00002307static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002308long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2312 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if (size_b == 0) {
2315 PyErr_SetString(PyExc_ZeroDivisionError,
2316 "integer division or modulo by zero");
2317 return -1;
2318 }
2319 if (size_a < size_b ||
2320 (size_a == size_b &&
2321 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2322 /* |a| < |b|. */
2323 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2324 if (*pdiv == NULL)
2325 return -1;
2326 Py_INCREF(a);
2327 *prem = (PyLongObject *) a;
2328 return 0;
2329 }
2330 if (size_b == 1) {
2331 digit rem = 0;
2332 z = divrem1(a, b->ob_digit[0], &rem);
2333 if (z == NULL)
2334 return -1;
2335 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2336 if (*prem == NULL) {
2337 Py_DECREF(z);
2338 return -1;
2339 }
2340 }
2341 else {
2342 z = x_divrem(a, b, prem);
2343 if (z == NULL)
2344 return -1;
2345 }
2346 /* Set the signs.
2347 The quotient z has the sign of a*b;
2348 the remainder r has the sign of a,
2349 so a = b*z + r. */
2350 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2351 NEGATE(z);
2352 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2353 NEGATE(*prem);
2354 *pdiv = maybe_small_long(z);
2355 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002356}
2357
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002358/* Unsigned long division with remainder -- the algorithm. The arguments v1
2359 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002362x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 PyLongObject *v, *w, *a;
2365 Py_ssize_t i, k, size_v, size_w;
2366 int d;
2367 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2368 twodigits vv;
2369 sdigit zhi;
2370 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2373 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2374 handle the special case when the initial estimate q for a quotient
2375 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2376 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* allocate space; w will also be used to hold the final remainder */
2379 size_v = ABS(Py_SIZE(v1));
2380 size_w = ABS(Py_SIZE(w1));
2381 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2382 v = _PyLong_New(size_v+1);
2383 if (v == NULL) {
2384 *prem = NULL;
2385 return NULL;
2386 }
2387 w = _PyLong_New(size_w);
2388 if (w == NULL) {
2389 Py_DECREF(v);
2390 *prem = NULL;
2391 return NULL;
2392 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2395 shift v1 left by the same amount. Results go into w and v. */
2396 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2397 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2398 assert(carry == 0);
2399 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2400 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2401 v->ob_digit[size_v] = carry;
2402 size_v++;
2403 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2406 at most (and usually exactly) k = size_v - size_w digits. */
2407 k = size_v - size_w;
2408 assert(k >= 0);
2409 a = _PyLong_New(k);
2410 if (a == NULL) {
2411 Py_DECREF(w);
2412 Py_DECREF(v);
2413 *prem = NULL;
2414 return NULL;
2415 }
2416 v0 = v->ob_digit;
2417 w0 = w->ob_digit;
2418 wm1 = w0[size_w-1];
2419 wm2 = w0[size_w-2];
2420 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2421 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2422 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002425 Py_DECREF(a);
2426 Py_DECREF(w);
2427 Py_DECREF(v);
2428 *prem = NULL;
2429 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002430 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* estimate quotient digit q; may overestimate by 1 (rare) */
2433 vtop = vk[size_w];
2434 assert(vtop <= wm1);
2435 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2436 q = (digit)(vv / wm1);
2437 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2438 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2439 | vk[size_w-2])) {
2440 --q;
2441 r += wm1;
2442 if (r >= PyLong_BASE)
2443 break;
2444 }
2445 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2448 zhi = 0;
2449 for (i = 0; i < size_w; ++i) {
2450 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2451 -PyLong_BASE * q <= z < PyLong_BASE */
2452 z = (sdigit)vk[i] + zhi -
2453 (stwodigits)q * (stwodigits)w0[i];
2454 vk[i] = (digit)z & PyLong_MASK;
2455 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002456 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* add w back if q was too large (this branch taken rarely) */
2460 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2461 if ((sdigit)vtop + zhi < 0) {
2462 carry = 0;
2463 for (i = 0; i < size_w; ++i) {
2464 carry += vk[i] + w0[i];
2465 vk[i] = carry & PyLong_MASK;
2466 carry >>= PyLong_SHIFT;
2467 }
2468 --q;
2469 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 /* store quotient digit */
2472 assert(q < PyLong_BASE);
2473 *--ak = q;
2474 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* unshift remainder; we reuse w to store the result */
2477 carry = v_rshift(w0, v0, size_w, d);
2478 assert(carry==0);
2479 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 *prem = long_normalize(w);
2482 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002483}
2484
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002485/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2486 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2487 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2488 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2489 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2490 -1.0. */
2491
2492/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2493#if DBL_MANT_DIG == 53
2494#define EXP2_DBL_MANT_DIG 9007199254740992.0
2495#else
2496#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2497#endif
2498
2499double
2500_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2503 /* See below for why x_digits is always large enough. */
2504 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2505 double dx;
2506 /* Correction term for round-half-to-even rounding. For a digit x,
2507 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2508 multiple of 4, rounding ties to a multiple of 8. */
2509 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 a_size = ABS(Py_SIZE(a));
2512 if (a_size == 0) {
2513 /* Special case for 0: significand 0.0, exponent 0. */
2514 *e = 0;
2515 return 0.0;
2516 }
2517 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2518 /* The following is an overflow-free version of the check
2519 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2520 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2521 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2522 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002523 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2527 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 Number of digits needed for result: write // for floor division.
2530 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2539 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2542 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2543 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 in both cases.
2550 */
2551 if (a_bits <= DBL_MANT_DIG + 2) {
2552 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2553 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2554 x_size = 0;
2555 while (x_size < shift_digits)
2556 x_digits[x_size++] = 0;
2557 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2558 (int)shift_bits);
2559 x_size += a_size;
2560 x_digits[x_size++] = rem;
2561 }
2562 else {
2563 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2564 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2565 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2566 a_size - shift_digits, (int)shift_bits);
2567 x_size = a_size - shift_digits;
2568 /* For correct rounding below, we need the least significant
2569 bit of x to be 'sticky' for this shift: if any of the bits
2570 shifted out was nonzero, we set the least significant bit
2571 of x. */
2572 if (rem)
2573 x_digits[0] |= 1;
2574 else
2575 while (shift_digits > 0)
2576 if (a->ob_digit[--shift_digits]) {
2577 x_digits[0] |= 1;
2578 break;
2579 }
2580 }
Victor Stinner63941882011-09-29 00:42:28 +02002581 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 /* Round, and convert to double. */
2584 x_digits[0] += half_even_correction[x_digits[0] & 7];
2585 dx = x_digits[--x_size];
2586 while (x_size > 0)
2587 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* Rescale; make correction if result is 1.0. */
2590 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2591 if (dx == 1.0) {
2592 if (a_bits == PY_SSIZE_T_MAX)
2593 goto overflow;
2594 dx = 0.5;
2595 a_bits += 1;
2596 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 *e = a_bits;
2599 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002600
2601 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* exponent > PY_SSIZE_T_MAX */
2603 PyErr_SetString(PyExc_OverflowError,
2604 "huge integer: number of bits overflows a Py_ssize_t");
2605 *e = 0;
2606 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607}
2608
2609/* Get a C double from a long int object. Rounds to the nearest double,
2610 using the round-half-to-even rule in the case of a tie. */
2611
2612double
2613PyLong_AsDouble(PyObject *v)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 Py_ssize_t exponent;
2616 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002617
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002618 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyErr_BadInternalCall();
2620 return -1.0;
2621 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002622 if (!PyLong_Check(v)) {
2623 PyErr_SetString(PyExc_TypeError, "an integer is required");
2624 return -1.0;
2625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2627 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2628 PyErr_SetString(PyExc_OverflowError,
2629 "long int too large to convert to float");
2630 return -1.0;
2631 }
2632 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002633}
2634
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002635/* Methods */
2636
2637static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002638long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002641}
2642
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002644long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 if (Py_SIZE(a) != Py_SIZE(b)) {
2649 sign = Py_SIZE(a) - Py_SIZE(b);
2650 }
2651 else {
2652 Py_ssize_t i = ABS(Py_SIZE(a));
2653 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2654 ;
2655 if (i < 0)
2656 sign = 0;
2657 else {
2658 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2659 if (Py_SIZE(a) < 0)
2660 sign = -sign;
2661 }
2662 }
2663 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002664}
2665
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002666#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002668
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002669static PyObject *
2670long_richcompare(PyObject *self, PyObject *other, int op)
2671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 int result;
2673 PyObject *v;
2674 CHECK_BINOP(self, other);
2675 if (self == other)
2676 result = 0;
2677 else
2678 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2679 /* Convert the return value to a Boolean */
2680 switch (op) {
2681 case Py_EQ:
2682 v = TEST_COND(result == 0);
2683 break;
2684 case Py_NE:
2685 v = TEST_COND(result != 0);
2686 break;
2687 case Py_LE:
2688 v = TEST_COND(result <= 0);
2689 break;
2690 case Py_GE:
2691 v = TEST_COND(result >= 0);
2692 break;
2693 case Py_LT:
2694 v = TEST_COND(result == -1);
2695 break;
2696 case Py_GT:
2697 v = TEST_COND(result == 1);
2698 break;
2699 default:
2700 PyErr_BadArgument();
2701 return NULL;
2702 }
2703 Py_INCREF(v);
2704 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002705}
2706
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002707static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002708long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002709{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002710 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 Py_ssize_t i;
2712 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 i = Py_SIZE(v);
2715 switch(i) {
2716 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2717 case 0: return 0;
2718 case 1: return v->ob_digit[0];
2719 }
2720 sign = 1;
2721 x = 0;
2722 if (i < 0) {
2723 sign = -1;
2724 i = -(i);
2725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002727 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2728 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2729 _PyHASH_MODULUS.
2730
2731 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2732 amounts to a rotation of the bits of x. To see this, write
2733
2734 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2735
2736 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2737 PyLong_SHIFT bits of x (those that are shifted out of the
2738 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2739 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2740 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2741 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2742 congruent to y modulo _PyHASH_MODULUS. So
2743
2744 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2745
2746 The right-hand side is just the result of rotating the
2747 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2748 not all _PyHASH_BITS bits of x are 1s, the same is true
2749 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2750 the reduction of x*2**PyLong_SHIFT modulo
2751 _PyHASH_MODULUS. */
2752 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2753 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002755 if (x >= _PyHASH_MODULUS)
2756 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 }
2758 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002759 if (x == (Py_uhash_t)-1)
2760 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002761 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002762}
2763
2764
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002765/* Add the absolute values of two long integers. */
2766
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002767static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002768x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2771 PyLongObject *z;
2772 Py_ssize_t i;
2773 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* Ensure a is the larger of the two: */
2776 if (size_a < size_b) {
2777 { PyLongObject *temp = a; a = b; b = temp; }
2778 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002779 size_a = size_b;
2780 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 }
2782 z = _PyLong_New(size_a+1);
2783 if (z == NULL)
2784 return NULL;
2785 for (i = 0; i < size_b; ++i) {
2786 carry += a->ob_digit[i] + b->ob_digit[i];
2787 z->ob_digit[i] = carry & PyLong_MASK;
2788 carry >>= PyLong_SHIFT;
2789 }
2790 for (; i < size_a; ++i) {
2791 carry += a->ob_digit[i];
2792 z->ob_digit[i] = carry & PyLong_MASK;
2793 carry >>= PyLong_SHIFT;
2794 }
2795 z->ob_digit[i] = carry;
2796 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002797}
2798
2799/* Subtract the absolute values of two integers. */
2800
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002801static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002802x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2805 PyLongObject *z;
2806 Py_ssize_t i;
2807 int sign = 1;
2808 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 /* Ensure a is the larger of the two: */
2811 if (size_a < size_b) {
2812 sign = -1;
2813 { PyLongObject *temp = a; a = b; b = temp; }
2814 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002815 size_a = size_b;
2816 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 }
2818 else if (size_a == size_b) {
2819 /* Find highest digit where a and b differ: */
2820 i = size_a;
2821 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2822 ;
2823 if (i < 0)
2824 return (PyLongObject *)PyLong_FromLong(0);
2825 if (a->ob_digit[i] < b->ob_digit[i]) {
2826 sign = -1;
2827 { PyLongObject *temp = a; a = b; b = temp; }
2828 }
2829 size_a = size_b = i+1;
2830 }
2831 z = _PyLong_New(size_a);
2832 if (z == NULL)
2833 return NULL;
2834 for (i = 0; i < size_b; ++i) {
2835 /* The following assumes unsigned arithmetic
2836 works module 2**N for some N>PyLong_SHIFT. */
2837 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2838 z->ob_digit[i] = borrow & PyLong_MASK;
2839 borrow >>= PyLong_SHIFT;
2840 borrow &= 1; /* Keep only one sign bit */
2841 }
2842 for (; i < size_a; ++i) {
2843 borrow = a->ob_digit[i] - borrow;
2844 z->ob_digit[i] = borrow & PyLong_MASK;
2845 borrow >>= PyLong_SHIFT;
2846 borrow &= 1; /* Keep only one sign bit */
2847 }
2848 assert(borrow == 0);
2849 if (sign < 0)
2850 NEGATE(z);
2851 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002852}
2853
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002854static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002855long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2862 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2863 MEDIUM_VALUE(b));
2864 return result;
2865 }
2866 if (Py_SIZE(a) < 0) {
2867 if (Py_SIZE(b) < 0) {
2868 z = x_add(a, b);
2869 if (z != NULL && Py_SIZE(z) != 0)
2870 Py_SIZE(z) = -(Py_SIZE(z));
2871 }
2872 else
2873 z = x_sub(b, a);
2874 }
2875 else {
2876 if (Py_SIZE(b) < 0)
2877 z = x_sub(a, b);
2878 else
2879 z = x_add(a, b);
2880 }
2881 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002882}
2883
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002884static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002885long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2892 PyObject* r;
2893 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2894 return r;
2895 }
2896 if (Py_SIZE(a) < 0) {
2897 if (Py_SIZE(b) < 0)
2898 z = x_sub(a, b);
2899 else
2900 z = x_add(a, b);
2901 if (z != NULL && Py_SIZE(z) != 0)
2902 Py_SIZE(z) = -(Py_SIZE(z));
2903 }
2904 else {
2905 if (Py_SIZE(b) < 0)
2906 z = x_add(a, b);
2907 else
2908 z = x_sub(a, b);
2909 }
2910 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002911}
2912
Tim Peters5af4e6c2002-08-12 02:31:19 +00002913/* Grade school multiplication, ignoring the signs.
2914 * Returns the absolute value of the product, or NULL if error.
2915 */
2916static PyLongObject *
2917x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 PyLongObject *z;
2920 Py_ssize_t size_a = ABS(Py_SIZE(a));
2921 Py_ssize_t size_b = ABS(Py_SIZE(b));
2922 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 z = _PyLong_New(size_a + size_b);
2925 if (z == NULL)
2926 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2929 if (a == b) {
2930 /* Efficient squaring per HAC, Algorithm 14.16:
2931 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2932 * Gives slightly less than a 2x speedup when a == b,
2933 * via exploiting that each entry in the multiplication
2934 * pyramid appears twice (except for the size_a squares).
2935 */
2936 for (i = 0; i < size_a; ++i) {
2937 twodigits carry;
2938 twodigits f = a->ob_digit[i];
2939 digit *pz = z->ob_digit + (i << 1);
2940 digit *pa = a->ob_digit + i + 1;
2941 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002944 Py_DECREF(z);
2945 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002946 });
Tim Peters0973b992004-08-29 22:16:50 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 carry = *pz + f * f;
2949 *pz++ = (digit)(carry & PyLong_MASK);
2950 carry >>= PyLong_SHIFT;
2951 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* Now f is added in twice in each column of the
2954 * pyramid it appears. Same as adding f<<1 once.
2955 */
2956 f <<= 1;
2957 while (pa < paend) {
2958 carry += *pz + *pa++ * f;
2959 *pz++ = (digit)(carry & PyLong_MASK);
2960 carry >>= PyLong_SHIFT;
2961 assert(carry <= (PyLong_MASK << 1));
2962 }
2963 if (carry) {
2964 carry += *pz;
2965 *pz++ = (digit)(carry & PyLong_MASK);
2966 carry >>= PyLong_SHIFT;
2967 }
2968 if (carry)
2969 *pz += (digit)(carry & PyLong_MASK);
2970 assert((carry >> PyLong_SHIFT) == 0);
2971 }
2972 }
2973 else { /* a is not the same as b -- gradeschool long mult */
2974 for (i = 0; i < size_a; ++i) {
2975 twodigits carry = 0;
2976 twodigits f = a->ob_digit[i];
2977 digit *pz = z->ob_digit + i;
2978 digit *pb = b->ob_digit;
2979 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002982 Py_DECREF(z);
2983 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002984 });
Tim Peters0973b992004-08-29 22:16:50 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 while (pb < pbend) {
2987 carry += *pz + *pb++ * f;
2988 *pz++ = (digit)(carry & PyLong_MASK);
2989 carry >>= PyLong_SHIFT;
2990 assert(carry <= PyLong_MASK);
2991 }
2992 if (carry)
2993 *pz += (digit)(carry & PyLong_MASK);
2994 assert((carry >> PyLong_SHIFT) == 0);
2995 }
2996 }
2997 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002998}
2999
3000/* A helper for Karatsuba multiplication (k_mul).
3001 Takes a long "n" and an integer "size" representing the place to
3002 split, and sets low and high such that abs(n) == (high << size) + low,
3003 viewing the shift as being by digits. The sign bit is ignored, and
3004 the return values are >= 0.
3005 Returns 0 on success, -1 on failure.
3006*/
3007static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003008kmul_split(PyLongObject *n,
3009 Py_ssize_t size,
3010 PyLongObject **high,
3011 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 PyLongObject *hi, *lo;
3014 Py_ssize_t size_lo, size_hi;
3015 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 size_lo = MIN(size_n, size);
3018 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 if ((hi = _PyLong_New(size_hi)) == NULL)
3021 return -1;
3022 if ((lo = _PyLong_New(size_lo)) == NULL) {
3023 Py_DECREF(hi);
3024 return -1;
3025 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3028 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 *high = long_normalize(hi);
3031 *low = long_normalize(lo);
3032 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003033}
3034
Tim Peters60004642002-08-12 22:01:34 +00003035static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3036
Tim Peters5af4e6c2002-08-12 02:31:19 +00003037/* Karatsuba multiplication. Ignores the input signs, and returns the
3038 * absolute value of the product (or NULL if error).
3039 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3040 */
3041static PyLongObject *
3042k_mul(PyLongObject *a, PyLongObject *b)
3043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 Py_ssize_t asize = ABS(Py_SIZE(a));
3045 Py_ssize_t bsize = ABS(Py_SIZE(b));
3046 PyLongObject *ah = NULL;
3047 PyLongObject *al = NULL;
3048 PyLongObject *bh = NULL;
3049 PyLongObject *bl = NULL;
3050 PyLongObject *ret = NULL;
3051 PyLongObject *t1, *t2, *t3;
3052 Py_ssize_t shift; /* the number of digits we split off */
3053 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3056 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3057 * Then the original product is
3058 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3059 * By picking X to be a power of 2, "*X" is just shifting, and it's
3060 * been reduced to 3 multiplies on numbers half the size.
3061 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 /* We want to split based on the larger number; fiddle so that b
3064 * is largest.
3065 */
3066 if (asize > bsize) {
3067 t1 = a;
3068 a = b;
3069 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 i = asize;
3072 asize = bsize;
3073 bsize = i;
3074 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 /* Use gradeschool math when either number is too small. */
3077 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3078 if (asize <= i) {
3079 if (asize == 0)
3080 return (PyLongObject *)PyLong_FromLong(0);
3081 else
3082 return x_mul(a, b);
3083 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 /* If a is small compared to b, splitting on b gives a degenerate
3086 * case with ah==0, and Karatsuba may be (even much) less efficient
3087 * than "grade school" then. However, we can still win, by viewing
3088 * b as a string of "big digits", each of width a->ob_size. That
3089 * leads to a sequence of balanced calls to k_mul.
3090 */
3091 if (2 * asize <= bsize)
3092 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 /* Split a & b into hi & lo pieces. */
3095 shift = bsize >> 1;
3096 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3097 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (a == b) {
3100 bh = ah;
3101 bl = al;
3102 Py_INCREF(bh);
3103 Py_INCREF(bl);
3104 }
3105 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 /* The plan:
3108 * 1. Allocate result space (asize + bsize digits: that's always
3109 * enough).
3110 * 2. Compute ah*bh, and copy into result at 2*shift.
3111 * 3. Compute al*bl, and copy into result at 0. Note that this
3112 * can't overlap with #2.
3113 * 4. Subtract al*bl from the result, starting at shift. This may
3114 * underflow (borrow out of the high digit), but we don't care:
3115 * we're effectively doing unsigned arithmetic mod
3116 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3117 * borrows and carries out of the high digit can be ignored.
3118 * 5. Subtract ah*bh from the result, starting at shift.
3119 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3120 * at shift.
3121 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 /* 1. Allocate result space. */
3124 ret = _PyLong_New(asize + bsize);
3125 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003126#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 /* Fill with trash, to catch reference to uninitialized digits. */
3128 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003129#endif
Tim Peters44121a62002-08-12 06:17:58 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3132 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3133 assert(Py_SIZE(t1) >= 0);
3134 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3135 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3136 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* Zero-out the digits higher than the ah*bh copy. */
3139 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3140 if (i)
3141 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3142 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* 3. t2 <- al*bl, and copy into the low digits. */
3145 if ((t2 = k_mul(al, bl)) == NULL) {
3146 Py_DECREF(t1);
3147 goto fail;
3148 }
3149 assert(Py_SIZE(t2) >= 0);
3150 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3151 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Zero out remaining digits. */
3154 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3155 if (i)
3156 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3159 * because it's fresher in cache.
3160 */
3161 i = Py_SIZE(ret) - shift; /* # digits after shift */
3162 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3163 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3166 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3169 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3170 Py_DECREF(ah);
3171 Py_DECREF(al);
3172 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 if (a == b) {
3175 t2 = t1;
3176 Py_INCREF(t2);
3177 }
3178 else if ((t2 = x_add(bh, bl)) == NULL) {
3179 Py_DECREF(t1);
3180 goto fail;
3181 }
3182 Py_DECREF(bh);
3183 Py_DECREF(bl);
3184 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 t3 = k_mul(t1, t2);
3187 Py_DECREF(t1);
3188 Py_DECREF(t2);
3189 if (t3 == NULL) goto fail;
3190 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 /* Add t3. It's not obvious why we can't run out of room here.
3193 * See the (*) comment after this function.
3194 */
3195 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3196 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Mark Dickinson22b20182010-05-10 21:27:53 +00003200 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 Py_XDECREF(ret);
3202 Py_XDECREF(ah);
3203 Py_XDECREF(al);
3204 Py_XDECREF(bh);
3205 Py_XDECREF(bl);
3206 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003207}
3208
Tim Petersd6974a52002-08-13 20:37:51 +00003209/* (*) Why adding t3 can't "run out of room" above.
3210
Tim Petersab86c2b2002-08-15 20:06:00 +00003211Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3212to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003213
Tim Petersab86c2b2002-08-15 20:06:00 +000032141. For any integer i, i = c(i/2) + f(i/2). In particular,
3215 bsize = c(bsize/2) + f(bsize/2).
32162. shift = f(bsize/2)
32173. asize <= bsize
32184. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3219 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003220
Tim Petersab86c2b2002-08-15 20:06:00 +00003221We allocated asize + bsize result digits, and add t3 into them at an offset
3222of shift. This leaves asize+bsize-shift allocated digit positions for t3
3223to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3224asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003225
Tim Petersab86c2b2002-08-15 20:06:00 +00003226bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3227at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003228
Tim Petersab86c2b2002-08-15 20:06:00 +00003229If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3230digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3231most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003232
Tim Petersab86c2b2002-08-15 20:06:00 +00003233The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003234
Tim Petersab86c2b2002-08-15 20:06:00 +00003235 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003236
Tim Petersab86c2b2002-08-15 20:06:00 +00003237and we have asize + c(bsize/2) available digit positions. We need to show
3238this is always enough. An instance of c(bsize/2) cancels out in both, so
3239the question reduces to whether asize digits is enough to hold
3240(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3241then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3242asize 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 +00003243digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003244asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003245c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3246is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3247bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003248
Tim Peters48d52c02002-08-14 17:07:32 +00003249Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3250clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3251ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003252*/
3253
Tim Peters60004642002-08-12 22:01:34 +00003254/* b has at least twice the digits of a, and a is big enough that Karatsuba
3255 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3256 * of slices, each with a->ob_size digits, and multiply the slices by a,
3257 * one at a time. This gives k_mul balanced inputs to work with, and is
3258 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003259 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003260 * single-width slice overlap between successive partial sums).
3261 */
3262static PyLongObject *
3263k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 const Py_ssize_t asize = ABS(Py_SIZE(a));
3266 Py_ssize_t bsize = ABS(Py_SIZE(b));
3267 Py_ssize_t nbdone; /* # of b digits already multiplied */
3268 PyLongObject *ret;
3269 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 assert(asize > KARATSUBA_CUTOFF);
3272 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 /* Allocate result space, and zero it out. */
3275 ret = _PyLong_New(asize + bsize);
3276 if (ret == NULL)
3277 return NULL;
3278 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 /* Successive slices of b are copied into bslice. */
3281 bslice = _PyLong_New(asize);
3282 if (bslice == NULL)
3283 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 nbdone = 0;
3286 while (bsize > 0) {
3287 PyLongObject *product;
3288 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 /* Multiply the next slice of b by a. */
3291 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3292 nbtouse * sizeof(digit));
3293 Py_SIZE(bslice) = nbtouse;
3294 product = k_mul(a, bslice);
3295 if (product == NULL)
3296 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 /* Add into result. */
3299 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3300 product->ob_digit, Py_SIZE(product));
3301 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 bsize -= nbtouse;
3304 nbdone += nbtouse;
3305 }
Tim Peters60004642002-08-12 22:01:34 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 Py_DECREF(bslice);
3308 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003309
Mark Dickinson22b20182010-05-10 21:27:53 +00003310 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 Py_DECREF(ret);
3312 Py_XDECREF(bslice);
3313 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003314}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003315
3316static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003317long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 /* fast path for single-digit multiplication */
3324 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3325 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003326#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003328#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 /* if we don't have long long then we're almost certainly
3330 using 15-bit digits, so v will fit in a long. In the
3331 unlikely event that we're using 30-bit digits on a platform
3332 without long long, a large v will just cause us to fall
3333 through to the general multiplication code below. */
3334 if (v >= LONG_MIN && v <= LONG_MAX)
3335 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003336#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 z = k_mul(a, b);
3340 /* Negate if exactly one of the inputs is negative. */
3341 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3342 NEGATE(z);
3343 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003344}
3345
Guido van Rossume32e0141992-01-19 16:31:05 +00003346/* The / and % operators are now defined in terms of divmod().
3347 The expression a mod b has the value a - b*floor(a/b).
3348 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003349 |a| by |b|, with the sign of a. This is also expressed
3350 as a - b*trunc(a/b), if trunc truncates towards zero.
3351 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 a b a rem b a mod b
3353 13 10 3 3
3354 -13 10 -3 7
3355 13 -10 3 -7
3356 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003357 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003358 have different signs. We then subtract one from the 'div'
3359 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003360
Tim Peters47e52ee2004-08-30 02:44:38 +00003361/* Compute
3362 * *pdiv, *pmod = divmod(v, w)
3363 * NULL can be passed for pdiv or pmod, in which case that part of
3364 * the result is simply thrown away. The caller owns a reference to
3365 * each of these it requests (does not pass NULL for).
3366 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003367static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003368l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 if (long_divrem(v, w, &div, &mod) < 0)
3374 return -1;
3375 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3376 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3377 PyLongObject *temp;
3378 PyLongObject *one;
3379 temp = (PyLongObject *) long_add(mod, w);
3380 Py_DECREF(mod);
3381 mod = temp;
3382 if (mod == NULL) {
3383 Py_DECREF(div);
3384 return -1;
3385 }
3386 one = (PyLongObject *) PyLong_FromLong(1L);
3387 if (one == NULL ||
3388 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3389 Py_DECREF(mod);
3390 Py_DECREF(div);
3391 Py_XDECREF(one);
3392 return -1;
3393 }
3394 Py_DECREF(one);
3395 Py_DECREF(div);
3396 div = temp;
3397 }
3398 if (pdiv != NULL)
3399 *pdiv = div;
3400 else
3401 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 if (pmod != NULL)
3404 *pmod = mod;
3405 else
3406 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003409}
3410
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003411static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003412long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 CHECK_BINOP(a, b);
3417 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3418 div = NULL;
3419 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003420}
3421
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003422/* PyLong/PyLong -> float, with correctly rounded result. */
3423
3424#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3425#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3426
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003427static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003428long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 PyLongObject *a, *b, *x;
3431 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3432 digit mask, low;
3433 int inexact, negate, a_is_small, b_is_small;
3434 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 CHECK_BINOP(v, w);
3437 a = (PyLongObject *)v;
3438 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /*
3441 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3444 1. choose a suitable integer 'shift'
3445 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3446 3. adjust x for correct rounding
3447 4. convert x to a double dx with the same value
3448 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3453 returns either 0.0 or -0.0, depending on the sign of b. For a and
3454 b both nonzero, ignore signs of a and b, and add the sign back in
3455 at the end. Now write a_bits and b_bits for the bit lengths of a
3456 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3457 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3462 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3463 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3464 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 1. The integer 'shift' is chosen so that x has the right number of
3469 bits for a double, plus two or three extra bits that will be used
3470 in the rounding decisions. Writing a_bits and b_bits for the
3471 number of significant bits in a and b respectively, a
3472 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 This is fine in the usual case, but if a/b is smaller than the
3477 smallest normal float then it can lead to double rounding on an
3478 IEEE 754 platform, giving incorrectly rounded results. So we
3479 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 2. The quantity x is computed by first shifting a (left -shift bits
3484 if shift <= 0, right shift bits if shift > 0) and then dividing by
3485 b. For both the shift and the division, we keep track of whether
3486 the result is inexact, in a flag 'inexact'; this information is
3487 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 With the choice of shift above, together with our assumption that
3490 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3491 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3494 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 For float representability, we need x/2**extra_bits <
3499 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3500 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 To round, we just modify the bottom digit of x in-place; this can
3505 end up giving a digit with value > PyLONG_MASK, but that's not a
3506 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 With the original choices for shift above, extra_bits will always
3509 be 2 or 3. Then rounding under the round-half-to-even rule, we
3510 round up iff the most significant of the extra bits is 1, and
3511 either: (a) the computation of x in step 2 had an inexact result,
3512 or (b) at least one other of the extra bits is 1, or (c) the least
3513 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 4. Conversion to a double is straightforward; all floating-point
3516 operations involved in the conversion are exact, so there's no
3517 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3520 The result will always be exactly representable as a double, except
3521 in the case that it overflows. To avoid dependence on the exact
3522 behaviour of ldexp on overflow, we check for overflow before
3523 applying ldexp. The result of ldexp is adjusted for sign before
3524 returning.
3525 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /* Reduce to case where a and b are both positive. */
3528 a_size = ABS(Py_SIZE(a));
3529 b_size = ABS(Py_SIZE(b));
3530 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3531 if (b_size == 0) {
3532 PyErr_SetString(PyExc_ZeroDivisionError,
3533 "division by zero");
3534 goto error;
3535 }
3536 if (a_size == 0)
3537 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 /* Fast path for a and b small (exactly representable in a double).
3540 Relies on floating-point division being correctly rounded; results
3541 may be subject to double rounding on x86 machines that operate with
3542 the x87 FPU set to 64-bit precision. */
3543 a_is_small = a_size <= MANT_DIG_DIGITS ||
3544 (a_size == MANT_DIG_DIGITS+1 &&
3545 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3546 b_is_small = b_size <= MANT_DIG_DIGITS ||
3547 (b_size == MANT_DIG_DIGITS+1 &&
3548 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3549 if (a_is_small && b_is_small) {
3550 double da, db;
3551 da = a->ob_digit[--a_size];
3552 while (a_size > 0)
3553 da = da * PyLong_BASE + a->ob_digit[--a_size];
3554 db = b->ob_digit[--b_size];
3555 while (b_size > 0)
3556 db = db * PyLong_BASE + b->ob_digit[--b_size];
3557 result = da / db;
3558 goto success;
3559 }
Tim Peterse2a60002001-09-04 06:17:36 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 /* Catch obvious cases of underflow and overflow */
3562 diff = a_size - b_size;
3563 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3564 /* Extreme overflow */
3565 goto overflow;
3566 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3567 /* Extreme underflow */
3568 goto underflow_or_zero;
3569 /* Next line is now safe from overflowing a Py_ssize_t */
3570 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3571 bits_in_digit(b->ob_digit[b_size - 1]);
3572 /* Now diff = a_bits - b_bits. */
3573 if (diff > DBL_MAX_EXP)
3574 goto overflow;
3575 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3576 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 /* Choose value for shift; see comments for step 1 above. */
3579 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 /* x = abs(a * 2**-shift) */
3584 if (shift <= 0) {
3585 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3586 digit rem;
3587 /* x = a << -shift */
3588 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3589 /* In practice, it's probably impossible to end up
3590 here. Both a and b would have to be enormous,
3591 using close to SIZE_T_MAX bytes of memory each. */
3592 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003593 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 goto error;
3595 }
3596 x = _PyLong_New(a_size + shift_digits + 1);
3597 if (x == NULL)
3598 goto error;
3599 for (i = 0; i < shift_digits; i++)
3600 x->ob_digit[i] = 0;
3601 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3602 a_size, -shift % PyLong_SHIFT);
3603 x->ob_digit[a_size + shift_digits] = rem;
3604 }
3605 else {
3606 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3607 digit rem;
3608 /* x = a >> shift */
3609 assert(a_size >= shift_digits);
3610 x = _PyLong_New(a_size - shift_digits);
3611 if (x == NULL)
3612 goto error;
3613 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3614 a_size - shift_digits, shift % PyLong_SHIFT);
3615 /* set inexact if any of the bits shifted out is nonzero */
3616 if (rem)
3617 inexact = 1;
3618 while (!inexact && shift_digits > 0)
3619 if (a->ob_digit[--shift_digits])
3620 inexact = 1;
3621 }
3622 long_normalize(x);
3623 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3626 reference to x, so it's safe to modify it in-place. */
3627 if (b_size == 1) {
3628 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3629 b->ob_digit[0]);
3630 long_normalize(x);
3631 if (rem)
3632 inexact = 1;
3633 }
3634 else {
3635 PyLongObject *div, *rem;
3636 div = x_divrem(x, b, &rem);
3637 Py_DECREF(x);
3638 x = div;
3639 if (x == NULL)
3640 goto error;
3641 if (Py_SIZE(rem))
3642 inexact = 1;
3643 Py_DECREF(rem);
3644 }
3645 x_size = ABS(Py_SIZE(x));
3646 assert(x_size > 0); /* result of division is never zero */
3647 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 /* The number of extra bits that have to be rounded away. */
3650 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3651 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* Round by directly modifying the low digit of x. */
3654 mask = (digit)1 << (extra_bits - 1);
3655 low = x->ob_digit[0] | inexact;
3656 if (low & mask && low & (3*mask-1))
3657 low += mask;
3658 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 /* Convert x to a double dx; the conversion is exact. */
3661 dx = x->ob_digit[--x_size];
3662 while (x_size > 0)
3663 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3664 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /* Check whether ldexp result will overflow a double. */
3667 if (shift + x_bits >= DBL_MAX_EXP &&
3668 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3669 goto overflow;
3670 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003671
3672 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003674
3675 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003677
3678 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 PyErr_SetString(PyExc_OverflowError,
3680 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003681 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003683}
3684
3685static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003686long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 CHECK_BINOP(a, b);
3691
3692 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3693 mod = NULL;
3694 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003695}
3696
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003697static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003698long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 PyLongObject *div, *mod;
3701 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3706 return NULL;
3707 }
3708 z = PyTuple_New(2);
3709 if (z != NULL) {
3710 PyTuple_SetItem(z, 0, (PyObject *) div);
3711 PyTuple_SetItem(z, 1, (PyObject *) mod);
3712 }
3713 else {
3714 Py_DECREF(div);
3715 Py_DECREF(mod);
3716 }
3717 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003718}
3719
Tim Peters47e52ee2004-08-30 02:44:38 +00003720/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003721static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003722long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3725 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 PyLongObject *z = NULL; /* accumulated result */
3728 Py_ssize_t i, j, k; /* counters */
3729 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 /* 5-ary values. If the exponent is large enough, table is
3732 * precomputed so that table[i] == a**i % c for i in range(32).
3733 */
3734 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3735 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 /* a, b, c = v, w, x */
3738 CHECK_BINOP(v, w);
3739 a = (PyLongObject*)v; Py_INCREF(a);
3740 b = (PyLongObject*)w; Py_INCREF(b);
3741 if (PyLong_Check(x)) {
3742 c = (PyLongObject *)x;
3743 Py_INCREF(x);
3744 }
3745 else if (x == Py_None)
3746 c = NULL;
3747 else {
3748 Py_DECREF(a);
3749 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003750 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 }
Tim Peters4c483c42001-09-05 06:24:58 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3754 if (c) {
3755 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003756 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 goto Error;
3758 }
3759 else {
3760 /* else return a float. This works because we know
3761 that this calls float_pow() which converts its
3762 arguments to double. */
3763 Py_DECREF(a);
3764 Py_DECREF(b);
3765 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3766 }
3767 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 if (c) {
3770 /* if modulus == 0:
3771 raise ValueError() */
3772 if (Py_SIZE(c) == 0) {
3773 PyErr_SetString(PyExc_ValueError,
3774 "pow() 3rd argument cannot be 0");
3775 goto Error;
3776 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 /* if modulus < 0:
3779 negativeOutput = True
3780 modulus = -modulus */
3781 if (Py_SIZE(c) < 0) {
3782 negativeOutput = 1;
3783 temp = (PyLongObject *)_PyLong_Copy(c);
3784 if (temp == NULL)
3785 goto Error;
3786 Py_DECREF(c);
3787 c = temp;
3788 temp = NULL;
3789 NEGATE(c);
3790 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 /* if modulus == 1:
3793 return 0 */
3794 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3795 z = (PyLongObject *)PyLong_FromLong(0L);
3796 goto Done;
3797 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 /* if base < 0:
3800 base = base % modulus
3801 Having the base positive just makes things easier. */
3802 if (Py_SIZE(a) < 0) {
3803 if (l_divmod(a, c, NULL, &temp) < 0)
3804 goto Error;
3805 Py_DECREF(a);
3806 a = temp;
3807 temp = NULL;
3808 }
3809 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 /* At this point a, b, and c are guaranteed non-negative UNLESS
3812 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 z = (PyLongObject *)PyLong_FromLong(1L);
3815 if (z == NULL)
3816 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 /* Perform a modular reduction, X = X % c, but leave X alone if c
3819 * is NULL.
3820 */
3821#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003822 do { \
3823 if (c != NULL) { \
3824 if (l_divmod(X, c, NULL, &temp) < 0) \
3825 goto Error; \
3826 Py_XDECREF(X); \
3827 X = temp; \
3828 temp = NULL; \
3829 } \
3830 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 /* Multiply two values, then reduce the result:
3833 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003834#define MULT(X, Y, result) \
3835 do { \
3836 temp = (PyLongObject *)long_mul(X, Y); \
3837 if (temp == NULL) \
3838 goto Error; \
3839 Py_XDECREF(result); \
3840 result = temp; \
3841 temp = NULL; \
3842 REDUCE(result); \
3843 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3846 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3847 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3848 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3849 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003852 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003854 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 }
3856 }
3857 }
3858 else {
3859 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3860 Py_INCREF(z); /* still holds 1L */
3861 table[0] = z;
3862 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003863 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3866 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3869 const int index = (bi >> j) & 0x1f;
3870 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003871 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003873 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 }
3875 }
3876 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 if (negativeOutput && (Py_SIZE(z) != 0)) {
3879 temp = (PyLongObject *)long_sub(z, c);
3880 if (temp == NULL)
3881 goto Error;
3882 Py_DECREF(z);
3883 z = temp;
3884 temp = NULL;
3885 }
3886 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003887
Mark Dickinson22b20182010-05-10 21:27:53 +00003888 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 if (z != NULL) {
3890 Py_DECREF(z);
3891 z = NULL;
3892 }
3893 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003894 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3896 for (i = 0; i < 32; ++i)
3897 Py_XDECREF(table[i]);
3898 }
3899 Py_DECREF(a);
3900 Py_DECREF(b);
3901 Py_XDECREF(c);
3902 Py_XDECREF(temp);
3903 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003904}
3905
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003906static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003907long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 /* Implement ~x as -(x+1) */
3910 PyLongObject *x;
3911 PyLongObject *w;
3912 if (ABS(Py_SIZE(v)) <=1)
3913 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3914 w = (PyLongObject *)PyLong_FromLong(1L);
3915 if (w == NULL)
3916 return NULL;
3917 x = (PyLongObject *) long_add(v, w);
3918 Py_DECREF(w);
3919 if (x == NULL)
3920 return NULL;
3921 Py_SIZE(x) = -(Py_SIZE(x));
3922 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003923}
3924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003925static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003926long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 PyLongObject *z;
3929 if (ABS(Py_SIZE(v)) <= 1)
3930 return PyLong_FromLong(-MEDIUM_VALUE(v));
3931 z = (PyLongObject *)_PyLong_Copy(v);
3932 if (z != NULL)
3933 Py_SIZE(z) = -(Py_SIZE(v));
3934 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003935}
3936
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003937static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003938long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (Py_SIZE(v) < 0)
3941 return long_neg(v);
3942 else
3943 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003944}
3945
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003946static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003947long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003950}
3951
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003952static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003953long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 PyLongObject *z = NULL;
3956 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3957 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 if (Py_SIZE(a) < 0) {
3962 /* Right shifting negative numbers is harder */
3963 PyLongObject *a1, *a2;
3964 a1 = (PyLongObject *) long_invert(a);
3965 if (a1 == NULL)
3966 goto rshift_error;
3967 a2 = (PyLongObject *) long_rshift(a1, b);
3968 Py_DECREF(a1);
3969 if (a2 == NULL)
3970 goto rshift_error;
3971 z = (PyLongObject *) long_invert(a2);
3972 Py_DECREF(a2);
3973 }
3974 else {
3975 shiftby = PyLong_AsSsize_t((PyObject *)b);
3976 if (shiftby == -1L && PyErr_Occurred())
3977 goto rshift_error;
3978 if (shiftby < 0) {
3979 PyErr_SetString(PyExc_ValueError,
3980 "negative shift count");
3981 goto rshift_error;
3982 }
3983 wordshift = shiftby / PyLong_SHIFT;
3984 newsize = ABS(Py_SIZE(a)) - wordshift;
3985 if (newsize <= 0)
3986 return PyLong_FromLong(0);
3987 loshift = shiftby % PyLong_SHIFT;
3988 hishift = PyLong_SHIFT - loshift;
3989 lomask = ((digit)1 << hishift) - 1;
3990 himask = PyLong_MASK ^ lomask;
3991 z = _PyLong_New(newsize);
3992 if (z == NULL)
3993 goto rshift_error;
3994 if (Py_SIZE(a) < 0)
3995 Py_SIZE(z) = -(Py_SIZE(z));
3996 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3997 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3998 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003999 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 }
4001 z = long_normalize(z);
4002 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004003 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004005
Guido van Rossumc6913e71991-11-19 20:26:46 +00004006}
4007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004008static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004009long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 /* This version due to Tim Peters */
4012 PyLongObject *a = (PyLongObject*)v;
4013 PyLongObject *b = (PyLongObject*)w;
4014 PyLongObject *z = NULL;
4015 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4016 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 shiftby = PyLong_AsSsize_t((PyObject *)b);
4021 if (shiftby == -1L && PyErr_Occurred())
4022 goto lshift_error;
4023 if (shiftby < 0) {
4024 PyErr_SetString(PyExc_ValueError, "negative shift count");
4025 goto lshift_error;
4026 }
4027 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4028 wordshift = shiftby / PyLong_SHIFT;
4029 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 oldsize = ABS(Py_SIZE(a));
4032 newsize = oldsize + wordshift;
4033 if (remshift)
4034 ++newsize;
4035 z = _PyLong_New(newsize);
4036 if (z == NULL)
4037 goto lshift_error;
4038 if (Py_SIZE(a) < 0)
4039 NEGATE(z);
4040 for (i = 0; i < wordshift; i++)
4041 z->ob_digit[i] = 0;
4042 accum = 0;
4043 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4044 accum |= (twodigits)a->ob_digit[j] << remshift;
4045 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4046 accum >>= PyLong_SHIFT;
4047 }
4048 if (remshift)
4049 z->ob_digit[newsize-1] = (digit)accum;
4050 else
4051 assert(!accum);
4052 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004053 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004055}
4056
Mark Dickinson27a87a22009-10-25 20:43:34 +00004057/* Compute two's complement of digit vector a[0:m], writing result to
4058 z[0:m]. The digit vector a need not be normalized, but should not
4059 be entirely zero. a and z may point to the same digit vector. */
4060
4061static void
4062v_complement(digit *z, digit *a, Py_ssize_t m)
4063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 Py_ssize_t i;
4065 digit carry = 1;
4066 for (i = 0; i < m; ++i) {
4067 carry += a[i] ^ PyLong_MASK;
4068 z[i] = carry & PyLong_MASK;
4069 carry >>= PyLong_SHIFT;
4070 }
4071 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004072}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004073
4074/* Bitwise and/xor/or operations */
4075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004076static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004077long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004079 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 int nega, negb, negz;
4082 Py_ssize_t size_a, size_b, size_z, i;
4083 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 /* Bitwise operations for negative numbers operate as though
4086 on a two's complement representation. So convert arguments
4087 from sign-magnitude to two's complement, and convert the
4088 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 /* If a is negative, replace it by its two's complement. */
4091 size_a = ABS(Py_SIZE(a));
4092 nega = Py_SIZE(a) < 0;
4093 if (nega) {
4094 z = _PyLong_New(size_a);
4095 if (z == NULL)
4096 return NULL;
4097 v_complement(z->ob_digit, a->ob_digit, size_a);
4098 a = z;
4099 }
4100 else
4101 /* Keep reference count consistent. */
4102 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 /* Same for b. */
4105 size_b = ABS(Py_SIZE(b));
4106 negb = Py_SIZE(b) < 0;
4107 if (negb) {
4108 z = _PyLong_New(size_b);
4109 if (z == NULL) {
4110 Py_DECREF(a);
4111 return NULL;
4112 }
4113 v_complement(z->ob_digit, b->ob_digit, size_b);
4114 b = z;
4115 }
4116 else
4117 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 /* Swap a and b if necessary to ensure size_a >= size_b. */
4120 if (size_a < size_b) {
4121 z = a; a = b; b = z;
4122 size_z = size_a; size_a = size_b; size_b = size_z;
4123 negz = nega; nega = negb; negb = negz;
4124 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 /* JRH: The original logic here was to allocate the result value (z)
4127 as the longer of the two operands. However, there are some cases
4128 where the result is guaranteed to be shorter than that: AND of two
4129 positives, OR of two negatives: use the shorter number. AND with
4130 mixed signs: use the positive number. OR with mixed signs: use the
4131 negative number.
4132 */
4133 switch (op) {
4134 case '^':
4135 negz = nega ^ negb;
4136 size_z = size_a;
4137 break;
4138 case '&':
4139 negz = nega & negb;
4140 size_z = negb ? size_a : size_b;
4141 break;
4142 case '|':
4143 negz = nega | negb;
4144 size_z = negb ? size_b : size_a;
4145 break;
4146 default:
4147 PyErr_BadArgument();
4148 return NULL;
4149 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 /* We allow an extra digit if z is negative, to make sure that
4152 the final two's complement of z doesn't overflow. */
4153 z = _PyLong_New(size_z + negz);
4154 if (z == NULL) {
4155 Py_DECREF(a);
4156 Py_DECREF(b);
4157 return NULL;
4158 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 /* Compute digits for overlap of a and b. */
4161 switch(op) {
4162 case '&':
4163 for (i = 0; i < size_b; ++i)
4164 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4165 break;
4166 case '|':
4167 for (i = 0; i < size_b; ++i)
4168 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4169 break;
4170 case '^':
4171 for (i = 0; i < size_b; ++i)
4172 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4173 break;
4174 default:
4175 PyErr_BadArgument();
4176 return NULL;
4177 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 /* Copy any remaining digits of a, inverting if necessary. */
4180 if (op == '^' && negb)
4181 for (; i < size_z; ++i)
4182 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4183 else if (i < size_z)
4184 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4185 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 /* Complement result if negative. */
4188 if (negz) {
4189 Py_SIZE(z) = -(Py_SIZE(z));
4190 z->ob_digit[size_z] = PyLong_MASK;
4191 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4192 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 Py_DECREF(a);
4195 Py_DECREF(b);
4196 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004197}
4198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004199static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004200long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 PyObject *c;
4203 CHECK_BINOP(a, b);
4204 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4205 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004206}
4207
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004208static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004209long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 PyObject *c;
4212 CHECK_BINOP(a, b);
4213 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4214 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004215}
4216
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004217static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004218long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 PyObject *c;
4221 CHECK_BINOP(a, b);
4222 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4223 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004224}
4225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004226static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004227long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 if (PyLong_CheckExact(v))
4230 Py_INCREF(v);
4231 else
4232 v = _PyLong_Copy((PyLongObject *)v);
4233 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004234}
4235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004237long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 double result;
4240 result = PyLong_AsDouble(v);
4241 if (result == -1.0 && PyErr_Occurred())
4242 return NULL;
4243 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004244}
4245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004246static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004247long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004248
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249static PyObject *
4250long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4251{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004252 PyObject *obase = NULL, *x = NULL;
4253 long base;
4254 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 if (type != &PyLong_Type)
4258 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004259 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4260 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 return NULL;
4262 if (x == NULL)
4263 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004264 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004266
4267 base = PyLong_AsLongAndOverflow(obase, &overflow);
4268 if (base == -1 && PyErr_Occurred())
4269 return NULL;
4270 if (overflow || (base != 0 && base < 2) || base > 36) {
4271 PyErr_SetString(PyExc_ValueError,
4272 "int() arg 2 must be >= 2 and <= 36");
4273 return NULL;
4274 }
4275
4276 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004277 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4279 /* Since PyLong_FromString doesn't have a length parameter,
4280 * check here for possible NULs in the string. */
4281 char *string;
4282 Py_ssize_t size = Py_SIZE(x);
4283 if (PyByteArray_Check(x))
4284 string = PyByteArray_AS_STRING(x);
4285 else
4286 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004287 if (strlen(string) != (size_t)size || !size) {
4288 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 x is a bytes or buffer, *and* a base is given. */
4290 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004291 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004292 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 return NULL;
4294 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004295 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 }
4297 else {
4298 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004299 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 return NULL;
4301 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302}
4303
Guido van Rossumbef14172001-08-29 15:47:46 +00004304/* Wimpy, slow approach to tp_new calls for subtypes of long:
4305 first create a regular long from whatever arguments we got,
4306 then allocate a subtype instance and initialize it from
4307 the regular long. The regular long is then thrown away.
4308*/
4309static PyObject *
4310long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 PyLongObject *tmp, *newobj;
4313 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 assert(PyType_IsSubtype(type, &PyLong_Type));
4316 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4317 if (tmp == NULL)
4318 return NULL;
4319 assert(PyLong_CheckExact(tmp));
4320 n = Py_SIZE(tmp);
4321 if (n < 0)
4322 n = -n;
4323 newobj = (PyLongObject *)type->tp_alloc(type, n);
4324 if (newobj == NULL) {
4325 Py_DECREF(tmp);
4326 return NULL;
4327 }
4328 assert(PyLong_Check(newobj));
4329 Py_SIZE(newobj) = Py_SIZE(tmp);
4330 for (i = 0; i < n; i++)
4331 newobj->ob_digit[i] = tmp->ob_digit[i];
4332 Py_DECREF(tmp);
4333 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004334}
4335
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004336static PyObject *
4337long_getnewargs(PyLongObject *v)
4338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004340}
4341
Guido van Rossumb43daf72007-08-01 18:08:08 +00004342static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004343long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004345}
4346
4347static PyObject *
4348long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004350}
4351
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004352static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004353long__format__(PyObject *self, PyObject *args)
4354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004356 _PyUnicodeWriter writer;
4357 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4360 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004361
4362 _PyUnicodeWriter_Init(&writer, 0);
4363 ret = _PyLong_FormatAdvancedWriter(
4364 &writer,
4365 self,
4366 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4367 if (ret == -1) {
4368 _PyUnicodeWriter_Dealloc(&writer);
4369 return NULL;
4370 }
4371 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004372}
4373
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004374/* Return a pair (q, r) such that a = b * q + r, and
4375 abs(r) <= abs(b)/2, with equality possible only if q is even.
4376 In other words, q == a / b, rounded to the nearest integer using
4377 round-half-to-even. */
4378
4379PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004380_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004381{
4382 PyLongObject *quo = NULL, *rem = NULL;
4383 PyObject *one = NULL, *twice_rem, *result, *temp;
4384 int cmp, quo_is_odd, quo_is_neg;
4385
4386 /* Equivalent Python code:
4387
4388 def divmod_near(a, b):
4389 q, r = divmod(a, b)
4390 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4391 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4392 # positive, 2 * r < b if b negative.
4393 greater_than_half = 2*r > b if b > 0 else 2*r < b
4394 exactly_half = 2*r == b
4395 if greater_than_half or exactly_half and q % 2 == 1:
4396 q += 1
4397 r -= b
4398 return q, r
4399
4400 */
4401 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4402 PyErr_SetString(PyExc_TypeError,
4403 "non-integer arguments in division");
4404 return NULL;
4405 }
4406
4407 /* Do a and b have different signs? If so, quotient is negative. */
4408 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4409
4410 one = PyLong_FromLong(1L);
4411 if (one == NULL)
4412 return NULL;
4413
4414 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4415 goto error;
4416
4417 /* compare twice the remainder with the divisor, to see
4418 if we need to adjust the quotient and remainder */
4419 twice_rem = long_lshift((PyObject *)rem, one);
4420 if (twice_rem == NULL)
4421 goto error;
4422 if (quo_is_neg) {
4423 temp = long_neg((PyLongObject*)twice_rem);
4424 Py_DECREF(twice_rem);
4425 twice_rem = temp;
4426 if (twice_rem == NULL)
4427 goto error;
4428 }
4429 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4430 Py_DECREF(twice_rem);
4431
4432 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4433 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4434 /* fix up quotient */
4435 if (quo_is_neg)
4436 temp = long_sub(quo, (PyLongObject *)one);
4437 else
4438 temp = long_add(quo, (PyLongObject *)one);
4439 Py_DECREF(quo);
4440 quo = (PyLongObject *)temp;
4441 if (quo == NULL)
4442 goto error;
4443 /* and remainder */
4444 if (quo_is_neg)
4445 temp = long_add(rem, (PyLongObject *)b);
4446 else
4447 temp = long_sub(rem, (PyLongObject *)b);
4448 Py_DECREF(rem);
4449 rem = (PyLongObject *)temp;
4450 if (rem == NULL)
4451 goto error;
4452 }
4453
4454 result = PyTuple_New(2);
4455 if (result == NULL)
4456 goto error;
4457
4458 /* PyTuple_SET_ITEM steals references */
4459 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4460 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4461 Py_DECREF(one);
4462 return result;
4463
4464 error:
4465 Py_XDECREF(quo);
4466 Py_XDECREF(rem);
4467 Py_XDECREF(one);
4468 return NULL;
4469}
4470
Eric Smith8c663262007-08-25 02:26:07 +00004471static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004472long_round(PyObject *self, PyObject *args)
4473{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004474 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004475
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004476 /* To round an integer m to the nearest 10**n (n positive), we make use of
4477 * the divmod_near operation, defined by:
4478 *
4479 * divmod_near(a, b) = (q, r)
4480 *
4481 * where q is the nearest integer to the quotient a / b (the
4482 * nearest even integer in the case of a tie) and r == a - q * b.
4483 * Hence q * b = a - r is the nearest multiple of b to a,
4484 * preferring even multiples in the case of a tie.
4485 *
4486 * So the nearest multiple of 10**n to m is:
4487 *
4488 * m - divmod_near(m, 10**n)[1].
4489 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4491 return NULL;
4492 if (o_ndigits == NULL)
4493 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004494
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004495 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (ndigits == NULL)
4497 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004498
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004499 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (Py_SIZE(ndigits) >= 0) {
4501 Py_DECREF(ndigits);
4502 return long_long(self);
4503 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004504
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004505 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4506 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004508 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004510 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004511
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004512 result = PyLong_FromLong(10L);
4513 if (result == NULL) {
4514 Py_DECREF(ndigits);
4515 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004517
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004518 temp = long_pow(result, ndigits, Py_None);
4519 Py_DECREF(ndigits);
4520 Py_DECREF(result);
4521 result = temp;
4522 if (result == NULL)
4523 return NULL;
4524
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004525 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004526 Py_DECREF(result);
4527 result = temp;
4528 if (result == NULL)
4529 return NULL;
4530
4531 temp = long_sub((PyLongObject *)self,
4532 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4533 Py_DECREF(result);
4534 result = temp;
4535
4536 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004537}
4538
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004539static PyObject *
4540long_sizeof(PyLongObject *v)
4541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4545 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004546}
4547
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004548static PyObject *
4549long_bit_length(PyLongObject *v)
4550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004551 PyLongObject *result, *x, *y;
4552 Py_ssize_t ndigits, msd_bits = 0;
4553 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 assert(v != NULL);
4556 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 ndigits = ABS(Py_SIZE(v));
4559 if (ndigits == 0)
4560 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 msd = v->ob_digit[ndigits-1];
4563 while (msd >= 32) {
4564 msd_bits += 6;
4565 msd >>= 6;
4566 }
4567 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4570 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 /* expression above may overflow; use Python integers instead */
4573 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4574 if (result == NULL)
4575 return NULL;
4576 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4577 if (x == NULL)
4578 goto error;
4579 y = (PyLongObject *)long_mul(result, x);
4580 Py_DECREF(x);
4581 if (y == NULL)
4582 goto error;
4583 Py_DECREF(result);
4584 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4587 if (x == NULL)
4588 goto error;
4589 y = (PyLongObject *)long_add(result, x);
4590 Py_DECREF(x);
4591 if (y == NULL)
4592 goto error;
4593 Py_DECREF(result);
4594 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004597
Mark Dickinson22b20182010-05-10 21:27:53 +00004598 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 Py_DECREF(result);
4600 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004601}
4602
4603PyDoc_STRVAR(long_bit_length_doc,
4604"int.bit_length() -> int\n\
4605\n\
4606Number of bits necessary to represent self in binary.\n\
4607>>> bin(37)\n\
4608'0b100101'\n\
4609>>> (37).bit_length()\n\
46106");
4611
Christian Heimes53876d92008-04-19 00:31:39 +00004612#if 0
4613static PyObject *
4614long_is_finite(PyObject *v)
4615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004617}
4618#endif
4619
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004620
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004621static PyObject *
4622long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 PyObject *byteorder_str;
4625 PyObject *is_signed_obj = NULL;
4626 Py_ssize_t length;
4627 int little_endian;
4628 int is_signed;
4629 PyObject *bytes;
4630 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4633 &length, &byteorder_str,
4634 &is_signed_obj))
4635 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 if (args != NULL && Py_SIZE(args) > 2) {
4638 PyErr_SetString(PyExc_TypeError,
4639 "'signed' is a keyword-only argument");
4640 return NULL;
4641 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4644 little_endian = 1;
4645 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4646 little_endian = 0;
4647 else {
4648 PyErr_SetString(PyExc_ValueError,
4649 "byteorder must be either 'little' or 'big'");
4650 return NULL;
4651 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 if (is_signed_obj != NULL) {
4654 int cmp = PyObject_IsTrue(is_signed_obj);
4655 if (cmp < 0)
4656 return NULL;
4657 is_signed = cmp ? 1 : 0;
4658 }
4659 else {
4660 /* If the signed argument was omitted, use False as the
4661 default. */
4662 is_signed = 0;
4663 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 if (length < 0) {
4666 PyErr_SetString(PyExc_ValueError,
4667 "length argument must be non-negative");
4668 return NULL;
4669 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 bytes = PyBytes_FromStringAndSize(NULL, length);
4672 if (bytes == NULL)
4673 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4676 length, little_endian, is_signed) < 0) {
4677 Py_DECREF(bytes);
4678 return NULL;
4679 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004682}
4683
Mark Dickinson078c2532010-01-30 18:06:17 +00004684PyDoc_STRVAR(long_to_bytes_doc,
4685"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004686\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004687Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004688\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004690raised if the integer is not representable with the given number of\n\
4691bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004692\n\
4693The byteorder argument determines the byte order used to represent the\n\
4694integer. If byteorder is 'big', the most significant byte is at the\n\
4695beginning of the byte array. If byteorder is 'little', the most\n\
4696significant byte is at the end of the byte array. To request the native\n\
4697byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4698\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004699The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004701is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004702
4703static PyObject *
4704long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 PyObject *byteorder_str;
4707 PyObject *is_signed_obj = NULL;
4708 int little_endian;
4709 int is_signed;
4710 PyObject *obj;
4711 PyObject *bytes;
4712 PyObject *long_obj;
4713 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4716 &obj, &byteorder_str,
4717 &is_signed_obj))
4718 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 if (args != NULL && Py_SIZE(args) > 2) {
4721 PyErr_SetString(PyExc_TypeError,
4722 "'signed' is a keyword-only argument");
4723 return NULL;
4724 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4727 little_endian = 1;
4728 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4729 little_endian = 0;
4730 else {
4731 PyErr_SetString(PyExc_ValueError,
4732 "byteorder must be either 'little' or 'big'");
4733 return NULL;
4734 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 if (is_signed_obj != NULL) {
4737 int cmp = PyObject_IsTrue(is_signed_obj);
4738 if (cmp < 0)
4739 return NULL;
4740 is_signed = cmp ? 1 : 0;
4741 }
4742 else {
4743 /* If the signed argument was omitted, use False as the
4744 default. */
4745 is_signed = 0;
4746 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 bytes = PyObject_Bytes(obj);
4749 if (bytes == NULL)
4750 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 long_obj = _PyLong_FromByteArray(
4753 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4754 little_endian, is_signed);
4755 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004757 /* If from_bytes() was used on subclass, allocate new subclass
4758 * instance, initialize it with decoded long value and return it.
4759 */
4760 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4761 PyLongObject *newobj;
4762 int i;
4763 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 newobj = (PyLongObject *)type->tp_alloc(type, n);
4766 if (newobj == NULL) {
4767 Py_DECREF(long_obj);
4768 return NULL;
4769 }
4770 assert(PyLong_Check(newobj));
4771 Py_SIZE(newobj) = Py_SIZE(long_obj);
4772 for (i = 0; i < n; i++) {
4773 newobj->ob_digit[i] =
4774 ((PyLongObject *)long_obj)->ob_digit[i];
4775 }
4776 Py_DECREF(long_obj);
4777 return (PyObject *)newobj;
4778 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004781}
4782
Mark Dickinson078c2532010-01-30 18:06:17 +00004783PyDoc_STRVAR(long_from_bytes_doc,
4784"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4785\n\
4786Return the integer represented by the given array of bytes.\n\
4787\n\
4788The bytes argument must either support the buffer protocol or be an\n\
4789iterable object producing bytes. Bytes and bytearray are examples of\n\
4790built-in objects that support the buffer protocol.\n\
4791\n\
4792The byteorder argument determines the byte order used to represent the\n\
4793integer. If byteorder is 'big', the most significant byte is at the\n\
4794beginning of the byte array. If byteorder is 'little', the most\n\
4795significant byte is at the end of the byte array. To request the native\n\
4796byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4797\n\
4798The signed keyword-only argument indicates whether two's complement is\n\
4799used to represent the integer.");
4800
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004801static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4803 "Returns self, the complex conjugate of any int."},
4804 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4805 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004806#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4808 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004809#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 {"to_bytes", (PyCFunction)long_to_bytes,
4811 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4812 {"from_bytes", (PyCFunction)long_from_bytes,
4813 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4814 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4815 "Truncating an Integral returns itself."},
4816 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4817 "Flooring an Integral returns itself."},
4818 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4819 "Ceiling of an Integral returns itself."},
4820 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4821 "Rounding an Integral returns itself.\n"
4822 "Rounding with an ndigits argument also returns an integer."},
4823 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4824 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4825 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4826 "Returns size in memory, in bytes"},
4827 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004828};
4829
Guido van Rossumb43daf72007-08-01 18:08:08 +00004830static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004831 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004832 (getter)long_long, (setter)NULL,
4833 "the real part of a complex number",
4834 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004835 {"imag",
4836 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004837 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004838 NULL},
4839 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004840 (getter)long_long, (setter)NULL,
4841 "the numerator of a rational number in lowest terms",
4842 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004843 {"denominator",
4844 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004845 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004846 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004847 {NULL} /* Sentinel */
4848};
4849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004850PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004851"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004852\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004853Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004854point argument will be truncated towards zero (this does not include a\n\
4855string representation of a floating point number!) When converting a\n\
4856string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004857converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004858
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004859static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004860 (binaryfunc)long_add, /*nb_add*/
4861 (binaryfunc)long_sub, /*nb_subtract*/
4862 (binaryfunc)long_mul, /*nb_multiply*/
4863 long_mod, /*nb_remainder*/
4864 long_divmod, /*nb_divmod*/
4865 long_pow, /*nb_power*/
4866 (unaryfunc)long_neg, /*nb_negative*/
4867 (unaryfunc)long_long, /*tp_positive*/
4868 (unaryfunc)long_abs, /*tp_absolute*/
4869 (inquiry)long_bool, /*tp_bool*/
4870 (unaryfunc)long_invert, /*nb_invert*/
4871 long_lshift, /*nb_lshift*/
4872 (binaryfunc)long_rshift, /*nb_rshift*/
4873 long_and, /*nb_and*/
4874 long_xor, /*nb_xor*/
4875 long_or, /*nb_or*/
4876 long_long, /*nb_int*/
4877 0, /*nb_reserved*/
4878 long_float, /*nb_float*/
4879 0, /* nb_inplace_add */
4880 0, /* nb_inplace_subtract */
4881 0, /* nb_inplace_multiply */
4882 0, /* nb_inplace_remainder */
4883 0, /* nb_inplace_power */
4884 0, /* nb_inplace_lshift */
4885 0, /* nb_inplace_rshift */
4886 0, /* nb_inplace_and */
4887 0, /* nb_inplace_xor */
4888 0, /* nb_inplace_or */
4889 long_div, /* nb_floor_divide */
4890 long_true_divide, /* nb_true_divide */
4891 0, /* nb_inplace_floor_divide */
4892 0, /* nb_inplace_true_divide */
4893 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004894};
4895
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004896PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4898 "int", /* tp_name */
4899 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4900 sizeof(digit), /* tp_itemsize */
4901 long_dealloc, /* tp_dealloc */
4902 0, /* tp_print */
4903 0, /* tp_getattr */
4904 0, /* tp_setattr */
4905 0, /* tp_reserved */
4906 long_to_decimal_string, /* tp_repr */
4907 &long_as_number, /* tp_as_number */
4908 0, /* tp_as_sequence */
4909 0, /* tp_as_mapping */
4910 (hashfunc)long_hash, /* tp_hash */
4911 0, /* tp_call */
4912 long_to_decimal_string, /* tp_str */
4913 PyObject_GenericGetAttr, /* tp_getattro */
4914 0, /* tp_setattro */
4915 0, /* tp_as_buffer */
4916 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4917 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4918 long_doc, /* tp_doc */
4919 0, /* tp_traverse */
4920 0, /* tp_clear */
4921 long_richcompare, /* tp_richcompare */
4922 0, /* tp_weaklistoffset */
4923 0, /* tp_iter */
4924 0, /* tp_iternext */
4925 long_methods, /* tp_methods */
4926 0, /* tp_members */
4927 long_getset, /* tp_getset */
4928 0, /* tp_base */
4929 0, /* tp_dict */
4930 0, /* tp_descr_get */
4931 0, /* tp_descr_set */
4932 0, /* tp_dictoffset */
4933 0, /* tp_init */
4934 0, /* tp_alloc */
4935 long_new, /* tp_new */
4936 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004937};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004938
Mark Dickinsonbd792642009-03-18 20:06:12 +00004939static PyTypeObject Int_InfoType;
4940
4941PyDoc_STRVAR(int_info__doc__,
4942"sys.int_info\n\
4943\n\
4944A struct sequence that holds information about Python's\n\
4945internal representation of integers. The attributes are read only.");
4946
4947static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004949 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004951};
4952
4953static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 "sys.int_info", /* name */
4955 int_info__doc__, /* doc */
4956 int_info_fields, /* fields */
4957 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004958};
4959
4960PyObject *
4961PyLong_GetInfo(void)
4962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 PyObject* int_info;
4964 int field = 0;
4965 int_info = PyStructSequence_New(&Int_InfoType);
4966 if (int_info == NULL)
4967 return NULL;
4968 PyStructSequence_SET_ITEM(int_info, field++,
4969 PyLong_FromLong(PyLong_SHIFT));
4970 PyStructSequence_SET_ITEM(int_info, field++,
4971 PyLong_FromLong(sizeof(digit)));
4972 if (PyErr_Occurred()) {
4973 Py_CLEAR(int_info);
4974 return NULL;
4975 }
4976 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004977}
4978
Guido van Rossumddefaf32007-01-14 03:31:43 +00004979int
4980_PyLong_Init(void)
4981{
4982#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 int ival, size;
4984 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4987 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4988 if (Py_TYPE(v) == &PyLong_Type) {
4989 /* The element is already initialized, most likely
4990 * the Python interpreter was initialized before.
4991 */
4992 Py_ssize_t refcnt;
4993 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4996 _Py_NewReference(op);
4997 /* _Py_NewReference sets the ref count to 1 but
4998 * the ref count might be larger. Set the refcnt
4999 * to the original refcnt + 1 */
5000 Py_REFCNT(op) = refcnt + 1;
5001 assert(Py_SIZE(op) == size);
5002 assert(v->ob_digit[0] == abs(ival));
5003 }
5004 else {
5005 PyObject_INIT(v, &PyLong_Type);
5006 }
5007 Py_SIZE(v) = size;
5008 v->ob_digit[0] = abs(ival);
5009 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005010#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 /* initialize int_info */
5012 if (Int_InfoType.tp_name == 0)
5013 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005016}
5017
5018void
5019PyLong_Fini(void)
5020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 /* Integers are currently statically allocated. Py_DECREF is not
5022 needed, but Python must forget about the reference or multiple
5023 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005024#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 int i;
5026 PyLongObject *v = small_ints;
5027 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5028 _Py_DEC_REFTOTAL;
5029 _Py_ForgetReference((PyObject*)v);
5030 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005031#endif
5032}