]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Objects/longobject.c
AppPkg/.../Python-2.7.10: Update file for Python-2.7.10 inclusion.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / PyMod-2.7.10 / Objects / longobject.c
CommitLineData
3ec97ca4
DM
1/* Long (arbitrary precision) integer object implementation */\r
2\r
3/* XXX The functional organization of this file is terrible */\r
4\r
5#include "Python.h"\r
6#include "longintrepr.h"\r
7#include "structseq.h"\r
8\r
9#include <float.h>\r
10#include <ctype.h>\r
11#include <stddef.h>\r
12\r
13/* For long multiplication, use the O(N**2) school algorithm unless\r
14 * both operands contain more than KARATSUBA_CUTOFF digits (this\r
15 * being an internal Python long digit, in base PyLong_BASE).\r
16 */\r
17#define KARATSUBA_CUTOFF 70\r
18#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)\r
19\r
20/* For exponentiation, use the binary left-to-right algorithm\r
21 * unless the exponent contains more than FIVEARY_CUTOFF digits.\r
22 * In that case, do 5 bits at a time. The potential drawback is that\r
23 * a table of 2**5 intermediate results is computed.\r
24 */\r
25#define FIVEARY_CUTOFF 8\r
26\r
27#define ABS(x) ((x) < 0 ? -(x) : (x))\r
28\r
29#undef MIN\r
30#undef MAX\r
31#define MAX(x, y) ((x) < (y) ? (y) : (x))\r
32#define MIN(x, y) ((x) > (y) ? (y) : (x))\r
33\r
34#define SIGCHECK(PyTryBlock) \\r
35 do { \\r
36 if (--_Py_Ticker < 0) { \\r
37 _Py_Ticker = _Py_CheckInterval; \\r
38 if (PyErr_CheckSignals()) PyTryBlock \\r
39 } \\r
40 } while(0)\r
41\r
42/* Normalize (remove leading zeros from) a long int object.\r
43 Doesn't attempt to free the storage--in most cases, due to the nature\r
44 of the algorithms used, this could save at most be one word anyway. */\r
45\r
46static PyLongObject *\r
47long_normalize(register PyLongObject *v)\r
48{\r
49 Py_ssize_t j = ABS(Py_SIZE(v));\r
50 Py_ssize_t i = j;\r
51\r
52 while (i > 0 && v->ob_digit[i-1] == 0)\r
53 --i;\r
54 if (i != j)\r
55 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;\r
56 return v;\r
57}\r
58\r
59/* Allocate a new long int object with size digits.\r
60 Return NULL and set exception if we run out of memory. */\r
61\r
62#define MAX_LONG_DIGITS \\r
63 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))\r
64\r
65PyLongObject *\r
66_PyLong_New(Py_ssize_t size)\r
67{\r
68 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {\r
69 PyErr_SetString(PyExc_OverflowError,\r
70 "too many digits in integer");\r
71 return NULL;\r
72 }\r
73 /* coverity[ampersand_in_size] */\r
74 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect\r
75 overflow */\r
76 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);\r
77}\r
78\r
79PyObject *\r
80_PyLong_Copy(PyLongObject *src)\r
81{\r
82 PyLongObject *result;\r
83 Py_ssize_t i;\r
84\r
85 assert(src != NULL);\r
86 i = src->ob_size;\r
87 if (i < 0)\r
88 i = -(i);\r
89 result = _PyLong_New(i);\r
90 if (result != NULL) {\r
91 result->ob_size = src->ob_size;\r
92 while (--i >= 0)\r
93 result->ob_digit[i] = src->ob_digit[i];\r
94 }\r
95 return (PyObject *)result;\r
96}\r
97\r
98/* Create a new long int object from a C long int */\r
99\r
100PyObject *\r
101PyLong_FromLong(long ival)\r
102{\r
103 PyLongObject *v;\r
104 unsigned long abs_ival;\r
105 unsigned long t; /* unsigned so >> doesn't propagate sign bit */\r
106 int ndigits = 0;\r
107 int negative = 0;\r
108\r
109 if (ival < 0) {\r
110 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then\r
111 ANSI C says that the result of -ival is undefined when ival\r
112 == LONG_MIN. Hence the following workaround. */\r
113 abs_ival = (unsigned long)(-1-ival) + 1;\r
114 negative = 1;\r
115 }\r
116 else {\r
117 abs_ival = (unsigned long)ival;\r
118 }\r
119\r
120 /* Count the number of Python digits.\r
121 We used to pick 5 ("big enough for anything"), but that's a\r
122 waste of time and space given that 5*15 = 75 bits are rarely\r
123 needed. */\r
124 t = abs_ival;\r
125 while (t) {\r
126 ++ndigits;\r
127 t >>= PyLong_SHIFT;\r
128 }\r
129 v = _PyLong_New(ndigits);\r
130 if (v != NULL) {\r
131 digit *p = v->ob_digit;\r
132 v->ob_size = negative ? -ndigits : ndigits;\r
133 t = abs_ival;\r
134 while (t) {\r
135 *p++ = (digit)(t & PyLong_MASK);\r
136 t >>= PyLong_SHIFT;\r
137 }\r
138 }\r
139 return (PyObject *)v;\r
140}\r
141\r
142/* Create a new long int object from a C unsigned long int */\r
143\r
144PyObject *\r
145PyLong_FromUnsignedLong(unsigned long ival)\r
146{\r
147 PyLongObject *v;\r
148 unsigned long t;\r
149 int ndigits = 0;\r
150\r
151 /* Count the number of Python digits. */\r
152 t = (unsigned long)ival;\r
153 while (t) {\r
154 ++ndigits;\r
155 t >>= PyLong_SHIFT;\r
156 }\r
157 v = _PyLong_New(ndigits);\r
158 if (v != NULL) {\r
159 digit *p = v->ob_digit;\r
160 Py_SIZE(v) = ndigits;\r
161 while (ival) {\r
162 *p++ = (digit)(ival & PyLong_MASK);\r
163 ival >>= PyLong_SHIFT;\r
164 }\r
165 }\r
166 return (PyObject *)v;\r
167}\r
168\r
169/* Create a new long int object from a C double */\r
170\r
171PyObject *\r
172PyLong_FromDouble(double dval)\r
173{\r
174 PyLongObject *v;\r
175 double frac;\r
176 int i, ndig, expo, neg;\r
177 neg = 0;\r
178 if (Py_IS_INFINITY(dval)) {\r
179 PyErr_SetString(PyExc_OverflowError,\r
180 "cannot convert float infinity to integer");\r
181 return NULL;\r
182 }\r
183 if (Py_IS_NAN(dval)) {\r
184 PyErr_SetString(PyExc_ValueError,\r
185 "cannot convert float NaN to integer");\r
186 return NULL;\r
187 }\r
188 if (dval < 0.0) {\r
189 neg = 1;\r
190 dval = -dval;\r
191 }\r
192 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */\r
193 if (expo <= 0)\r
194 return PyLong_FromLong(0L);\r
195 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */\r
196 v = _PyLong_New(ndig);\r
197 if (v == NULL)\r
198 return NULL;\r
199 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);\r
200 for (i = ndig; --i >= 0; ) {\r
201 digit bits = (digit)frac;\r
202 v->ob_digit[i] = bits;\r
203 frac = frac - (double)bits;\r
204 frac = ldexp(frac, PyLong_SHIFT);\r
205 }\r
206 if (neg)\r
207 Py_SIZE(v) = -(Py_SIZE(v));\r
208 return (PyObject *)v;\r
209}\r
210\r
211/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define\r
212 * anything about what happens when a signed integer operation overflows,\r
213 * and some compilers think they're doing you a favor by being "clever"\r
214 * then. The bit pattern for the largest postive signed long is\r
215 * (unsigned long)LONG_MAX, and for the smallest negative signed long\r
216 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.\r
217 * However, some other compilers warn about applying unary minus to an\r
218 * unsigned operand. Hence the weird "0-".\r
219 */\r
220#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)\r
221#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)\r
222\r
223/* Get a C long int from a Python long or Python int object.\r
224 On overflow, returns -1 and sets *overflow to 1 or -1 depending\r
225 on the sign of the result. Otherwise *overflow is 0.\r
226\r
227 For other errors (e.g., type error), returns -1 and sets an error\r
228 condition.\r
229*/\r
230\r
231long\r
232PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)\r
233{\r
234 /* This version by Tim Peters */\r
235 register PyLongObject *v;\r
236 unsigned long x, prev;\r
237 long res;\r
238 Py_ssize_t i;\r
239 int sign;\r
240 int do_decref = 0; /* if nb_int was called */\r
241\r
242 *overflow = 0;\r
243 if (vv == NULL) {\r
244 PyErr_BadInternalCall();\r
245 return -1;\r
246 }\r
247\r
248 if(PyInt_Check(vv))\r
249 return PyInt_AsLong(vv);\r
250\r
251 if (!PyLong_Check(vv)) {\r
252 PyNumberMethods *nb;\r
253 nb = vv->ob_type->tp_as_number;\r
254 if (nb == NULL || nb->nb_int == NULL) {\r
255 PyErr_SetString(PyExc_TypeError,\r
256 "an integer is required");\r
257 return -1;\r
258 }\r
259 vv = (*nb->nb_int) (vv);\r
260 if (vv == NULL)\r
261 return -1;\r
262 do_decref = 1;\r
263 if(PyInt_Check(vv)) {\r
264 res = PyInt_AsLong(vv);\r
265 goto exit;\r
266 }\r
267 if (!PyLong_Check(vv)) {\r
268 Py_DECREF(vv);\r
269 PyErr_SetString(PyExc_TypeError,\r
270 "nb_int should return int object");\r
271 return -1;\r
272 }\r
273 }\r
274\r
275 res = -1;\r
276 v = (PyLongObject *)vv;\r
277 i = Py_SIZE(v);\r
278\r
279 switch (i) {\r
280 case -1:\r
281 res = -(sdigit)v->ob_digit[0];\r
282 break;\r
283 case 0:\r
284 res = 0;\r
285 break;\r
286 case 1:\r
287 res = v->ob_digit[0];\r
288 break;\r
289 default:\r
290 sign = 1;\r
291 x = 0;\r
292 if (i < 0) {\r
293 sign = -1;\r
294 i = -(i);\r
295 }\r
296 while (--i >= 0) {\r
297 prev = x;\r
298 x = (x << PyLong_SHIFT) + v->ob_digit[i];\r
299 if ((x >> PyLong_SHIFT) != prev) {\r
300 *overflow = sign;\r
301 goto exit;\r
302 }\r
303 }\r
304 /* Haven't lost any bits, but casting to long requires extra\r
305 * care (see comment above).\r
306 */\r
307 if (x <= (unsigned long)LONG_MAX) {\r
308 res = (long)x * sign;\r
309 }\r
310 else if (sign < 0 && x == PY_ABS_LONG_MIN) {\r
311 res = LONG_MIN;\r
312 }\r
313 else {\r
314 *overflow = sign;\r
315 /* res is already set to -1 */\r
316 }\r
317 }\r
318 exit:\r
319 if (do_decref) {\r
320 Py_DECREF(vv);\r
321 }\r
322 return res;\r
323}\r
324\r
325/* Get a C long int from a long int object.\r
326 Returns -1 and sets an error condition if overflow occurs. */\r
327\r
328long\r
329PyLong_AsLong(PyObject *obj)\r
330{\r
331 int overflow;\r
332 long result = PyLong_AsLongAndOverflow(obj, &overflow);\r
333 if (overflow) {\r
334 /* XXX: could be cute and give a different\r
335 message for overflow == -1 */\r
336 PyErr_SetString(PyExc_OverflowError,\r
337 "Python int too large to convert to C long");\r
338 }\r
339 return result;\r
340}\r
341\r
342/* Get a C int from a long int object or any object that has an __int__\r
343 method. Return -1 and set an error if overflow occurs. */\r
344\r
345int\r
346_PyLong_AsInt(PyObject *obj)\r
347{\r
348 int overflow;\r
349 long result = PyLong_AsLongAndOverflow(obj, &overflow);\r
350 if (overflow || result > INT_MAX || result < INT_MIN) {\r
351 /* XXX: could be cute and give a different\r
352 message for overflow == -1 */\r
353 PyErr_SetString(PyExc_OverflowError,\r
354 "Python int too large to convert to C int");\r
355 return -1;\r
356 }\r
357 return (int)result;\r
358}\r
359\r
360/* Get a Py_ssize_t from a long int object.\r
361 Returns -1 and sets an error condition if overflow occurs. */\r
362\r
363Py_ssize_t\r
364PyLong_AsSsize_t(PyObject *vv) {\r
365 register PyLongObject *v;\r
366 size_t x, prev;\r
367 Py_ssize_t i;\r
368 int sign;\r
369\r
370 if (vv == NULL || !PyLong_Check(vv)) {\r
371 PyErr_BadInternalCall();\r
372 return -1;\r
373 }\r
374 v = (PyLongObject *)vv;\r
375 i = v->ob_size;\r
376 sign = 1;\r
377 x = 0;\r
378 if (i < 0) {\r
379 sign = -1;\r
380 i = -(i);\r
381 }\r
382 while (--i >= 0) {\r
383 prev = x;\r
384 x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
385 if ((x >> PyLong_SHIFT) != prev)\r
386 goto overflow;\r
387 }\r
388 /* Haven't lost any bits, but casting to a signed type requires\r
389 * extra care (see comment above).\r
390 */\r
391 if (x <= (size_t)PY_SSIZE_T_MAX) {\r
392 return (Py_ssize_t)x * sign;\r
393 }\r
394 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {\r
395 return PY_SSIZE_T_MIN;\r
396 }\r
397 /* else overflow */\r
398\r
399 overflow:\r
400 PyErr_SetString(PyExc_OverflowError,\r
401 "long int too large to convert to int");\r
402 return -1;\r
403}\r
404\r
405/* Get a C unsigned long int from a long int object.\r
406 Returns -1 and sets an error condition if overflow occurs. */\r
407\r
408unsigned long\r
409PyLong_AsUnsignedLong(PyObject *vv)\r
410{\r
411 register PyLongObject *v;\r
412 unsigned long x, prev;\r
413 Py_ssize_t i;\r
414\r
415 if (vv == NULL || !PyLong_Check(vv)) {\r
416 if (vv != NULL && PyInt_Check(vv)) {\r
417 long val = PyInt_AsLong(vv);\r
418 if (val < 0) {\r
419 PyErr_SetString(PyExc_OverflowError,\r
420 "can't convert negative value "\r
421 "to unsigned long");\r
422 return (unsigned long) -1;\r
423 }\r
424 return val;\r
425 }\r
426 PyErr_BadInternalCall();\r
427 return (unsigned long) -1;\r
428 }\r
429 v = (PyLongObject *)vv;\r
430 i = Py_SIZE(v);\r
431 x = 0;\r
432 if (i < 0) {\r
433 PyErr_SetString(PyExc_OverflowError,\r
434 "can't convert negative value to unsigned long");\r
435 return (unsigned long) -1;\r
436 }\r
437 while (--i >= 0) {\r
438 prev = x;\r
439 x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
440 if ((x >> PyLong_SHIFT) != prev) {\r
441 PyErr_SetString(PyExc_OverflowError,\r
442 "long int too large to convert");\r
443 return (unsigned long) -1;\r
444 }\r
445 }\r
446 return x;\r
447}\r
448\r
449/* Get a C unsigned long int from a long int object, ignoring the high bits.\r
450 Returns -1 and sets an error condition if an error occurs. */\r
451\r
452unsigned long\r
453PyLong_AsUnsignedLongMask(PyObject *vv)\r
454{\r
455 register PyLongObject *v;\r
456 unsigned long x;\r
457 Py_ssize_t i;\r
458 int sign;\r
459\r
460 if (vv == NULL || !PyLong_Check(vv)) {\r
461 if (vv != NULL && PyInt_Check(vv))\r
462 return PyInt_AsUnsignedLongMask(vv);\r
463 PyErr_BadInternalCall();\r
464 return (unsigned long) -1;\r
465 }\r
466 v = (PyLongObject *)vv;\r
467 i = v->ob_size;\r
468 sign = 1;\r
469 x = 0;\r
470 if (i < 0) {\r
471 sign = -1;\r
472 i = -i;\r
473 }\r
474 while (--i >= 0) {\r
475 x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
476 }\r
477 return x * sign;\r
478}\r
479\r
480int\r
481_PyLong_Sign(PyObject *vv)\r
482{\r
483 PyLongObject *v = (PyLongObject *)vv;\r
484\r
485 assert(v != NULL);\r
486 assert(PyLong_Check(v));\r
487\r
488 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);\r
489}\r
490\r
491size_t\r
492_PyLong_NumBits(PyObject *vv)\r
493{\r
494 PyLongObject *v = (PyLongObject *)vv;\r
495 size_t result = 0;\r
496 Py_ssize_t ndigits;\r
497\r
498 assert(v != NULL);\r
499 assert(PyLong_Check(v));\r
500 ndigits = ABS(Py_SIZE(v));\r
501 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);\r
502 if (ndigits > 0) {\r
503 digit msd = v->ob_digit[ndigits - 1];\r
504\r
505 result = (ndigits - 1) * PyLong_SHIFT;\r
506 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))\r
507 goto Overflow;\r
508 do {\r
509 ++result;\r
510 if (result == 0)\r
511 goto Overflow;\r
512 msd >>= 1;\r
513 } while (msd);\r
514 }\r
515 return result;\r
516\r
517 Overflow:\r
518 PyErr_SetString(PyExc_OverflowError, "long has too many bits "\r
519 "to express in a platform size_t");\r
520 return (size_t)-1;\r
521}\r
522\r
523PyObject *\r
524_PyLong_FromByteArray(const unsigned char* bytes, size_t n,\r
525 int little_endian, int is_signed)\r
526{\r
527 const unsigned char* pstartbyte; /* LSB of bytes */\r
528 int incr; /* direction to move pstartbyte */\r
529 const unsigned char* pendbyte; /* MSB of bytes */\r
530 size_t numsignificantbytes; /* number of bytes that matter */\r
531 Py_ssize_t ndigits; /* number of Python long digits */\r
532 PyLongObject* v; /* result */\r
533 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */\r
534\r
535 if (n == 0)\r
536 return PyLong_FromLong(0L);\r
537\r
538 if (little_endian) {\r
539 pstartbyte = bytes;\r
540 pendbyte = bytes + n - 1;\r
541 incr = 1;\r
542 }\r
543 else {\r
544 pstartbyte = bytes + n - 1;\r
545 pendbyte = bytes;\r
546 incr = -1;\r
547 }\r
548\r
549 if (is_signed)\r
550 is_signed = *pendbyte >= 0x80;\r
551\r
552 /* Compute numsignificantbytes. This consists of finding the most\r
553 significant byte. Leading 0 bytes are insignificant if the number\r
554 is positive, and leading 0xff bytes if negative. */\r
555 {\r
556 size_t i;\r
557 const unsigned char* p = pendbyte;\r
558 const int pincr = -incr; /* search MSB to LSB */\r
559 const unsigned char insignficant = is_signed ? 0xff : 0x00;\r
560\r
561 for (i = 0; i < n; ++i, p += pincr) {\r
562 if (*p != insignficant)\r
563 break;\r
564 }\r
565 numsignificantbytes = n - i;\r
566 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so\r
567 actually has 2 significant bytes. OTOH, 0xff0001 ==\r
568 -0x00ffff, so we wouldn't *need* to bump it there; but we\r
569 do for 0xffff = -0x0001. To be safe without bothering to\r
570 check every case, bump it regardless. */\r
571 if (is_signed && numsignificantbytes < n)\r
572 ++numsignificantbytes;\r
573 }\r
574\r
575 /* How many Python long digits do we need? We have\r
576 8*numsignificantbytes bits, and each Python long digit has\r
577 PyLong_SHIFT bits, so it's the ceiling of the quotient. */\r
578 /* catch overflow before it happens */\r
579 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {\r
580 PyErr_SetString(PyExc_OverflowError,\r
581 "byte array too long to convert to int");\r
582 return NULL;\r
583 }\r
584 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;\r
585 v = _PyLong_New(ndigits);\r
586 if (v == NULL)\r
587 return NULL;\r
588\r
589 /* Copy the bits over. The tricky parts are computing 2's-comp on\r
590 the fly for signed numbers, and dealing with the mismatch between\r
591 8-bit bytes and (probably) 15-bit Python digits.*/\r
592 {\r
593 size_t i;\r
594 twodigits carry = 1; /* for 2's-comp calculation */\r
595 twodigits accum = 0; /* sliding register */\r
596 unsigned int accumbits = 0; /* number of bits in accum */\r
597 const unsigned char* p = pstartbyte;\r
598\r
599 for (i = 0; i < numsignificantbytes; ++i, p += incr) {\r
600 twodigits thisbyte = *p;\r
601 /* Compute correction for 2's comp, if needed. */\r
602 if (is_signed) {\r
603 thisbyte = (0xff ^ thisbyte) + carry;\r
604 carry = thisbyte >> 8;\r
605 thisbyte &= 0xff;\r
606 }\r
607 /* Because we're going LSB to MSB, thisbyte is\r
608 more significant than what's already in accum,\r
609 so needs to be prepended to accum. */\r
610 accum |= (twodigits)thisbyte << accumbits;\r
611 accumbits += 8;\r
612 if (accumbits >= PyLong_SHIFT) {\r
613 /* There's enough to fill a Python digit. */\r
614 assert(idigit < ndigits);\r
615 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);\r
616 ++idigit;\r
617 accum >>= PyLong_SHIFT;\r
618 accumbits -= PyLong_SHIFT;\r
619 assert(accumbits < PyLong_SHIFT);\r
620 }\r
621 }\r
622 assert(accumbits < PyLong_SHIFT);\r
623 if (accumbits) {\r
624 assert(idigit < ndigits);\r
625 v->ob_digit[idigit] = (digit)accum;\r
626 ++idigit;\r
627 }\r
628 }\r
629\r
630 Py_SIZE(v) = is_signed ? -idigit : idigit;\r
631 return (PyObject *)long_normalize(v);\r
632}\r
633\r
634int\r
635_PyLong_AsByteArray(PyLongObject* v,\r
636 unsigned char* bytes, size_t n,\r
637 int little_endian, int is_signed)\r
638{\r
639 Py_ssize_t i; /* index into v->ob_digit */\r
640 Py_ssize_t ndigits; /* |v->ob_size| */\r
641 twodigits accum; /* sliding register */\r
642 unsigned int accumbits; /* # bits in accum */\r
643 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */\r
644 digit carry; /* for computing 2's-comp */\r
645 size_t j; /* # bytes filled */\r
646 unsigned char* p; /* pointer to next byte in bytes */\r
647 int pincr; /* direction to move p */\r
648\r
649 assert(v != NULL && PyLong_Check(v));\r
650\r
651 if (Py_SIZE(v) < 0) {\r
652 ndigits = -(Py_SIZE(v));\r
653 if (!is_signed) {\r
654 PyErr_SetString(PyExc_OverflowError,\r
655 "can't convert negative long to unsigned");\r
656 return -1;\r
657 }\r
658 do_twos_comp = 1;\r
659 }\r
660 else {\r
661 ndigits = Py_SIZE(v);\r
662 do_twos_comp = 0;\r
663 }\r
664\r
665 if (little_endian) {\r
666 p = bytes;\r
667 pincr = 1;\r
668 }\r
669 else {\r
670 p = bytes + n - 1;\r
671 pincr = -1;\r
672 }\r
673\r
674 /* Copy over all the Python digits.\r
675 It's crucial that every Python digit except for the MSD contribute\r
676 exactly PyLong_SHIFT bits to the total, so first assert that the long is\r
677 normalized. */\r
678 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);\r
679 j = 0;\r
680 accum = 0;\r
681 accumbits = 0;\r
682 carry = do_twos_comp ? 1 : 0;\r
683 for (i = 0; i < ndigits; ++i) {\r
684 digit thisdigit = v->ob_digit[i];\r
685 if (do_twos_comp) {\r
686 thisdigit = (thisdigit ^ PyLong_MASK) + carry;\r
687 carry = thisdigit >> PyLong_SHIFT;\r
688 thisdigit &= PyLong_MASK;\r
689 }\r
690 /* Because we're going LSB to MSB, thisdigit is more\r
691 significant than what's already in accum, so needs to be\r
692 prepended to accum. */\r
693 accum |= (twodigits)thisdigit << accumbits;\r
694\r
695 /* The most-significant digit may be (probably is) at least\r
696 partly empty. */\r
697 if (i == ndigits - 1) {\r
698 /* Count # of sign bits -- they needn't be stored,\r
699 * although for signed conversion we need later to\r
700 * make sure at least one sign bit gets stored. */\r
701 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;\r
702 while (s != 0) {\r
703 s >>= 1;\r
704 accumbits++;\r
705 }\r
706 }\r
707 else\r
708 accumbits += PyLong_SHIFT;\r
709\r
710 /* Store as many bytes as possible. */\r
711 while (accumbits >= 8) {\r
712 if (j >= n)\r
713 goto Overflow;\r
714 ++j;\r
715 *p = (unsigned char)(accum & 0xff);\r
716 p += pincr;\r
717 accumbits -= 8;\r
718 accum >>= 8;\r
719 }\r
720 }\r
721\r
722 /* Store the straggler (if any). */\r
723 assert(accumbits < 8);\r
724 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */\r
725 if (accumbits > 0) {\r
726 if (j >= n)\r
727 goto Overflow;\r
728 ++j;\r
729 if (do_twos_comp) {\r
730 /* Fill leading bits of the byte with sign bits\r
731 (appropriately pretending that the long had an\r
732 infinite supply of sign bits). */\r
733 accum |= (~(twodigits)0) << accumbits;\r
734 }\r
735 *p = (unsigned char)(accum & 0xff);\r
736 p += pincr;\r
737 }\r
738 else if (j == n && n > 0 && is_signed) {\r
739 /* The main loop filled the byte array exactly, so the code\r
740 just above didn't get to ensure there's a sign bit, and the\r
741 loop below wouldn't add one either. Make sure a sign bit\r
742 exists. */\r
743 unsigned char msb = *(p - pincr);\r
744 int sign_bit_set = msb >= 0x80;\r
745 assert(accumbits == 0);\r
746 if (sign_bit_set == do_twos_comp)\r
747 return 0;\r
748 else\r
749 goto Overflow;\r
750 }\r
751\r
752 /* Fill remaining bytes with copies of the sign bit. */\r
753 {\r
754 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;\r
755 for ( ; j < n; ++j, p += pincr)\r
756 *p = signbyte;\r
757 }\r
758\r
759 return 0;\r
760\r
761 Overflow:\r
762 PyErr_SetString(PyExc_OverflowError, "long too big to convert");\r
763 return -1;\r
764\r
765}\r
766\r
767/* Create a new long (or int) object from a C pointer */\r
768\r
769PyObject *\r
770PyLong_FromVoidPtr(void *p)\r
771{\r
772#if SIZEOF_VOID_P <= SIZEOF_LONG\r
773 if ((long)p < 0)\r
774 return PyLong_FromUnsignedLong((unsigned long)p);\r
775 return PyInt_FromLong((long)p);\r
776#else\r
777\r
778#ifndef HAVE_LONG_LONG\r
779# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"\r
780#endif\r
781#if SIZEOF_LONG_LONG < SIZEOF_VOID_P\r
782# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"\r
783#endif\r
784 /* optimize null pointers */\r
785 if (p == NULL)\r
786 return PyInt_FromLong(0);\r
787 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);\r
788\r
789#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */\r
790}\r
791\r
792/* Get a C pointer from a long object (or an int object in some cases) */\r
793\r
794void *\r
795PyLong_AsVoidPtr(PyObject *vv)\r
796{\r
797 /* This function will allow int or long objects. If vv is neither,\r
798 then the PyLong_AsLong*() functions will raise the exception:\r
799 PyExc_SystemError, "bad argument to internal function"\r
800 */\r
801#if SIZEOF_VOID_P <= SIZEOF_LONG\r
802 long x;\r
803\r
804 if (PyInt_Check(vv))\r
805 x = PyInt_AS_LONG(vv);\r
806 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)\r
807 x = PyLong_AsLong(vv);\r
808 else\r
809 x = PyLong_AsUnsignedLong(vv);\r
810#else\r
811\r
812#ifndef HAVE_LONG_LONG\r
813# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"\r
814#endif\r
815#if SIZEOF_LONG_LONG < SIZEOF_VOID_P\r
816# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"\r
817#endif\r
818 PY_LONG_LONG x;\r
819\r
820 if (PyInt_Check(vv))\r
821 x = PyInt_AS_LONG(vv);\r
822 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)\r
823 x = PyLong_AsLongLong(vv);\r
824 else\r
825 x = PyLong_AsUnsignedLongLong(vv);\r
826\r
827#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */\r
828\r
829 if (x == -1 && PyErr_Occurred())\r
830 return NULL;\r
831 return (void *)x;\r
832}\r
833\r
834#ifdef HAVE_LONG_LONG\r
835\r
836/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later\r
837 * rewritten to use the newer PyLong_{As,From}ByteArray API.\r
838 */\r
839\r
840#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one\r
841#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)\r
842\r
843/* Create a new long int object from a C PY_LONG_LONG int. */\r
844\r
845PyObject *\r
846PyLong_FromLongLong(PY_LONG_LONG ival)\r
847{\r
848 PyLongObject *v;\r
849 unsigned PY_LONG_LONG abs_ival;\r
850 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */\r
851 int ndigits = 0;\r
852 int negative = 0;\r
853\r
854 if (ival < 0) {\r
855 /* avoid signed overflow on negation; see comments\r
856 in PyLong_FromLong above. */\r
857 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;\r
858 negative = 1;\r
859 }\r
860 else {\r
861 abs_ival = (unsigned PY_LONG_LONG)ival;\r
862 }\r
863\r
864 /* Count the number of Python digits.\r
865 We used to pick 5 ("big enough for anything"), but that's a\r
866 waste of time and space given that 5*15 = 75 bits are rarely\r
867 needed. */\r
868 t = abs_ival;\r
869 while (t) {\r
870 ++ndigits;\r
871 t >>= PyLong_SHIFT;\r
872 }\r
873 v = _PyLong_New(ndigits);\r
874 if (v != NULL) {\r
875 digit *p = v->ob_digit;\r
876 Py_SIZE(v) = negative ? -ndigits : ndigits;\r
877 t = abs_ival;\r
878 while (t) {\r
879 *p++ = (digit)(t & PyLong_MASK);\r
880 t >>= PyLong_SHIFT;\r
881 }\r
882 }\r
883 return (PyObject *)v;\r
884}\r
885\r
886/* Create a new long int object from a C unsigned PY_LONG_LONG int. */\r
887\r
888PyObject *\r
889PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)\r
890{\r
891 PyLongObject *v;\r
892 unsigned PY_LONG_LONG t;\r
893 int ndigits = 0;\r
894\r
895 /* Count the number of Python digits. */\r
896 t = (unsigned PY_LONG_LONG)ival;\r
897 while (t) {\r
898 ++ndigits;\r
899 t >>= PyLong_SHIFT;\r
900 }\r
901 v = _PyLong_New(ndigits);\r
902 if (v != NULL) {\r
903 digit *p = v->ob_digit;\r
904 Py_SIZE(v) = ndigits;\r
905 while (ival) {\r
906 *p++ = (digit)(ival & PyLong_MASK);\r
907 ival >>= PyLong_SHIFT;\r
908 }\r
909 }\r
910 return (PyObject *)v;\r
911}\r
912\r
913/* Create a new long int object from a C Py_ssize_t. */\r
914\r
915PyObject *\r
916PyLong_FromSsize_t(Py_ssize_t ival)\r
917{\r
918 Py_ssize_t bytes = ival;\r
919 int one = 1;\r
920 return _PyLong_FromByteArray((unsigned char *)&bytes,\r
921 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);\r
922}\r
923\r
924/* Create a new long int object from a C size_t. */\r
925\r
926PyObject *\r
927PyLong_FromSize_t(size_t ival)\r
928{\r
929 size_t bytes = ival;\r
930 int one = 1;\r
931 return _PyLong_FromByteArray((unsigned char *)&bytes,\r
932 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);\r
933}\r
934\r
935/* Get a C PY_LONG_LONG int from a long int object.\r
936 Return -1 and set an error if overflow occurs. */\r
937\r
938PY_LONG_LONG\r
939PyLong_AsLongLong(PyObject *vv)\r
940{\r
941 PY_LONG_LONG bytes;\r
942 int one = 1;\r
943 int res;\r
944\r
945 if (vv == NULL) {\r
946 PyErr_BadInternalCall();\r
947 return -1;\r
948 }\r
949 if (!PyLong_Check(vv)) {\r
950 PyNumberMethods *nb;\r
951 PyObject *io;\r
952 if (PyInt_Check(vv))\r
953 return (PY_LONG_LONG)PyInt_AsLong(vv);\r
954 if ((nb = vv->ob_type->tp_as_number) == NULL ||\r
955 nb->nb_int == NULL) {\r
956 PyErr_SetString(PyExc_TypeError, "an integer is required");\r
957 return -1;\r
958 }\r
959 io = (*nb->nb_int) (vv);\r
960 if (io == NULL)\r
961 return -1;\r
962 if (PyInt_Check(io)) {\r
963 bytes = PyInt_AsLong(io);\r
964 Py_DECREF(io);\r
965 return bytes;\r
966 }\r
967 if (PyLong_Check(io)) {\r
968 bytes = PyLong_AsLongLong(io);\r
969 Py_DECREF(io);\r
970 return bytes;\r
971 }\r
972 Py_DECREF(io);\r
973 PyErr_SetString(PyExc_TypeError, "integer conversion failed");\r
974 return -1;\r
975 }\r
976\r
977 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,\r
978 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);\r
979\r
980 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */\r
981 if (res < 0)\r
982 return (PY_LONG_LONG)-1;\r
983 else\r
984 return bytes;\r
985}\r
986\r
987/* Get a C unsigned PY_LONG_LONG int from a long int object.\r
988 Return -1 and set an error if overflow occurs. */\r
989\r
990unsigned PY_LONG_LONG\r
991PyLong_AsUnsignedLongLong(PyObject *vv)\r
992{\r
993 unsigned PY_LONG_LONG bytes;\r
994 int one = 1;\r
995 int res;\r
996\r
997 if (vv == NULL || !PyLong_Check(vv)) {\r
998 PyErr_BadInternalCall();\r
999 return (unsigned PY_LONG_LONG)-1;\r
1000 }\r
1001\r
1002 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,\r
1003 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);\r
1004\r
1005 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */\r
1006 if (res < 0)\r
1007 return (unsigned PY_LONG_LONG)res;\r
1008 else\r
1009 return bytes;\r
1010}\r
1011\r
1012/* Get a C unsigned long int from a long int object, ignoring the high bits.\r
1013 Returns -1 and sets an error condition if an error occurs. */\r
1014\r
1015unsigned PY_LONG_LONG\r
1016PyLong_AsUnsignedLongLongMask(PyObject *vv)\r
1017{\r
1018 register PyLongObject *v;\r
1019 unsigned PY_LONG_LONG x;\r
1020 Py_ssize_t i;\r
1021 int sign;\r
1022\r
1023 if (vv == NULL || !PyLong_Check(vv)) {\r
1024 PyErr_BadInternalCall();\r
1025 return (unsigned long) -1;\r
1026 }\r
1027 v = (PyLongObject *)vv;\r
1028 i = v->ob_size;\r
1029 sign = 1;\r
1030 x = 0;\r
1031 if (i < 0) {\r
1032 sign = -1;\r
1033 i = -i;\r
1034 }\r
1035 while (--i >= 0) {\r
1036 x = (x << PyLong_SHIFT) | v->ob_digit[i];\r
1037 }\r
1038 return x * sign;\r
1039}\r
1040\r
1041/* Get a C long long int from a Python long or Python int object.\r
1042 On overflow, returns -1 and sets *overflow to 1 or -1 depending\r
1043 on the sign of the result. Otherwise *overflow is 0.\r
1044\r
1045 For other errors (e.g., type error), returns -1 and sets an error\r
1046 condition.\r
1047*/\r
1048\r
1049PY_LONG_LONG\r
1050PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)\r
1051{\r
1052 /* This version by Tim Peters */\r
1053 register PyLongObject *v;\r
1054 unsigned PY_LONG_LONG x, prev;\r
1055 PY_LONG_LONG res;\r
1056 Py_ssize_t i;\r
1057 int sign;\r
1058 int do_decref = 0; /* if nb_int was called */\r
1059\r
1060 *overflow = 0;\r
1061 if (vv == NULL) {\r
1062 PyErr_BadInternalCall();\r
1063 return -1;\r
1064 }\r
1065\r
1066 if (PyInt_Check(vv))\r
1067 return PyInt_AsLong(vv);\r
1068\r
1069 if (!PyLong_Check(vv)) {\r
1070 PyNumberMethods *nb;\r
1071 nb = vv->ob_type->tp_as_number;\r
1072 if (nb == NULL || nb->nb_int == NULL) {\r
1073 PyErr_SetString(PyExc_TypeError,\r
1074 "an integer is required");\r
1075 return -1;\r
1076 }\r
1077 vv = (*nb->nb_int) (vv);\r
1078 if (vv == NULL)\r
1079 return -1;\r
1080 do_decref = 1;\r
1081 if(PyInt_Check(vv)) {\r
1082 res = PyInt_AsLong(vv);\r
1083 goto exit;\r
1084 }\r
1085 if (!PyLong_Check(vv)) {\r
1086 Py_DECREF(vv);\r
1087 PyErr_SetString(PyExc_TypeError,\r
1088 "nb_int should return int object");\r
1089 return -1;\r
1090 }\r
1091 }\r
1092\r
1093 res = -1;\r
1094 v = (PyLongObject *)vv;\r
1095 i = Py_SIZE(v);\r
1096\r
1097 switch (i) {\r
1098 case -1:\r
1099 res = -(sdigit)v->ob_digit[0];\r
1100 break;\r
1101 case 0:\r
1102 res = 0;\r
1103 break;\r
1104 case 1:\r
1105 res = v->ob_digit[0];\r
1106 break;\r
1107 default:\r
1108 sign = 1;\r
1109 x = 0;\r
1110 if (i < 0) {\r
1111 sign = -1;\r
1112 i = -(i);\r
1113 }\r
1114 while (--i >= 0) {\r
1115 prev = x;\r
1116 x = (x << PyLong_SHIFT) + v->ob_digit[i];\r
1117 if ((x >> PyLong_SHIFT) != prev) {\r
1118 *overflow = sign;\r
1119 goto exit;\r
1120 }\r
1121 }\r
1122 /* Haven't lost any bits, but casting to long requires extra\r
1123 * care (see comment above).\r
1124 */\r
1125 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {\r
1126 res = (PY_LONG_LONG)x * sign;\r
1127 }\r
1128 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {\r
1129 res = PY_LLONG_MIN;\r
1130 }\r
1131 else {\r
1132 *overflow = sign;\r
1133 /* res is already set to -1 */\r
1134 }\r
1135 }\r
1136 exit:\r
1137 if (do_decref) {\r
1138 Py_DECREF(vv);\r
1139 }\r
1140 return res;\r
1141}\r
1142\r
1143#undef IS_LITTLE_ENDIAN\r
1144\r
1145#endif /* HAVE_LONG_LONG */\r
1146\r
1147\r
1148static int\r
1149convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {\r
1150 if (PyLong_Check(v)) {\r
1151 *a = (PyLongObject *) v;\r
1152 Py_INCREF(v);\r
1153 }\r
1154 else if (PyInt_Check(v)) {\r
1155 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));\r
1156 }\r
1157 else {\r
1158 return 0;\r
1159 }\r
1160 if (PyLong_Check(w)) {\r
1161 *b = (PyLongObject *) w;\r
1162 Py_INCREF(w);\r
1163 }\r
1164 else if (PyInt_Check(w)) {\r
1165 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));\r
1166 }\r
1167 else {\r
1168 Py_DECREF(*a);\r
1169 return 0;\r
1170 }\r
1171 return 1;\r
1172}\r
1173\r
1174#define CONVERT_BINOP(v, w, a, b) \\r
1175 do { \\r
1176 if (!convert_binop(v, w, a, b)) { \\r
1177 Py_INCREF(Py_NotImplemented); \\r
1178 return Py_NotImplemented; \\r
1179 } \\r
1180 } while(0) \\r
1181\r
1182/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <\r
1183 2**k if d is nonzero, else 0. */\r
1184\r
1185static const unsigned char BitLengthTable[32] = {\r
1186 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,\r
1187 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5\r
1188};\r
1189\r
1190static int\r
1191bits_in_digit(digit d)\r
1192{\r
1193 int d_bits = 0;\r
1194 while (d >= 32) {\r
1195 d_bits += 6;\r
1196 d >>= 6;\r
1197 }\r
1198 d_bits += (int)BitLengthTable[d];\r
1199 return d_bits;\r
1200}\r
1201\r
1202/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]\r
1203 * is modified in place, by adding y to it. Carries are propagated as far as\r
1204 * x[m-1], and the remaining carry (0 or 1) is returned.\r
1205 */\r
1206static digit\r
1207v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)\r
1208{\r
1209 Py_ssize_t i;\r
1210 digit carry = 0;\r
1211\r
1212 assert(m >= n);\r
1213 for (i = 0; i < n; ++i) {\r
1214 carry += x[i] + y[i];\r
1215 x[i] = carry & PyLong_MASK;\r
1216 carry >>= PyLong_SHIFT;\r
1217 assert((carry & 1) == carry);\r
1218 }\r
1219 for (; carry && i < m; ++i) {\r
1220 carry += x[i];\r
1221 x[i] = carry & PyLong_MASK;\r
1222 carry >>= PyLong_SHIFT;\r
1223 assert((carry & 1) == carry);\r
1224 }\r
1225 return carry;\r
1226}\r
1227\r
1228/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]\r
1229 * is modified in place, by subtracting y from it. Borrows are propagated as\r
1230 * far as x[m-1], and the remaining borrow (0 or 1) is returned.\r
1231 */\r
1232static digit\r
1233v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)\r
1234{\r
1235 Py_ssize_t i;\r
1236 digit borrow = 0;\r
1237\r
1238 assert(m >= n);\r
1239 for (i = 0; i < n; ++i) {\r
1240 borrow = x[i] - y[i] - borrow;\r
1241 x[i] = borrow & PyLong_MASK;\r
1242 borrow >>= PyLong_SHIFT;\r
1243 borrow &= 1; /* keep only 1 sign bit */\r
1244 }\r
1245 for (; borrow && i < m; ++i) {\r
1246 borrow = x[i] - borrow;\r
1247 x[i] = borrow & PyLong_MASK;\r
1248 borrow >>= PyLong_SHIFT;\r
1249 borrow &= 1;\r
1250 }\r
1251 return borrow;\r
1252}\r
1253\r
1254/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put\r
1255 * result in z[0:m], and return the d bits shifted out of the top.\r
1256 */\r
1257static digit\r
1258v_lshift(digit *z, digit *a, Py_ssize_t m, int d)\r
1259{\r
1260 Py_ssize_t i;\r
1261 digit carry = 0;\r
1262\r
1263 assert(0 <= d && d < PyLong_SHIFT);\r
1264 for (i=0; i < m; i++) {\r
1265 twodigits acc = (twodigits)a[i] << d | carry;\r
1266 z[i] = (digit)acc & PyLong_MASK;\r
1267 carry = (digit)(acc >> PyLong_SHIFT);\r
1268 }\r
1269 return carry;\r
1270}\r
1271\r
1272/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put\r
1273 * result in z[0:m], and return the d bits shifted out of the bottom.\r
1274 */\r
1275static digit\r
1276v_rshift(digit *z, digit *a, Py_ssize_t m, int d)\r
1277{\r
1278 Py_ssize_t i;\r
1279 digit carry = 0;\r
1280 digit mask = ((digit)1 << d) - 1U;\r
1281\r
1282 assert(0 <= d && d < PyLong_SHIFT);\r
1283 for (i=m; i-- > 0;) {\r
1284 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];\r
1285 carry = (digit)acc & mask;\r
1286 z[i] = (digit)(acc >> d);\r
1287 }\r
1288 return carry;\r
1289}\r
1290\r
1291/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient\r
1292 in pout, and returning the remainder. pin and pout point at the LSD.\r
1293 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in\r
1294 _PyLong_Format, but that should be done with great care since longs are\r
1295 immutable. */\r
1296\r
1297static digit\r
1298inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)\r
1299{\r
1300 twodigits rem = 0;\r
1301\r
1302 assert(n > 0 && n <= PyLong_MASK);\r
1303 pin += size;\r
1304 pout += size;\r
1305 while (--size >= 0) {\r
1306 digit hi;\r
1307 rem = (rem << PyLong_SHIFT) | *--pin;\r
1308 *--pout = hi = (digit)(rem / n);\r
1309 rem -= (twodigits)hi * n;\r
1310 }\r
1311 return (digit)rem;\r
1312}\r
1313\r
1314/* Divide a long integer by a digit, returning both the quotient\r
1315 (as function result) and the remainder (through *prem).\r
1316 The sign of a is ignored; n should not be zero. */\r
1317\r
1318static PyLongObject *\r
1319divrem1(PyLongObject *a, digit n, digit *prem)\r
1320{\r
1321 const Py_ssize_t size = ABS(Py_SIZE(a));\r
1322 PyLongObject *z;\r
1323\r
1324 assert(n > 0 && n <= PyLong_MASK);\r
1325 z = _PyLong_New(size);\r
1326 if (z == NULL)\r
1327 return NULL;\r
1328 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);\r
1329 return long_normalize(z);\r
1330}\r
1331\r
1332/* Convert a long integer to a base 10 string. Returns a new non-shared\r
1333 string. (Return value is non-shared so that callers can modify the\r
1334 returned value if necessary.) */\r
1335\r
1336static PyObject *\r
1337long_to_decimal_string(PyObject *aa, int addL)\r
1338{\r
1339 PyLongObject *scratch, *a;\r
1340 PyObject *str;\r
1341 Py_ssize_t size, strlen, size_a, i, j;\r
1342 digit *pout, *pin, rem, tenpow;\r
1343 char *p;\r
1344 int negative;\r
1345\r
1346 a = (PyLongObject *)aa;\r
1347 if (a == NULL || !PyLong_Check(a)) {\r
1348 PyErr_BadInternalCall();\r
1349 return NULL;\r
1350 }\r
1351 size_a = ABS(Py_SIZE(a));\r
1352 negative = Py_SIZE(a) < 0;\r
1353\r
1354 /* quick and dirty upper bound for the number of digits\r
1355 required to express a in base _PyLong_DECIMAL_BASE:\r
1356\r
1357 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))\r
1358\r
1359 But log2(a) < size_a * PyLong_SHIFT, and\r
1360 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT\r
1361 > 3 * _PyLong_DECIMAL_SHIFT\r
1362 */\r
1363 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {\r
1364 PyErr_SetString(PyExc_OverflowError,\r
1365 "long is too large to format");\r
1366 return NULL;\r
1367 }\r
1368 /* the expression size_a * PyLong_SHIFT is now safe from overflow */\r
1369 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);\r
1370 scratch = _PyLong_New(size);\r
1371 if (scratch == NULL)\r
1372 return NULL;\r
1373\r
1374 /* convert array of base _PyLong_BASE digits in pin to an array of\r
1375 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,\r
1376 Volume 2 (3rd edn), section 4.4, Method 1b). */\r
1377 pin = a->ob_digit;\r
1378 pout = scratch->ob_digit;\r
1379 size = 0;\r
1380 for (i = size_a; --i >= 0; ) {\r
1381 digit hi = pin[i];\r
1382 for (j = 0; j < size; j++) {\r
1383 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;\r
1384 hi = (digit)(z / _PyLong_DECIMAL_BASE);\r
1385 pout[j] = (digit)(z - (twodigits)hi *\r
1386 _PyLong_DECIMAL_BASE);\r
1387 }\r
1388 while (hi) {\r
1389 pout[size++] = hi % _PyLong_DECIMAL_BASE;\r
1390 hi /= _PyLong_DECIMAL_BASE;\r
1391 }\r
1392 /* check for keyboard interrupt */\r
1393 SIGCHECK({\r
1394 Py_DECREF(scratch);\r
1395 return NULL;\r
1396 });\r
1397 }\r
1398 /* pout should have at least one digit, so that the case when a = 0\r
1399 works correctly */\r
1400 if (size == 0)\r
1401 pout[size++] = 0;\r
1402\r
1403 /* calculate exact length of output string, and allocate */\r
1404 strlen = (addL != 0) + negative +\r
1405 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;\r
1406 tenpow = 10;\r
1407 rem = pout[size-1];\r
1408 while (rem >= tenpow) {\r
1409 tenpow *= 10;\r
1410 strlen++;\r
1411 }\r
1412 str = PyString_FromStringAndSize(NULL, strlen);\r
1413 if (str == NULL) {\r
1414 Py_DECREF(scratch);\r
1415 return NULL;\r
1416 }\r
1417\r
1418 /* fill the string right-to-left */\r
1419 p = PyString_AS_STRING(str) + strlen;\r
1420 *p = '\0';\r
1421 if (addL)\r
1422 *--p = 'L';\r
1423 /* pout[0] through pout[size-2] contribute exactly\r
1424 _PyLong_DECIMAL_SHIFT digits each */\r
1425 for (i=0; i < size - 1; i++) {\r
1426 rem = pout[i];\r
1427 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {\r
1428 *--p = '0' + rem % 10;\r
1429 rem /= 10;\r
1430 }\r
1431 }\r
1432 /* pout[size-1]: always produce at least one decimal digit */\r
1433 rem = pout[i];\r
1434 do {\r
1435 *--p = '0' + rem % 10;\r
1436 rem /= 10;\r
1437 } while (rem != 0);\r
1438\r
1439 /* and sign */\r
1440 if (negative)\r
1441 *--p = '-';\r
1442\r
1443 /* check we've counted correctly */\r
1444 assert(p == PyString_AS_STRING(str));\r
1445 Py_DECREF(scratch);\r
1446 return (PyObject *)str;\r
1447}\r
1448\r
1449/* Convert the long to a string object with given base,\r
1450 appending a base prefix of 0[box] if base is 2, 8 or 16.\r
1451 Add a trailing "L" if addL is non-zero.\r
1452 If newstyle is zero, then use the pre-2.6 behavior of octal having\r
1453 a leading "0", instead of the prefix "0o" */\r
1454PyAPI_FUNC(PyObject *)\r
1455_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)\r
1456{\r
1457 register PyLongObject *a = (PyLongObject *)aa;\r
1458 PyStringObject *str;\r
1459 Py_ssize_t i, sz;\r
1460 Py_ssize_t size_a;\r
1461 char *p;\r
1462 int bits;\r
1463 char sign = '\0';\r
1464\r
1465 if (base == 10)\r
1466 return long_to_decimal_string((PyObject *)a, addL);\r
1467\r
1468 if (a == NULL || !PyLong_Check(a)) {\r
1469 PyErr_BadInternalCall();\r
1470 return NULL;\r
1471 }\r
1472 assert(base >= 2 && base <= 36);\r
1473 size_a = ABS(Py_SIZE(a));\r
1474\r
1475 /* Compute a rough upper bound for the length of the string */\r
1476 i = base;\r
1477 bits = 0;\r
1478 while (i > 1) {\r
1479 ++bits;\r
1480 i >>= 1;\r
1481 }\r
1482 i = 5 + (addL ? 1 : 0);\r
1483 /* ensure we don't get signed overflow in sz calculation */\r
1484 if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {\r
1485 PyErr_SetString(PyExc_OverflowError,\r
1486 "long is too large to format");\r
1487 return NULL;\r
1488 }\r
1489 sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;\r
1490 assert(sz >= 0);\r
1491 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);\r
1492 if (str == NULL)\r
1493 return NULL;\r
1494 p = PyString_AS_STRING(str) + sz;\r
1495 *p = '\0';\r
1496 if (addL)\r
1497 *--p = 'L';\r
1498 if (a->ob_size < 0)\r
1499 sign = '-';\r
1500\r
1501 if (a->ob_size == 0) {\r
1502 *--p = '0';\r
1503 }\r
1504 else if ((base & (base - 1)) == 0) {\r
1505 /* JRH: special case for power-of-2 bases */\r
1506 twodigits accum = 0;\r
1507 int accumbits = 0; /* # of bits in accum */\r
1508 int basebits = 1; /* # of bits in base-1 */\r
1509 i = base;\r
1510 while ((i >>= 1) > 1)\r
1511 ++basebits;\r
1512\r
1513 for (i = 0; i < size_a; ++i) {\r
1514 accum |= (twodigits)a->ob_digit[i] << accumbits;\r
1515 accumbits += PyLong_SHIFT;\r
1516 assert(accumbits >= basebits);\r
1517 do {\r
1518 char cdigit = (char)(accum & (base - 1));\r
1519 cdigit += (cdigit < 10) ? '0' : 'a'-10;\r
1520 assert(p > PyString_AS_STRING(str));\r
1521 *--p = cdigit;\r
1522 accumbits -= basebits;\r
1523 accum >>= basebits;\r
1524 } while (i < size_a-1 ? accumbits >= basebits : accum > 0);\r
1525 }\r
1526 }\r
1527 else {\r
1528 /* Not 0, and base not a power of 2. Divide repeatedly by\r
1529 base, but for speed use the highest power of base that\r
1530 fits in a digit. */\r
1531 Py_ssize_t size = size_a;\r
1532 digit *pin = a->ob_digit;\r
1533 PyLongObject *scratch;\r
1534 /* powbasw <- largest power of base that fits in a digit. */\r
1535 digit powbase = base; /* powbase == base ** power */\r
1536 int power = 1;\r
1537 for (;;) {\r
1538 twodigits newpow = powbase * (twodigits)base;\r
1539 if (newpow >> PyLong_SHIFT)\r
1540 /* doesn't fit in a digit */\r
1541 break;\r
1542 powbase = (digit)newpow;\r
1543 ++power;\r
1544 }\r
1545\r
1546 /* Get a scratch area for repeated division. */\r
1547 scratch = _PyLong_New(size);\r
1548 if (scratch == NULL) {\r
1549 Py_DECREF(str);\r
1550 return NULL;\r
1551 }\r
1552\r
1553 /* Repeatedly divide by powbase. */\r
1554 do {\r
1555 int ntostore = power;\r
1556 digit rem = inplace_divrem1(scratch->ob_digit,\r
1557 pin, size, powbase);\r
1558 pin = scratch->ob_digit; /* no need to use a again */\r
1559 if (pin[size - 1] == 0)\r
1560 --size;\r
1561 SIGCHECK({\r
1562 Py_DECREF(scratch);\r
1563 Py_DECREF(str);\r
1564 return NULL;\r
1565 });\r
1566\r
1567 /* Break rem into digits. */\r
1568 assert(ntostore > 0);\r
1569 do {\r
1570 digit nextrem = (digit)(rem / base);\r
1571 char c = (char)(rem - nextrem * base);\r
1572 assert(p > PyString_AS_STRING(str));\r
1573 c += (c < 10) ? '0' : 'a'-10;\r
1574 *--p = c;\r
1575 rem = nextrem;\r
1576 --ntostore;\r
1577 /* Termination is a bit delicate: must not\r
1578 store leading zeroes, so must get out if\r
1579 remaining quotient and rem are both 0. */\r
1580 } while (ntostore && (size || rem));\r
1581 } while (size != 0);\r
1582 Py_DECREF(scratch);\r
1583 }\r
1584\r
1585 if (base == 2) {\r
1586 *--p = 'b';\r
1587 *--p = '0';\r
1588 }\r
1589 else if (base == 8) {\r
1590 if (newstyle) {\r
1591 *--p = 'o';\r
1592 *--p = '0';\r
1593 }\r
1594 else\r
1595 if (size_a != 0)\r
1596 *--p = '0';\r
1597 }\r
1598 else if (base == 16) {\r
1599 *--p = 'x';\r
1600 *--p = '0';\r
1601 }\r
1602 else if (base != 10) {\r
1603 *--p = '#';\r
1604 *--p = '0' + base%10;\r
1605 if (base > 10)\r
1606 *--p = '0' + base/10;\r
1607 }\r
1608 if (sign)\r
1609 *--p = sign;\r
1610 if (p != PyString_AS_STRING(str)) {\r
1611 char *q = PyString_AS_STRING(str);\r
1612 assert(p > q);\r
1613 do {\r
1614 } while ((*q++ = *p++) != '\0');\r
1615 q--;\r
1616 _PyString_Resize((PyObject **)&str,\r
1617 (Py_ssize_t) (q - PyString_AS_STRING(str)));\r
1618 }\r
1619 return (PyObject *)str;\r
1620}\r
1621\r
1622/* Table of digit values for 8-bit string -> integer conversion.\r
1623 * '0' maps to 0, ..., '9' maps to 9.\r
1624 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.\r
1625 * All other indices map to 37.\r
1626 * Note that when converting a base B string, a char c is a legitimate\r
1627 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.\r
1628 */\r
1629int _PyLong_DigitValue[256] = {\r
1630 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1631 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1632 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1633 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,\r
1634 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\r
1635 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,\r
1636 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\r
1637 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,\r
1638 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1639 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1640 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1641 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1642 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1643 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1644 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1645 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,\r
1646};\r
1647\r
1648/* *str points to the first digit in a string of base `base` digits. base\r
1649 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first\r
1650 * non-digit (which may be *str!). A normalized long is returned.\r
1651 * The point to this routine is that it takes time linear in the number of\r
1652 * string characters.\r
1653 */\r
1654static PyLongObject *\r
1655long_from_binary_base(char **str, int base)\r
1656{\r
1657 char *p = *str;\r
1658 char *start = p;\r
1659 int bits_per_char;\r
1660 Py_ssize_t n;\r
1661 PyLongObject *z;\r
1662 twodigits accum;\r
1663 int bits_in_accum;\r
1664 digit *pdigit;\r
1665\r
1666 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);\r
1667 n = base;\r
1668 for (bits_per_char = -1; n; ++bits_per_char)\r
1669 n >>= 1;\r
1670 /* n <- total # of bits needed, while setting p to end-of-string */\r
1671 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)\r
1672 ++p;\r
1673 *str = p;\r
1674 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */\r
1675 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;\r
1676 if (n / bits_per_char < p - start) {\r
1677 PyErr_SetString(PyExc_ValueError,\r
1678 "long string too large to convert");\r
1679 return NULL;\r
1680 }\r
1681 n = n / PyLong_SHIFT;\r
1682 z = _PyLong_New(n);\r
1683 if (z == NULL)\r
1684 return NULL;\r
1685 /* Read string from right, and fill in long from left; i.e.,\r
1686 * from least to most significant in both.\r
1687 */\r
1688 accum = 0;\r
1689 bits_in_accum = 0;\r
1690 pdigit = z->ob_digit;\r
1691 while (--p >= start) {\r
1692 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];\r
1693 assert(k >= 0 && k < base);\r
1694 accum |= (twodigits)k << bits_in_accum;\r
1695 bits_in_accum += bits_per_char;\r
1696 if (bits_in_accum >= PyLong_SHIFT) {\r
1697 *pdigit++ = (digit)(accum & PyLong_MASK);\r
1698 assert(pdigit - z->ob_digit <= n);\r
1699 accum >>= PyLong_SHIFT;\r
1700 bits_in_accum -= PyLong_SHIFT;\r
1701 assert(bits_in_accum < PyLong_SHIFT);\r
1702 }\r
1703 }\r
1704 if (bits_in_accum) {\r
1705 assert(bits_in_accum <= PyLong_SHIFT);\r
1706 *pdigit++ = (digit)accum;\r
1707 assert(pdigit - z->ob_digit <= n);\r
1708 }\r
1709 while (pdigit - z->ob_digit < n)\r
1710 *pdigit++ = 0;\r
1711 return long_normalize(z);\r
1712}\r
1713\r
1714PyObject *\r
1715PyLong_FromString(char *str, char **pend, int base)\r
1716{\r
1717 int sign = 1;\r
1718 char *start, *orig_str = str;\r
1719 PyLongObject *z;\r
1720 PyObject *strobj, *strrepr;\r
1721 Py_ssize_t slen;\r
1722\r
1723 if ((base != 0 && base < 2) || base > 36) {\r
1724 PyErr_SetString(PyExc_ValueError,\r
1725 "long() arg 2 must be >= 2 and <= 36");\r
1726 return NULL;\r
1727 }\r
1728 while (*str != '\0' && isspace(Py_CHARMASK(*str)))\r
1729 str++;\r
1730 if (*str == '+')\r
1731 ++str;\r
1732 else if (*str == '-') {\r
1733 ++str;\r
1734 sign = -1;\r
1735 }\r
1736 while (*str != '\0' && isspace(Py_CHARMASK(*str)))\r
1737 str++;\r
1738 if (base == 0) {\r
1739 /* No base given. Deduce the base from the contents\r
1740 of the string */\r
1741 if (str[0] != '0')\r
1742 base = 10;\r
1743 else if (str[1] == 'x' || str[1] == 'X')\r
1744 base = 16;\r
1745 else if (str[1] == 'o' || str[1] == 'O')\r
1746 base = 8;\r
1747 else if (str[1] == 'b' || str[1] == 'B')\r
1748 base = 2;\r
1749 else\r
1750 /* "old" (C-style) octal literal, still valid in\r
1751 2.x, although illegal in 3.x */\r
1752 base = 8;\r
1753 }\r
1754 /* Whether or not we were deducing the base, skip leading chars\r
1755 as needed */\r
1756 if (str[0] == '0' &&\r
1757 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||\r
1758 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||\r
1759 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))\r
1760 str += 2;\r
1761\r
1762 start = str;\r
1763 if ((base & (base - 1)) == 0)\r
1764 z = long_from_binary_base(&str, base);\r
1765 else {\r
1766/***\r
1767Binary bases can be converted in time linear in the number of digits, because\r
1768Python's representation base is binary. Other bases (including decimal!) use\r
1769the simple quadratic-time algorithm below, complicated by some speed tricks.\r
1770\r
1771First some math: the largest integer that can be expressed in N base-B digits\r
1772is B**N-1. Consequently, if we have an N-digit input in base B, the worst-\r
1773case number of Python digits needed to hold it is the smallest integer n s.t.\r
1774\r
1775 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]\r
1776 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]\r
1777 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)\r
1778\r
1779The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so\r
1780we can compute this quickly. A Python long with that much space is reserved\r
1781near the start, and the result is computed into it.\r
1782\r
1783The input string is actually treated as being in base base**i (i.e., i digits\r
1784are processed at a time), where two more static arrays hold:\r
1785\r
1786 convwidth_base[base] = the largest integer i such that\r
1787 base**i <= PyLong_BASE\r
1788 convmultmax_base[base] = base ** convwidth_base[base]\r
1789\r
1790The first of these is the largest i such that i consecutive input digits\r
1791must fit in a single Python digit. The second is effectively the input\r
1792base we're really using.\r
1793\r
1794Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base\r
1795convmultmax_base[base], the result is "simply"\r
1796\r
1797 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1\r
1798\r
1799where B = convmultmax_base[base].\r
1800\r
1801Error analysis: as above, the number of Python digits `n` needed is worst-\r
1802case\r
1803\r
1804 n >= N * log(B)/log(PyLong_BASE)\r
1805\r
1806where `N` is the number of input digits in base `B`. This is computed via\r
1807\r
1808 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;\r
1809\r
1810below. Two numeric concerns are how much space this can waste, and whether\r
1811the computed result can be too small. To be concrete, assume PyLong_BASE =\r
18122**15, which is the default (and it's unlikely anyone changes that).\r
1813\r
1814Waste isn't a problem: provided the first input digit isn't 0, the difference\r
1815between the worst-case input with N digits and the smallest input with N\r
1816digits is about a factor of B, but B is small compared to PyLong_BASE so at\r
1817most one allocated Python digit can remain unused on that count. If\r
1818N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating\r
1819that and adding 1 returns a result 1 larger than necessary. However, that\r
1820can't happen: whenever B is a power of 2, long_from_binary_base() is called\r
1821instead, and it's impossible for B**i to be an integer power of 2**15 when B\r
1822is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be\r
1823an exact integer when B is not a power of 2, since B**i has a prime factor\r
1824other than 2 in that case, but (2**15)**j's only prime factor is 2).\r
1825\r
1826The computed result can be too small if the true value of\r
1827N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but\r
1828due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient,\r
1829and/or multiplying that by N) yields a numeric result a little less than that\r
1830integer. Unfortunately, "how close can a transcendental function get to an\r
1831integer over some range?" questions are generally theoretically intractable.\r
1832Computer analysis via continued fractions is practical: expand\r
1833log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the\r
1834best" rational approximations. Then j*log(B)/log(PyLong_BASE) is\r
1835approximately equal to (the integer) i. This shows that we can get very close\r
1836to being in trouble, but very rarely. For example, 76573 is a denominator in\r
1837one of the continued-fraction approximations to log(10)/log(2**15), and\r
1838indeed:\r
1839\r
1840 >>> log(10)/log(2**15)*76573\r
1841 16958.000000654003\r
1842\r
1843is very close to an integer. If we were working with IEEE single-precision,\r
1844rounding errors could kill us. Finding worst cases in IEEE double-precision\r
1845requires better-than-double-precision log() functions, and Tim didn't bother.\r
1846Instead the code checks to see whether the allocated space is enough as each\r
1847new Python digit is added, and copies the whole thing to a larger long if not.\r
1848This should happen extremely rarely, and in fact I don't have a test case\r
1849that triggers it(!). Instead the code was tested by artificially allocating\r
1850just 1 digit at the start, so that the copying code was exercised for every\r
1851digit beyond the first.\r
1852***/\r
1853 register twodigits c; /* current input character */\r
1854 Py_ssize_t size_z;\r
1855 int i;\r
1856 int convwidth;\r
1857 twodigits convmultmax, convmult;\r
1858 digit *pz, *pzstop;\r
1859 char* scan;\r
1860\r
1861 static double log_base_PyLong_BASE[37] = {0.0e0,};\r
1862 static int convwidth_base[37] = {0,};\r
1863 static twodigits convmultmax_base[37] = {0,};\r
1864\r
1865 if (log_base_PyLong_BASE[base] == 0.0) {\r
1866 twodigits convmax = base;\r
1867 int i = 1;\r
1868\r
1869 log_base_PyLong_BASE[base] = (log((double)base) /\r
1870 log((double)PyLong_BASE));\r
1871 for (;;) {\r
1872 twodigits next = convmax * base;\r
1873 if (next > PyLong_BASE)\r
1874 break;\r
1875 convmax = next;\r
1876 ++i;\r
1877 }\r
1878 convmultmax_base[base] = convmax;\r
1879 assert(i > 0);\r
1880 convwidth_base[base] = i;\r
1881 }\r
1882\r
1883 /* Find length of the string of numeric characters. */\r
1884 scan = str;\r
1885 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)\r
1886 ++scan;\r
1887\r
1888 /* Create a long object that can contain the largest possible\r
1889 * integer with this base and length. Note that there's no\r
1890 * need to initialize z->ob_digit -- no slot is read up before\r
1891 * being stored into.\r
1892 */\r
1893 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;\r
1894 /* Uncomment next line to test exceedingly rare copy code */\r
1895 /* size_z = 1; */\r
1896 assert(size_z > 0);\r
1897 z = _PyLong_New(size_z);\r
1898 if (z == NULL)\r
1899 return NULL;\r
1900 Py_SIZE(z) = 0;\r
1901\r
1902 /* `convwidth` consecutive input digits are treated as a single\r
1903 * digit in base `convmultmax`.\r
1904 */\r
1905 convwidth = convwidth_base[base];\r
1906 convmultmax = convmultmax_base[base];\r
1907\r
1908 /* Work ;-) */\r
1909 while (str < scan) {\r
1910 /* grab up to convwidth digits from the input string */\r
1911 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];\r
1912 for (i = 1; i < convwidth && str != scan; ++i, ++str) {\r
1913 c = (twodigits)(c * base +\r
1914 _PyLong_DigitValue[Py_CHARMASK(*str)]);\r
1915 assert(c < PyLong_BASE);\r
1916 }\r
1917\r
1918 convmult = convmultmax;\r
1919 /* Calculate the shift only if we couldn't get\r
1920 * convwidth digits.\r
1921 */\r
1922 if (i != convwidth) {\r
1923 convmult = base;\r
1924 for ( ; i > 1; --i)\r
1925 convmult *= base;\r
1926 }\r
1927\r
1928 /* Multiply z by convmult, and add c. */\r
1929 pz = z->ob_digit;\r
1930 pzstop = pz + Py_SIZE(z);\r
1931 for (; pz < pzstop; ++pz) {\r
1932 c += (twodigits)*pz * convmult;\r
1933 *pz = (digit)(c & PyLong_MASK);\r
1934 c >>= PyLong_SHIFT;\r
1935 }\r
1936 /* carry off the current end? */\r
1937 if (c) {\r
1938 assert(c < PyLong_BASE);\r
1939 if (Py_SIZE(z) < size_z) {\r
1940 *pz = (digit)c;\r
1941 ++Py_SIZE(z);\r
1942 }\r
1943 else {\r
1944 PyLongObject *tmp;\r
1945 /* Extremely rare. Get more space. */\r
1946 assert(Py_SIZE(z) == size_z);\r
1947 tmp = _PyLong_New(size_z + 1);\r
1948 if (tmp == NULL) {\r
1949 Py_DECREF(z);\r
1950 return NULL;\r
1951 }\r
1952 memcpy(tmp->ob_digit,\r
1953 z->ob_digit,\r
1954 sizeof(digit) * size_z);\r
1955 Py_DECREF(z);\r
1956 z = tmp;\r
1957 z->ob_digit[size_z] = (digit)c;\r
1958 ++size_z;\r
1959 }\r
1960 }\r
1961 }\r
1962 }\r
1963 if (z == NULL)\r
1964 return NULL;\r
1965 if (str == start)\r
1966 goto onError;\r
1967 if (sign < 0)\r
1968 Py_SIZE(z) = -(Py_SIZE(z));\r
1969 if (*str == 'L' || *str == 'l')\r
1970 str++;\r
1971 while (*str && isspace(Py_CHARMASK(*str)))\r
1972 str++;\r
1973 if (*str != '\0')\r
1974 goto onError;\r
1975 if (pend)\r
1976 *pend = str;\r
1977 return (PyObject *) z;\r
1978\r
1979 onError:\r
1980 Py_XDECREF(z);\r
1981 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;\r
1982 strobj = PyString_FromStringAndSize(orig_str, slen);\r
1983 if (strobj == NULL)\r
1984 return NULL;\r
1985 strrepr = PyObject_Repr(strobj);\r
1986 Py_DECREF(strobj);\r
1987 if (strrepr == NULL)\r
1988 return NULL;\r
1989 PyErr_Format(PyExc_ValueError,\r
1990 "invalid literal for long() with base %d: %s",\r
1991 base, PyString_AS_STRING(strrepr));\r
1992 Py_DECREF(strrepr);\r
1993 return NULL;\r
1994}\r
1995\r
1996#ifdef Py_USING_UNICODE\r
1997PyObject *\r
1998PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)\r
1999{\r
2000 PyObject *result;\r
2001 char *buffer = (char *)PyMem_MALLOC(length+1);\r
2002\r
2003 if (buffer == NULL)\r
2004 return NULL;\r
2005\r
2006 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {\r
2007 PyMem_FREE(buffer);\r
2008 return NULL;\r
2009 }\r
2010 result = PyLong_FromString(buffer, NULL, base);\r
2011 PyMem_FREE(buffer);\r
2012 return result;\r
2013}\r
2014#endif\r
2015\r
2016/* forward */\r
2017static PyLongObject *x_divrem\r
2018 (PyLongObject *, PyLongObject *, PyLongObject **);\r
2019static PyObject *long_long(PyObject *v);\r
2020\r
2021/* Long division with remainder, top-level routine */\r
2022\r
2023static int\r
2024long_divrem(PyLongObject *a, PyLongObject *b,\r
2025 PyLongObject **pdiv, PyLongObject **prem)\r
2026{\r
2027 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
2028 PyLongObject *z;\r
2029\r
2030 if (size_b == 0) {\r
2031 PyErr_SetString(PyExc_ZeroDivisionError,\r
2032 "long division or modulo by zero");\r
2033 return -1;\r
2034 }\r
2035 if (size_a < size_b ||\r
2036 (size_a == size_b &&\r
2037 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {\r
2038 /* |a| < |b|. */\r
2039 *pdiv = _PyLong_New(0);\r
2040 if (*pdiv == NULL)\r
2041 return -1;\r
2042 Py_INCREF(a);\r
2043 *prem = (PyLongObject *) a;\r
2044 return 0;\r
2045 }\r
2046 if (size_b == 1) {\r
2047 digit rem = 0;\r
2048 z = divrem1(a, b->ob_digit[0], &rem);\r
2049 if (z == NULL)\r
2050 return -1;\r
2051 *prem = (PyLongObject *) PyLong_FromLong((long)rem);\r
2052 if (*prem == NULL) {\r
2053 Py_DECREF(z);\r
2054 return -1;\r
2055 }\r
2056 }\r
2057 else {\r
2058 z = x_divrem(a, b, prem);\r
2059 if (z == NULL)\r
2060 return -1;\r
2061 }\r
2062 /* Set the signs.\r
2063 The quotient z has the sign of a*b;\r
2064 the remainder r has the sign of a,\r
2065 so a = b*z + r. */\r
2066 if ((a->ob_size < 0) != (b->ob_size < 0))\r
2067 z->ob_size = -(z->ob_size);\r
2068 if (a->ob_size < 0 && (*prem)->ob_size != 0)\r
2069 (*prem)->ob_size = -((*prem)->ob_size);\r
2070 *pdiv = z;\r
2071 return 0;\r
2072}\r
2073\r
2074/* Unsigned long division with remainder -- the algorithm. The arguments v1\r
2075 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */\r
2076\r
2077static PyLongObject *\r
2078x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)\r
2079{\r
2080 PyLongObject *v, *w, *a;\r
2081 Py_ssize_t i, k, size_v, size_w;\r
2082 int d;\r
2083 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;\r
2084 twodigits vv;\r
2085 sdigit zhi;\r
2086 stwodigits z;\r
2087\r
2088 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd\r
2089 edn.), section 4.3.1, Algorithm D], except that we don't explicitly\r
2090 handle the special case when the initial estimate q for a quotient\r
2091 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and\r
2092 that won't overflow a digit. */\r
2093\r
2094 /* allocate space; w will also be used to hold the final remainder */\r
2095 size_v = ABS(Py_SIZE(v1));\r
2096 size_w = ABS(Py_SIZE(w1));\r
2097 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */\r
2098 v = _PyLong_New(size_v+1);\r
2099 if (v == NULL) {\r
2100 *prem = NULL;\r
2101 return NULL;\r
2102 }\r
2103 w = _PyLong_New(size_w);\r
2104 if (w == NULL) {\r
2105 Py_DECREF(v);\r
2106 *prem = NULL;\r
2107 return NULL;\r
2108 }\r
2109\r
2110 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.\r
2111 shift v1 left by the same amount. Results go into w and v. */\r
2112 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);\r
2113 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);\r
2114 assert(carry == 0);\r
2115 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);\r
2116 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {\r
2117 v->ob_digit[size_v] = carry;\r
2118 size_v++;\r
2119 }\r
2120\r
2121 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has\r
2122 at most (and usually exactly) k = size_v - size_w digits. */\r
2123 k = size_v - size_w;\r
2124 assert(k >= 0);\r
2125 a = _PyLong_New(k);\r
2126 if (a == NULL) {\r
2127 Py_DECREF(w);\r
2128 Py_DECREF(v);\r
2129 *prem = NULL;\r
2130 return NULL;\r
2131 }\r
2132 v0 = v->ob_digit;\r
2133 w0 = w->ob_digit;\r
2134 wm1 = w0[size_w-1];\r
2135 wm2 = w0[size_w-2];\r
2136 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {\r
2137 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving\r
2138 single-digit quotient q, remainder in vk[0:size_w]. */\r
2139\r
2140 SIGCHECK({\r
2141 Py_DECREF(a);\r
2142 Py_DECREF(w);\r
2143 Py_DECREF(v);\r
2144 *prem = NULL;\r
2145 return NULL;\r
2146 });\r
2147\r
2148 /* estimate quotient digit q; may overestimate by 1 (rare) */\r
2149 vtop = vk[size_w];\r
2150 assert(vtop <= wm1);\r
2151 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];\r
2152 q = (digit)(vv / wm1);\r
2153 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */\r
2154 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)\r
2155 | vk[size_w-2])) {\r
2156 --q;\r
2157 r += wm1;\r
2158 if (r >= PyLong_BASE)\r
2159 break;\r
2160 }\r
2161 assert(q <= PyLong_BASE);\r
2162\r
2163 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */\r
2164 zhi = 0;\r
2165 for (i = 0; i < size_w; ++i) {\r
2166 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;\r
2167 -PyLong_BASE * q <= z < PyLong_BASE */\r
2168 z = (sdigit)vk[i] + zhi -\r
2169 (stwodigits)q * (stwodigits)w0[i];\r
2170 vk[i] = (digit)z & PyLong_MASK;\r
2171 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,\r
2172 z, PyLong_SHIFT);\r
2173 }\r
2174\r
2175 /* add w back if q was too large (this branch taken rarely) */\r
2176 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);\r
2177 if ((sdigit)vtop + zhi < 0) {\r
2178 carry = 0;\r
2179 for (i = 0; i < size_w; ++i) {\r
2180 carry += vk[i] + w0[i];\r
2181 vk[i] = carry & PyLong_MASK;\r
2182 carry >>= PyLong_SHIFT;\r
2183 }\r
2184 --q;\r
2185 }\r
2186\r
2187 /* store quotient digit */\r
2188 assert(q < PyLong_BASE);\r
2189 *--ak = q;\r
2190 }\r
2191\r
2192 /* unshift remainder; we reuse w to store the result */\r
2193 carry = v_rshift(w0, v0, size_w, d);\r
2194 assert(carry==0);\r
2195 Py_DECREF(v);\r
2196\r
2197 *prem = long_normalize(w);\r
2198 return long_normalize(a);\r
2199}\r
2200\r
2201/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=\r
2202 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is\r
2203 rounded to DBL_MANT_DIG significant bits using round-half-to-even.\r
2204 If a == 0, return 0.0 and set *e = 0. If the resulting exponent\r
2205 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return\r
2206 -1.0. */\r
2207\r
2208/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */\r
2209#if DBL_MANT_DIG == 53\r
2210#define EXP2_DBL_MANT_DIG 9007199254740992.0\r
2211#else\r
2212#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))\r
2213#endif\r
2214\r
2215double\r
2216_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)\r
2217{\r
2218 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;\r
2219 /* See below for why x_digits is always large enough. */\r
2220 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];\r
2221 double dx;\r
2222 /* Correction term for round-half-to-even rounding. For a digit x,\r
2223 "x + half_even_correction[x & 7]" gives x rounded to the nearest\r
2224 multiple of 4, rounding ties to a multiple of 8. */\r
2225 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};\r
2226\r
2227 a_size = ABS(Py_SIZE(a));\r
2228 if (a_size == 0) {\r
2229 /* Special case for 0: significand 0.0, exponent 0. */\r
2230 *e = 0;\r
2231 return 0.0;\r
2232 }\r
2233 a_bits = bits_in_digit(a->ob_digit[a_size-1]);\r
2234 /* The following is an overflow-free version of the check\r
2235 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */\r
2236 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&\r
2237 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||\r
2238 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))\r
2239 goto overflow;\r
2240 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;\r
2241\r
2242 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]\r
2243 (shifting left if a_bits <= DBL_MANT_DIG + 2).\r
2244\r
2245 Number of digits needed for result: write // for floor division.\r
2246 Then if shifting left, we end up using\r
2247\r
2248 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT\r
2249\r
2250 digits. If shifting right, we use\r
2251\r
2252 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT\r
2253\r
2254 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with\r
2255 the inequalities\r
2256\r
2257 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT\r
2258 m // PyLong_SHIFT - n // PyLong_SHIFT <=\r
2259 1 + (m - n - 1) // PyLong_SHIFT,\r
2260\r
2261 valid for any integers m and n, we find that x_size satisfies\r
2262\r
2263 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT\r
2264\r
2265 in both cases.\r
2266 */\r
2267 if (a_bits <= DBL_MANT_DIG + 2) {\r
2268 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;\r
2269 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;\r
2270 x_size = 0;\r
2271 while (x_size < shift_digits)\r
2272 x_digits[x_size++] = 0;\r
2273 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,\r
2274 (int)shift_bits);\r
2275 x_size += a_size;\r
2276 x_digits[x_size++] = rem;\r
2277 }\r
2278 else {\r
2279 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;\r
2280 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;\r
2281 rem = v_rshift(x_digits, a->ob_digit + shift_digits,\r
2282 a_size - shift_digits, (int)shift_bits);\r
2283 x_size = a_size - shift_digits;\r
2284 /* For correct rounding below, we need the least significant\r
2285 bit of x to be 'sticky' for this shift: if any of the bits\r
2286 shifted out was nonzero, we set the least significant bit\r
2287 of x. */\r
2288 if (rem)\r
2289 x_digits[0] |= 1;\r
2290 else\r
2291 while (shift_digits > 0)\r
2292 if (a->ob_digit[--shift_digits]) {\r
2293 x_digits[0] |= 1;\r
2294 break;\r
2295 }\r
2296 }\r
2297 assert(1 <= x_size &&\r
2298 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));\r
2299\r
2300 /* Round, and convert to double. */\r
2301 x_digits[0] += half_even_correction[x_digits[0] & 7];\r
2302 dx = x_digits[--x_size];\r
2303 while (x_size > 0)\r
2304 dx = dx * PyLong_BASE + x_digits[--x_size];\r
2305\r
2306 /* Rescale; make correction if result is 1.0. */\r
2307 dx /= 4.0 * EXP2_DBL_MANT_DIG;\r
2308 if (dx == 1.0) {\r
2309 if (a_bits == PY_SSIZE_T_MAX)\r
2310 goto overflow;\r
2311 dx = 0.5;\r
2312 a_bits += 1;\r
2313 }\r
2314\r
2315 *e = a_bits;\r
2316 return Py_SIZE(a) < 0 ? -dx : dx;\r
2317\r
2318 overflow:\r
2319 /* exponent > PY_SSIZE_T_MAX */\r
2320 PyErr_SetString(PyExc_OverflowError,\r
2321 "huge integer: number of bits overflows a Py_ssize_t");\r
2322 *e = 0;\r
2323 return -1.0;\r
2324}\r
2325\r
2326/* Get a C double from a long int object. Rounds to the nearest double,\r
2327 using the round-half-to-even rule in the case of a tie. */\r
2328\r
2329double\r
2330PyLong_AsDouble(PyObject *v)\r
2331{\r
2332 Py_ssize_t exponent;\r
2333 double x;\r
2334\r
2335 if (v == NULL || !PyLong_Check(v)) {\r
2336 PyErr_BadInternalCall();\r
2337 return -1.0;\r
2338 }\r
2339 x = _PyLong_Frexp((PyLongObject *)v, &exponent);\r
2340 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {\r
2341 PyErr_SetString(PyExc_OverflowError,\r
2342 "long int too large to convert to float");\r
2343 return -1.0;\r
2344 }\r
2345 return ldexp(x, (int)exponent);\r
2346}\r
2347\r
2348/* Methods */\r
2349\r
2350static void\r
2351long_dealloc(PyObject *v)\r
2352{\r
2353 Py_TYPE(v)->tp_free(v);\r
2354}\r
2355\r
2356static PyObject *\r
2357long_repr(PyObject *v)\r
2358{\r
2359 return _PyLong_Format(v, 10, 1, 0);\r
2360}\r
2361\r
2362static PyObject *\r
2363long_str(PyObject *v)\r
2364{\r
2365 return _PyLong_Format(v, 10, 0, 0);\r
2366}\r
2367\r
2368static int\r
2369long_compare(PyLongObject *a, PyLongObject *b)\r
2370{\r
2371 Py_ssize_t sign;\r
2372\r
2373 if (Py_SIZE(a) != Py_SIZE(b)) {\r
2374 sign = Py_SIZE(a) - Py_SIZE(b);\r
2375 }\r
2376 else {\r
2377 Py_ssize_t i = ABS(Py_SIZE(a));\r
2378 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])\r
2379 ;\r
2380 if (i < 0)\r
2381 sign = 0;\r
2382 else {\r
2383 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];\r
2384 if (Py_SIZE(a) < 0)\r
2385 sign = -sign;\r
2386 }\r
2387 }\r
2388 return sign < 0 ? -1 : sign > 0 ? 1 : 0;\r
2389}\r
2390\r
2391static long\r
2392long_hash(PyLongObject *v)\r
2393{\r
2394 unsigned long x;\r
2395 Py_ssize_t i;\r
2396 int sign;\r
2397\r
2398 /* This is designed so that Python ints and longs with the\r
2399 same value hash to the same value, otherwise comparisons\r
2400 of mapping keys will turn out weird */\r
2401 i = v->ob_size;\r
2402 sign = 1;\r
2403 x = 0;\r
2404 if (i < 0) {\r
2405 sign = -1;\r
2406 i = -(i);\r
2407 }\r
2408 /* The following loop produces a C unsigned long x such that x is\r
2409 congruent to the absolute value of v modulo ULONG_MAX. The\r
2410 resulting x is nonzero if and only if v is. */\r
2411 while (--i >= 0) {\r
2412 /* Force a native long #-bits (32 or 64) circular shift */\r
2413 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);\r
2414 x += v->ob_digit[i];\r
2415 /* If the addition above overflowed we compensate by\r
2416 incrementing. This preserves the value modulo\r
2417 ULONG_MAX. */\r
2418 if (x < v->ob_digit[i])\r
2419 x++;\r
2420 }\r
2421 x = x * sign;\r
2422 if (x == (unsigned long)-1)\r
2423 x = (unsigned long)-2;\r
2424 return (long)x;\r
2425}\r
2426\r
2427\r
2428/* Add the absolute values of two long integers. */\r
2429\r
2430static PyLongObject *\r
2431x_add(PyLongObject *a, PyLongObject *b)\r
2432{\r
2433 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
2434 PyLongObject *z;\r
2435 Py_ssize_t i;\r
2436 digit carry = 0;\r
2437\r
2438 /* Ensure a is the larger of the two: */\r
2439 if (size_a < size_b) {\r
2440 { PyLongObject *temp = a; a = b; b = temp; }\r
2441 { Py_ssize_t size_temp = size_a;\r
2442 size_a = size_b;\r
2443 size_b = size_temp; }\r
2444 }\r
2445 z = _PyLong_New(size_a+1);\r
2446 if (z == NULL)\r
2447 return NULL;\r
2448 for (i = 0; i < size_b; ++i) {\r
2449 carry += a->ob_digit[i] + b->ob_digit[i];\r
2450 z->ob_digit[i] = carry & PyLong_MASK;\r
2451 carry >>= PyLong_SHIFT;\r
2452 }\r
2453 for (; i < size_a; ++i) {\r
2454 carry += a->ob_digit[i];\r
2455 z->ob_digit[i] = carry & PyLong_MASK;\r
2456 carry >>= PyLong_SHIFT;\r
2457 }\r
2458 z->ob_digit[i] = carry;\r
2459 return long_normalize(z);\r
2460}\r
2461\r
2462/* Subtract the absolute values of two integers. */\r
2463\r
2464static PyLongObject *\r
2465x_sub(PyLongObject *a, PyLongObject *b)\r
2466{\r
2467 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));\r
2468 PyLongObject *z;\r
2469 Py_ssize_t i;\r
2470 int sign = 1;\r
2471 digit borrow = 0;\r
2472\r
2473 /* Ensure a is the larger of the two: */\r
2474 if (size_a < size_b) {\r
2475 sign = -1;\r
2476 { PyLongObject *temp = a; a = b; b = temp; }\r
2477 { Py_ssize_t size_temp = size_a;\r
2478 size_a = size_b;\r
2479 size_b = size_temp; }\r
2480 }\r
2481 else if (size_a == size_b) {\r
2482 /* Find highest digit where a and b differ: */\r
2483 i = size_a;\r
2484 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])\r
2485 ;\r
2486 if (i < 0)\r
2487 return _PyLong_New(0);\r
2488 if (a->ob_digit[i] < b->ob_digit[i]) {\r
2489 sign = -1;\r
2490 { PyLongObject *temp = a; a = b; b = temp; }\r
2491 }\r
2492 size_a = size_b = i+1;\r
2493 }\r
2494 z = _PyLong_New(size_a);\r
2495 if (z == NULL)\r
2496 return NULL;\r
2497 for (i = 0; i < size_b; ++i) {\r
2498 /* The following assumes unsigned arithmetic\r
2499 works module 2**N for some N>PyLong_SHIFT. */\r
2500 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;\r
2501 z->ob_digit[i] = borrow & PyLong_MASK;\r
2502 borrow >>= PyLong_SHIFT;\r
2503 borrow &= 1; /* Keep only one sign bit */\r
2504 }\r
2505 for (; i < size_a; ++i) {\r
2506 borrow = a->ob_digit[i] - borrow;\r
2507 z->ob_digit[i] = borrow & PyLong_MASK;\r
2508 borrow >>= PyLong_SHIFT;\r
2509 borrow &= 1; /* Keep only one sign bit */\r
2510 }\r
2511 assert(borrow == 0);\r
2512 if (sign < 0)\r
2513 z->ob_size = -(z->ob_size);\r
2514 return long_normalize(z);\r
2515}\r
2516\r
2517static PyObject *\r
2518long_add(PyLongObject *v, PyLongObject *w)\r
2519{\r
2520 PyLongObject *a, *b, *z;\r
2521\r
2522 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
2523\r
2524 if (a->ob_size < 0) {\r
2525 if (b->ob_size < 0) {\r
2526 z = x_add(a, b);\r
2527 if (z != NULL && z->ob_size != 0)\r
2528 z->ob_size = -(z->ob_size);\r
2529 }\r
2530 else\r
2531 z = x_sub(b, a);\r
2532 }\r
2533 else {\r
2534 if (b->ob_size < 0)\r
2535 z = x_sub(a, b);\r
2536 else\r
2537 z = x_add(a, b);\r
2538 }\r
2539 Py_DECREF(a);\r
2540 Py_DECREF(b);\r
2541 return (PyObject *)z;\r
2542}\r
2543\r
2544static PyObject *\r
2545long_sub(PyLongObject *v, PyLongObject *w)\r
2546{\r
2547 PyLongObject *a, *b, *z;\r
2548\r
2549 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
2550\r
2551 if (a->ob_size < 0) {\r
2552 if (b->ob_size < 0)\r
2553 z = x_sub(a, b);\r
2554 else\r
2555 z = x_add(a, b);\r
2556 if (z != NULL && z->ob_size != 0)\r
2557 z->ob_size = -(z->ob_size);\r
2558 }\r
2559 else {\r
2560 if (b->ob_size < 0)\r
2561 z = x_add(a, b);\r
2562 else\r
2563 z = x_sub(a, b);\r
2564 }\r
2565 Py_DECREF(a);\r
2566 Py_DECREF(b);\r
2567 return (PyObject *)z;\r
2568}\r
2569\r
2570/* Grade school multiplication, ignoring the signs.\r
2571 * Returns the absolute value of the product, or NULL if error.\r
2572 */\r
2573static PyLongObject *\r
2574x_mul(PyLongObject *a, PyLongObject *b)\r
2575{\r
2576 PyLongObject *z;\r
2577 Py_ssize_t size_a = ABS(Py_SIZE(a));\r
2578 Py_ssize_t size_b = ABS(Py_SIZE(b));\r
2579 Py_ssize_t i;\r
2580\r
2581 z = _PyLong_New(size_a + size_b);\r
2582 if (z == NULL)\r
2583 return NULL;\r
2584\r
2585 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));\r
2586 if (a == b) {\r
2587 /* Efficient squaring per HAC, Algorithm 14.16:\r
2588 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf\r
2589 * Gives slightly less than a 2x speedup when a == b,\r
2590 * via exploiting that each entry in the multiplication\r
2591 * pyramid appears twice (except for the size_a squares).\r
2592 */\r
2593 for (i = 0; i < size_a; ++i) {\r
2594 twodigits carry;\r
2595 twodigits f = a->ob_digit[i];\r
2596 digit *pz = z->ob_digit + (i << 1);\r
2597 digit *pa = a->ob_digit + i + 1;\r
2598 digit *paend = a->ob_digit + size_a;\r
2599\r
2600 SIGCHECK({\r
2601 Py_DECREF(z);\r
2602 return NULL;\r
2603 });\r
2604\r
2605 carry = *pz + f * f;\r
2606 *pz++ = (digit)(carry & PyLong_MASK);\r
2607 carry >>= PyLong_SHIFT;\r
2608 assert(carry <= PyLong_MASK);\r
2609\r
2610 /* Now f is added in twice in each column of the\r
2611 * pyramid it appears. Same as adding f<<1 once.\r
2612 */\r
2613 f <<= 1;\r
2614 while (pa < paend) {\r
2615 carry += *pz + *pa++ * f;\r
2616 *pz++ = (digit)(carry & PyLong_MASK);\r
2617 carry >>= PyLong_SHIFT;\r
2618 assert(carry <= (PyLong_MASK << 1));\r
2619 }\r
2620 if (carry) {\r
2621 carry += *pz;\r
2622 *pz++ = (digit)(carry & PyLong_MASK);\r
2623 carry >>= PyLong_SHIFT;\r
2624 }\r
2625 if (carry)\r
2626 *pz += (digit)(carry & PyLong_MASK);\r
2627 assert((carry >> PyLong_SHIFT) == 0);\r
2628 }\r
2629 }\r
2630 else { /* a is not the same as b -- gradeschool long mult */\r
2631 for (i = 0; i < size_a; ++i) {\r
2632 twodigits carry = 0;\r
2633 twodigits f = a->ob_digit[i];\r
2634 digit *pz = z->ob_digit + i;\r
2635 digit *pb = b->ob_digit;\r
2636 digit *pbend = b->ob_digit + size_b;\r
2637\r
2638 SIGCHECK({\r
2639 Py_DECREF(z);\r
2640 return NULL;\r
2641 });\r
2642\r
2643 while (pb < pbend) {\r
2644 carry += *pz + *pb++ * f;\r
2645 *pz++ = (digit)(carry & PyLong_MASK);\r
2646 carry >>= PyLong_SHIFT;\r
2647 assert(carry <= PyLong_MASK);\r
2648 }\r
2649 if (carry)\r
2650 *pz += (digit)(carry & PyLong_MASK);\r
2651 assert((carry >> PyLong_SHIFT) == 0);\r
2652 }\r
2653 }\r
2654 return long_normalize(z);\r
2655}\r
2656\r
2657/* A helper for Karatsuba multiplication (k_mul).\r
2658 Takes a long "n" and an integer "size" representing the place to\r
2659 split, and sets low and high such that abs(n) == (high << size) + low,\r
2660 viewing the shift as being by digits. The sign bit is ignored, and\r
2661 the return values are >= 0.\r
2662 Returns 0 on success, -1 on failure.\r
2663*/\r
2664static int\r
2665kmul_split(PyLongObject *n,\r
2666 Py_ssize_t size,\r
2667 PyLongObject **high,\r
2668 PyLongObject **low)\r
2669{\r
2670 PyLongObject *hi, *lo;\r
2671 Py_ssize_t size_lo, size_hi;\r
2672 const Py_ssize_t size_n = ABS(Py_SIZE(n));\r
2673\r
2674 size_lo = MIN(size_n, size);\r
2675 size_hi = size_n - size_lo;\r
2676\r
2677 if ((hi = _PyLong_New(size_hi)) == NULL)\r
2678 return -1;\r
2679 if ((lo = _PyLong_New(size_lo)) == NULL) {\r
2680 Py_DECREF(hi);\r
2681 return -1;\r
2682 }\r
2683\r
2684 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));\r
2685 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));\r
2686\r
2687 *high = long_normalize(hi);\r
2688 *low = long_normalize(lo);\r
2689 return 0;\r
2690}\r
2691\r
2692static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);\r
2693\r
2694/* Karatsuba multiplication. Ignores the input signs, and returns the\r
2695 * absolute value of the product (or NULL if error).\r
2696 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).\r
2697 */\r
2698static PyLongObject *\r
2699k_mul(PyLongObject *a, PyLongObject *b)\r
2700{\r
2701 Py_ssize_t asize = ABS(Py_SIZE(a));\r
2702 Py_ssize_t bsize = ABS(Py_SIZE(b));\r
2703 PyLongObject *ah = NULL;\r
2704 PyLongObject *al = NULL;\r
2705 PyLongObject *bh = NULL;\r
2706 PyLongObject *bl = NULL;\r
2707 PyLongObject *ret = NULL;\r
2708 PyLongObject *t1, *t2, *t3;\r
2709 Py_ssize_t shift; /* the number of digits we split off */\r
2710 Py_ssize_t i;\r
2711\r
2712 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl\r
2713 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl\r
2714 * Then the original product is\r
2715 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl\r
2716 * By picking X to be a power of 2, "*X" is just shifting, and it's\r
2717 * been reduced to 3 multiplies on numbers half the size.\r
2718 */\r
2719\r
2720 /* We want to split based on the larger number; fiddle so that b\r
2721 * is largest.\r
2722 */\r
2723 if (asize > bsize) {\r
2724 t1 = a;\r
2725 a = b;\r
2726 b = t1;\r
2727\r
2728 i = asize;\r
2729 asize = bsize;\r
2730 bsize = i;\r
2731 }\r
2732\r
2733 /* Use gradeschool math when either number is too small. */\r
2734 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;\r
2735 if (asize <= i) {\r
2736 if (asize == 0)\r
2737 return _PyLong_New(0);\r
2738 else\r
2739 return x_mul(a, b);\r
2740 }\r
2741\r
2742 /* If a is small compared to b, splitting on b gives a degenerate\r
2743 * case with ah==0, and Karatsuba may be (even much) less efficient\r
2744 * than "grade school" then. However, we can still win, by viewing\r
2745 * b as a string of "big digits", each of width a->ob_size. That\r
2746 * leads to a sequence of balanced calls to k_mul.\r
2747 */\r
2748 if (2 * asize <= bsize)\r
2749 return k_lopsided_mul(a, b);\r
2750\r
2751 /* Split a & b into hi & lo pieces. */\r
2752 shift = bsize >> 1;\r
2753 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;\r
2754 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */\r
2755\r
2756 if (a == b) {\r
2757 bh = ah;\r
2758 bl = al;\r
2759 Py_INCREF(bh);\r
2760 Py_INCREF(bl);\r
2761 }\r
2762 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;\r
2763\r
2764 /* The plan:\r
2765 * 1. Allocate result space (asize + bsize digits: that's always\r
2766 * enough).\r
2767 * 2. Compute ah*bh, and copy into result at 2*shift.\r
2768 * 3. Compute al*bl, and copy into result at 0. Note that this\r
2769 * can't overlap with #2.\r
2770 * 4. Subtract al*bl from the result, starting at shift. This may\r
2771 * underflow (borrow out of the high digit), but we don't care:\r
2772 * we're effectively doing unsigned arithmetic mod\r
2773 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,\r
2774 * borrows and carries out of the high digit can be ignored.\r
2775 * 5. Subtract ah*bh from the result, starting at shift.\r
2776 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting\r
2777 * at shift.\r
2778 */\r
2779\r
2780 /* 1. Allocate result space. */\r
2781 ret = _PyLong_New(asize + bsize);\r
2782 if (ret == NULL) goto fail;\r
2783#ifdef Py_DEBUG\r
2784 /* Fill with trash, to catch reference to uninitialized digits. */\r
2785 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));\r
2786#endif\r
2787\r
2788 /* 2. t1 <- ah*bh, and copy into high digits of result. */\r
2789 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;\r
2790 assert(Py_SIZE(t1) >= 0);\r
2791 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));\r
2792 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,\r
2793 Py_SIZE(t1) * sizeof(digit));\r
2794\r
2795 /* Zero-out the digits higher than the ah*bh copy. */\r
2796 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);\r
2797 if (i)\r
2798 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,\r
2799 i * sizeof(digit));\r
2800\r
2801 /* 3. t2 <- al*bl, and copy into the low digits. */\r
2802 if ((t2 = k_mul(al, bl)) == NULL) {\r
2803 Py_DECREF(t1);\r
2804 goto fail;\r
2805 }\r
2806 assert(Py_SIZE(t2) >= 0);\r
2807 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */\r
2808 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));\r
2809\r
2810 /* Zero out remaining digits. */\r
2811 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */\r
2812 if (i)\r
2813 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));\r
2814\r
2815 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first\r
2816 * because it's fresher in cache.\r
2817 */\r
2818 i = Py_SIZE(ret) - shift; /* # digits after shift */\r
2819 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));\r
2820 Py_DECREF(t2);\r
2821\r
2822 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));\r
2823 Py_DECREF(t1);\r
2824\r
2825 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */\r
2826 if ((t1 = x_add(ah, al)) == NULL) goto fail;\r
2827 Py_DECREF(ah);\r
2828 Py_DECREF(al);\r
2829 ah = al = NULL;\r
2830\r
2831 if (a == b) {\r
2832 t2 = t1;\r
2833 Py_INCREF(t2);\r
2834 }\r
2835 else if ((t2 = x_add(bh, bl)) == NULL) {\r
2836 Py_DECREF(t1);\r
2837 goto fail;\r
2838 }\r
2839 Py_DECREF(bh);\r
2840 Py_DECREF(bl);\r
2841 bh = bl = NULL;\r
2842\r
2843 t3 = k_mul(t1, t2);\r
2844 Py_DECREF(t1);\r
2845 Py_DECREF(t2);\r
2846 if (t3 == NULL) goto fail;\r
2847 assert(Py_SIZE(t3) >= 0);\r
2848\r
2849 /* Add t3. It's not obvious why we can't run out of room here.\r
2850 * See the (*) comment after this function.\r
2851 */\r
2852 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));\r
2853 Py_DECREF(t3);\r
2854\r
2855 return long_normalize(ret);\r
2856\r
2857 fail:\r
2858 Py_XDECREF(ret);\r
2859 Py_XDECREF(ah);\r
2860 Py_XDECREF(al);\r
2861 Py_XDECREF(bh);\r
2862 Py_XDECREF(bl);\r
2863 return NULL;\r
2864}\r
2865\r
2866/* (*) Why adding t3 can't "run out of room" above.\r
2867\r
2868Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts\r
2869to start with:\r
2870\r
28711. For any integer i, i = c(i/2) + f(i/2). In particular,\r
2872 bsize = c(bsize/2) + f(bsize/2).\r
28732. shift = f(bsize/2)\r
28743. asize <= bsize\r
28754. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this\r
2876 routine, so asize > bsize/2 >= f(bsize/2) in this routine.\r
2877\r
2878We allocated asize + bsize result digits, and add t3 into them at an offset\r
2879of shift. This leaves asize+bsize-shift allocated digit positions for t3\r
2880to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =\r
2881asize + c(bsize/2) available digit positions.\r
2882\r
2883bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has\r
2884at most c(bsize/2) digits + 1 bit.\r
2885\r
2886If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)\r
2887digits, and al has at most f(bsize/2) digits in any case. So ah+al has at\r
2888most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.\r
2889\r
2890The product (ah+al)*(bh+bl) therefore has at most\r
2891\r
2892 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits\r
2893\r
2894and we have asize + c(bsize/2) available digit positions. We need to show\r
2895this is always enough. An instance of c(bsize/2) cancels out in both, so\r
2896the question reduces to whether asize digits is enough to hold\r
2897(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,\r
2898then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,\r
2899asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1\r
2900digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If\r
2901asize == bsize, then we're asking whether bsize digits is enough to hold\r
2902c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits\r
2903is enough to hold 2 bits. This is so if bsize >= 2, which holds because\r
2904bsize >= KARATSUBA_CUTOFF >= 2.\r
2905\r
2906Note that since there's always enough room for (ah+al)*(bh+bl), and that's\r
2907clearly >= each of ah*bh and al*bl, there's always enough room to subtract\r
2908ah*bh and al*bl too.\r
2909*/\r
2910\r
2911/* b has at least twice the digits of a, and a is big enough that Karatsuba\r
2912 * would pay off *if* the inputs had balanced sizes. View b as a sequence\r
2913 * of slices, each with a->ob_size digits, and multiply the slices by a,\r
2914 * one at a time. This gives k_mul balanced inputs to work with, and is\r
2915 * also cache-friendly (we compute one double-width slice of the result\r
2916 * at a time, then move on, never backtracking except for the helpful\r
2917 * single-width slice overlap between successive partial sums).\r
2918 */\r
2919static PyLongObject *\r
2920k_lopsided_mul(PyLongObject *a, PyLongObject *b)\r
2921{\r
2922 const Py_ssize_t asize = ABS(Py_SIZE(a));\r
2923 Py_ssize_t bsize = ABS(Py_SIZE(b));\r
2924 Py_ssize_t nbdone; /* # of b digits already multiplied */\r
2925 PyLongObject *ret;\r
2926 PyLongObject *bslice = NULL;\r
2927\r
2928 assert(asize > KARATSUBA_CUTOFF);\r
2929 assert(2 * asize <= bsize);\r
2930\r
2931 /* Allocate result space, and zero it out. */\r
2932 ret = _PyLong_New(asize + bsize);\r
2933 if (ret == NULL)\r
2934 return NULL;\r
2935 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));\r
2936\r
2937 /* Successive slices of b are copied into bslice. */\r
2938 bslice = _PyLong_New(asize);\r
2939 if (bslice == NULL)\r
2940 goto fail;\r
2941\r
2942 nbdone = 0;\r
2943 while (bsize > 0) {\r
2944 PyLongObject *product;\r
2945 const Py_ssize_t nbtouse = MIN(bsize, asize);\r
2946\r
2947 /* Multiply the next slice of b by a. */\r
2948 memcpy(bslice->ob_digit, b->ob_digit + nbdone,\r
2949 nbtouse * sizeof(digit));\r
2950 Py_SIZE(bslice) = nbtouse;\r
2951 product = k_mul(a, bslice);\r
2952 if (product == NULL)\r
2953 goto fail;\r
2954\r
2955 /* Add into result. */\r
2956 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,\r
2957 product->ob_digit, Py_SIZE(product));\r
2958 Py_DECREF(product);\r
2959\r
2960 bsize -= nbtouse;\r
2961 nbdone += nbtouse;\r
2962 }\r
2963\r
2964 Py_DECREF(bslice);\r
2965 return long_normalize(ret);\r
2966\r
2967 fail:\r
2968 Py_DECREF(ret);\r
2969 Py_XDECREF(bslice);\r
2970 return NULL;\r
2971}\r
2972\r
2973static PyObject *\r
2974long_mul(PyLongObject *v, PyLongObject *w)\r
2975{\r
2976 PyLongObject *a, *b, *z;\r
2977\r
2978 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {\r
2979 Py_INCREF(Py_NotImplemented);\r
2980 return Py_NotImplemented;\r
2981 }\r
2982\r
2983 z = k_mul(a, b);\r
2984 /* Negate if exactly one of the inputs is negative. */\r
2985 if (((a->ob_size ^ b->ob_size) < 0) && z)\r
2986 z->ob_size = -(z->ob_size);\r
2987 Py_DECREF(a);\r
2988 Py_DECREF(b);\r
2989 return (PyObject *)z;\r
2990}\r
2991\r
2992/* The / and % operators are now defined in terms of divmod().\r
2993 The expression a mod b has the value a - b*floor(a/b).\r
2994 The long_divrem function gives the remainder after division of\r
2995 |a| by |b|, with the sign of a. This is also expressed\r
2996 as a - b*trunc(a/b), if trunc truncates towards zero.\r
2997 Some examples:\r
2998 a b a rem b a mod b\r
2999 13 10 3 3\r
3000 -13 10 -3 7\r
3001 13 -10 3 -7\r
3002 -13 -10 -3 -3\r
3003 So, to get from rem to mod, we have to add b if a and b\r
3004 have different signs. We then subtract one from the 'div'\r
3005 part of the outcome to keep the invariant intact. */\r
3006\r
3007/* Compute\r
3008 * *pdiv, *pmod = divmod(v, w)\r
3009 * NULL can be passed for pdiv or pmod, in which case that part of\r
3010 * the result is simply thrown away. The caller owns a reference to\r
3011 * each of these it requests (does not pass NULL for).\r
3012 */\r
3013static int\r
3014l_divmod(PyLongObject *v, PyLongObject *w,\r
3015 PyLongObject **pdiv, PyLongObject **pmod)\r
3016{\r
3017 PyLongObject *div, *mod;\r
3018\r
3019 if (long_divrem(v, w, &div, &mod) < 0)\r
3020 return -1;\r
3021 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||\r
3022 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {\r
3023 PyLongObject *temp;\r
3024 PyLongObject *one;\r
3025 temp = (PyLongObject *) long_add(mod, w);\r
3026 Py_DECREF(mod);\r
3027 mod = temp;\r
3028 if (mod == NULL) {\r
3029 Py_DECREF(div);\r
3030 return -1;\r
3031 }\r
3032 one = (PyLongObject *) PyLong_FromLong(1L);\r
3033 if (one == NULL ||\r
3034 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {\r
3035 Py_DECREF(mod);\r
3036 Py_DECREF(div);\r
3037 Py_XDECREF(one);\r
3038 return -1;\r
3039 }\r
3040 Py_DECREF(one);\r
3041 Py_DECREF(div);\r
3042 div = temp;\r
3043 }\r
3044 if (pdiv != NULL)\r
3045 *pdiv = div;\r
3046 else\r
3047 Py_DECREF(div);\r
3048\r
3049 if (pmod != NULL)\r
3050 *pmod = mod;\r
3051 else\r
3052 Py_DECREF(mod);\r
3053\r
3054 return 0;\r
3055}\r
3056\r
3057static PyObject *\r
3058long_div(PyObject *v, PyObject *w)\r
3059{\r
3060 PyLongObject *a, *b, *div;\r
3061\r
3062 CONVERT_BINOP(v, w, &a, &b);\r
3063 if (l_divmod(a, b, &div, NULL) < 0)\r
3064 div = NULL;\r
3065 Py_DECREF(a);\r
3066 Py_DECREF(b);\r
3067 return (PyObject *)div;\r
3068}\r
3069\r
3070static PyObject *\r
3071long_classic_div(PyObject *v, PyObject *w)\r
3072{\r
3073 PyLongObject *a, *b, *div;\r
3074\r
3075 CONVERT_BINOP(v, w, &a, &b);\r
3076 if (Py_DivisionWarningFlag &&\r
3077 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)\r
3078 div = NULL;\r
3079 else if (l_divmod(a, b, &div, NULL) < 0)\r
3080 div = NULL;\r
3081 Py_DECREF(a);\r
3082 Py_DECREF(b);\r
3083 return (PyObject *)div;\r
3084}\r
3085\r
3086/* PyLong/PyLong -> float, with correctly rounded result. */\r
3087\r
3088#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)\r
3089#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)\r
3090\r
3091static PyObject *\r
3092long_true_divide(PyObject *v, PyObject *w)\r
3093{\r
3094 PyLongObject *a, *b, *x;\r
3095 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;\r
3096 digit mask, low;\r
3097 int inexact, negate, a_is_small, b_is_small;\r
3098 double dx, result;\r
3099\r
3100 CONVERT_BINOP(v, w, &a, &b);\r
3101\r
3102 /*\r
3103 Method in a nutshell:\r
3104\r
3105 0. reduce to case a, b > 0; filter out obvious underflow/overflow\r
3106 1. choose a suitable integer 'shift'\r
3107 2. use integer arithmetic to compute x = floor(2**-shift*a/b)\r
3108 3. adjust x for correct rounding\r
3109 4. convert x to a double dx with the same value\r
3110 5. return ldexp(dx, shift).\r
3111\r
3112 In more detail:\r
3113\r
3114 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b\r
3115 returns either 0.0 or -0.0, depending on the sign of b. For a and\r
3116 b both nonzero, ignore signs of a and b, and add the sign back in\r
3117 at the end. Now write a_bits and b_bits for the bit lengths of a\r
3118 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise\r
3119 for b). Then\r
3120\r
3121 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).\r
3122\r
3123 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and\r
3124 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -\r
3125 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of\r
3126 the way, we can assume that\r
3127\r
3128 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.\r
3129\r
3130 1. The integer 'shift' is chosen so that x has the right number of\r
3131 bits for a double, plus two or three extra bits that will be used\r
3132 in the rounding decisions. Writing a_bits and b_bits for the\r
3133 number of significant bits in a and b respectively, a\r
3134 straightforward formula for shift is:\r
3135\r
3136 shift = a_bits - b_bits - DBL_MANT_DIG - 2\r
3137\r
3138 This is fine in the usual case, but if a/b is smaller than the\r
3139 smallest normal float then it can lead to double rounding on an\r
3140 IEEE 754 platform, giving incorrectly rounded results. So we\r
3141 adjust the formula slightly. The actual formula used is:\r
3142\r
3143 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2\r
3144\r
3145 2. The quantity x is computed by first shifting a (left -shift bits\r
3146 if shift <= 0, right shift bits if shift > 0) and then dividing by\r
3147 b. For both the shift and the division, we keep track of whether\r
3148 the result is inexact, in a flag 'inexact'; this information is\r
3149 needed at the rounding stage.\r
3150\r
3151 With the choice of shift above, together with our assumption that\r
3152 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows\r
3153 that x >= 1.\r
3154\r
3155 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace\r
3156 this with an exactly representable float of the form\r
3157\r
3158 round(x/2**extra_bits) * 2**(extra_bits+shift).\r
3159\r
3160 For float representability, we need x/2**extra_bits <\r
3161 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -\r
3162 DBL_MANT_DIG. This translates to the condition:\r
3163\r
3164 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG\r
3165\r
3166 To round, we just modify the bottom digit of x in-place; this can\r
3167 end up giving a digit with value > PyLONG_MASK, but that's not a\r
3168 problem since digits can hold values up to 2*PyLONG_MASK+1.\r
3169\r
3170 With the original choices for shift above, extra_bits will always\r
3171 be 2 or 3. Then rounding under the round-half-to-even rule, we\r
3172 round up iff the most significant of the extra bits is 1, and\r
3173 either: (a) the computation of x in step 2 had an inexact result,\r
3174 or (b) at least one other of the extra bits is 1, or (c) the least\r
3175 significant bit of x (above those to be rounded) is 1.\r
3176\r
3177 4. Conversion to a double is straightforward; all floating-point\r
3178 operations involved in the conversion are exact, so there's no\r
3179 danger of rounding errors.\r
3180\r
3181 5. Use ldexp(x, shift) to compute x*2**shift, the final result.\r
3182 The result will always be exactly representable as a double, except\r
3183 in the case that it overflows. To avoid dependence on the exact\r
3184 behaviour of ldexp on overflow, we check for overflow before\r
3185 applying ldexp. The result of ldexp is adjusted for sign before\r
3186 returning.\r
3187 */\r
3188\r
3189 /* Reduce to case where a and b are both positive. */\r
3190 a_size = ABS(Py_SIZE(a));\r
3191 b_size = ABS(Py_SIZE(b));\r
3192 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);\r
3193 if (b_size == 0) {\r
3194 PyErr_SetString(PyExc_ZeroDivisionError,\r
3195 "division by zero");\r
3196 goto error;\r
3197 }\r
3198 if (a_size == 0)\r
3199 goto underflow_or_zero;\r
3200\r
3201 /* Fast path for a and b small (exactly representable in a double).\r
3202 Relies on floating-point division being correctly rounded; results\r
3203 may be subject to double rounding on x86 machines that operate with\r
3204 the x87 FPU set to 64-bit precision. */\r
3205 a_is_small = a_size <= MANT_DIG_DIGITS ||\r
3206 (a_size == MANT_DIG_DIGITS+1 &&\r
3207 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);\r
3208 b_is_small = b_size <= MANT_DIG_DIGITS ||\r
3209 (b_size == MANT_DIG_DIGITS+1 &&\r
3210 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);\r
3211 if (a_is_small && b_is_small) {\r
3212 double da, db;\r
3213 da = a->ob_digit[--a_size];\r
3214 while (a_size > 0)\r
3215 da = da * PyLong_BASE + a->ob_digit[--a_size];\r
3216 db = b->ob_digit[--b_size];\r
3217 while (b_size > 0)\r
3218 db = db * PyLong_BASE + b->ob_digit[--b_size];\r
3219 result = da / db;\r
3220 goto success;\r
3221 }\r
3222\r
3223 /* Catch obvious cases of underflow and overflow */\r
3224 diff = a_size - b_size;\r
3225 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)\r
3226 /* Extreme overflow */\r
3227 goto overflow;\r
3228 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)\r
3229 /* Extreme underflow */\r
3230 goto underflow_or_zero;\r
3231 /* Next line is now safe from overflowing a Py_ssize_t */\r
3232 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -\r
3233 bits_in_digit(b->ob_digit[b_size - 1]);\r
3234 /* Now diff = a_bits - b_bits. */\r
3235 if (diff > DBL_MAX_EXP)\r
3236 goto overflow;\r
3237 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)\r
3238 goto underflow_or_zero;\r
3239\r
3240 /* Choose value for shift; see comments for step 1 above. */\r
3241 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;\r
3242\r
3243 inexact = 0;\r
3244\r
3245 /* x = abs(a * 2**-shift) */\r
3246 if (shift <= 0) {\r
3247 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;\r
3248 digit rem;\r
3249 /* x = a << -shift */\r
3250 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {\r
3251 /* In practice, it's probably impossible to end up\r
3252 here. Both a and b would have to be enormous,\r
3253 using close to SIZE_T_MAX bytes of memory each. */\r
3254 PyErr_SetString(PyExc_OverflowError,\r
3255 "intermediate overflow during division");\r
3256 goto error;\r
3257 }\r
3258 x = _PyLong_New(a_size + shift_digits + 1);\r
3259 if (x == NULL)\r
3260 goto error;\r
3261 for (i = 0; i < shift_digits; i++)\r
3262 x->ob_digit[i] = 0;\r
3263 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,\r
3264 a_size, -shift % PyLong_SHIFT);\r
3265 x->ob_digit[a_size + shift_digits] = rem;\r
3266 }\r
3267 else {\r
3268 Py_ssize_t shift_digits = shift / PyLong_SHIFT;\r
3269 digit rem;\r
3270 /* x = a >> shift */\r
3271 assert(a_size >= shift_digits);\r
3272 x = _PyLong_New(a_size - shift_digits);\r
3273 if (x == NULL)\r
3274 goto error;\r
3275 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,\r
3276 a_size - shift_digits, shift % PyLong_SHIFT);\r
3277 /* set inexact if any of the bits shifted out is nonzero */\r
3278 if (rem)\r
3279 inexact = 1;\r
3280 while (!inexact && shift_digits > 0)\r
3281 if (a->ob_digit[--shift_digits])\r
3282 inexact = 1;\r
3283 }\r
3284 long_normalize(x);\r
3285 x_size = Py_SIZE(x);\r
3286\r
3287 /* x //= b. If the remainder is nonzero, set inexact. We own the only\r
3288 reference to x, so it's safe to modify it in-place. */\r
3289 if (b_size == 1) {\r
3290 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,\r
3291 b->ob_digit[0]);\r
3292 long_normalize(x);\r
3293 if (rem)\r
3294 inexact = 1;\r
3295 }\r
3296 else {\r
3297 PyLongObject *div, *rem;\r
3298 div = x_divrem(x, b, &rem);\r
3299 Py_DECREF(x);\r
3300 x = div;\r
3301 if (x == NULL)\r
3302 goto error;\r
3303 if (Py_SIZE(rem))\r
3304 inexact = 1;\r
3305 Py_DECREF(rem);\r
3306 }\r
3307 x_size = ABS(Py_SIZE(x));\r
3308 assert(x_size > 0); /* result of division is never zero */\r
3309 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);\r
3310\r
3311 /* The number of extra bits that have to be rounded away. */\r
3312 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;\r
3313 assert(extra_bits == 2 || extra_bits == 3);\r
3314\r
3315 /* Round by directly modifying the low digit of x. */\r
3316 mask = (digit)1 << (extra_bits - 1);\r
3317 low = x->ob_digit[0] | inexact;\r
3318 if (low & mask && low & (3*mask-1))\r
3319 low += mask;\r
3320 x->ob_digit[0] = low & ~(mask-1U);\r
3321\r
3322 /* Convert x to a double dx; the conversion is exact. */\r
3323 dx = x->ob_digit[--x_size];\r
3324 while (x_size > 0)\r
3325 dx = dx * PyLong_BASE + x->ob_digit[--x_size];\r
3326 Py_DECREF(x);\r
3327\r
3328 /* Check whether ldexp result will overflow a double. */\r
3329 if (shift + x_bits >= DBL_MAX_EXP &&\r
3330 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))\r
3331 goto overflow;\r
3332 result = ldexp(dx, (int)shift);\r
3333\r
3334 success:\r
3335 Py_DECREF(a);\r
3336 Py_DECREF(b);\r
3337 return PyFloat_FromDouble(negate ? -result : result);\r
3338\r
3339 underflow_or_zero:\r
3340 Py_DECREF(a);\r
3341 Py_DECREF(b);\r
3342 return PyFloat_FromDouble(negate ? -0.0 : 0.0);\r
3343\r
3344 overflow:\r
3345 PyErr_SetString(PyExc_OverflowError,\r
3346 "integer division result too large for a float");\r
3347 error:\r
3348 Py_DECREF(a);\r
3349 Py_DECREF(b);\r
3350 return NULL;\r
3351}\r
3352\r
3353static PyObject *\r
3354long_mod(PyObject *v, PyObject *w)\r
3355{\r
3356 PyLongObject *a, *b, *mod;\r
3357\r
3358 CONVERT_BINOP(v, w, &a, &b);\r
3359\r
3360 if (l_divmod(a, b, NULL, &mod) < 0)\r
3361 mod = NULL;\r
3362 Py_DECREF(a);\r
3363 Py_DECREF(b);\r
3364 return (PyObject *)mod;\r
3365}\r
3366\r
3367static PyObject *\r
3368long_divmod(PyObject *v, PyObject *w)\r
3369{\r
3370 PyLongObject *a, *b, *div, *mod;\r
3371 PyObject *z;\r
3372\r
3373 CONVERT_BINOP(v, w, &a, &b);\r
3374\r
3375 if (l_divmod(a, b, &div, &mod) < 0) {\r
3376 Py_DECREF(a);\r
3377 Py_DECREF(b);\r
3378 return NULL;\r
3379 }\r
3380 z = PyTuple_New(2);\r
3381 if (z != NULL) {\r
3382 PyTuple_SetItem(z, 0, (PyObject *) div);\r
3383 PyTuple_SetItem(z, 1, (PyObject *) mod);\r
3384 }\r
3385 else {\r
3386 Py_DECREF(div);\r
3387 Py_DECREF(mod);\r
3388 }\r
3389 Py_DECREF(a);\r
3390 Py_DECREF(b);\r
3391 return z;\r
3392}\r
3393\r
3394/* pow(v, w, x) */\r
3395static PyObject *\r
3396long_pow(PyObject *v, PyObject *w, PyObject *x)\r
3397{\r
3398 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */\r
3399 int negativeOutput = 0; /* if x<0 return negative output */\r
3400\r
3401 PyLongObject *z = NULL; /* accumulated result */\r
3402 Py_ssize_t i, j, k; /* counters */\r
3403 PyLongObject *temp = NULL;\r
3404\r
3405 /* 5-ary values. If the exponent is large enough, table is\r
3406 * precomputed so that table[i] == a**i % c for i in range(32).\r
3407 */\r
3408 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\r
3409 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\r
3410\r
3411 /* a, b, c = v, w, x */\r
3412 CONVERT_BINOP(v, w, &a, &b);\r
3413 if (PyLong_Check(x)) {\r
3414 c = (PyLongObject *)x;\r
3415 Py_INCREF(x);\r
3416 }\r
3417 else if (PyInt_Check(x)) {\r
3418 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));\r
3419 if (c == NULL)\r
3420 goto Error;\r
3421 }\r
3422 else if (x == Py_None)\r
3423 c = NULL;\r
3424 else {\r
3425 Py_DECREF(a);\r
3426 Py_DECREF(b);\r
3427 Py_INCREF(Py_NotImplemented);\r
3428 return Py_NotImplemented;\r
3429 }\r
3430\r
3431 if (Py_SIZE(b) < 0) { /* if exponent is negative */\r
3432 if (c) {\r
3433 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "\r
3434 "cannot be negative when 3rd argument specified");\r
3435 goto Error;\r
3436 }\r
3437 else {\r
3438 /* else return a float. This works because we know\r
3439 that this calls float_pow() which converts its\r
3440 arguments to double. */\r
3441 Py_DECREF(a);\r
3442 Py_DECREF(b);\r
3443 return PyFloat_Type.tp_as_number->nb_power(v, w, x);\r
3444 }\r
3445 }\r
3446\r
3447 if (c) {\r
3448 /* if modulus == 0:\r
3449 raise ValueError() */\r
3450 if (Py_SIZE(c) == 0) {\r
3451 PyErr_SetString(PyExc_ValueError,\r
3452 "pow() 3rd argument cannot be 0");\r
3453 goto Error;\r
3454 }\r
3455\r
3456 /* if modulus < 0:\r
3457 negativeOutput = True\r
3458 modulus = -modulus */\r
3459 if (Py_SIZE(c) < 0) {\r
3460 negativeOutput = 1;\r
3461 temp = (PyLongObject *)_PyLong_Copy(c);\r
3462 if (temp == NULL)\r
3463 goto Error;\r
3464 Py_DECREF(c);\r
3465 c = temp;\r
3466 temp = NULL;\r
3467 c->ob_size = - c->ob_size;\r
3468 }\r
3469\r
3470 /* if modulus == 1:\r
3471 return 0 */\r
3472 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {\r
3473 z = (PyLongObject *)PyLong_FromLong(0L);\r
3474 goto Done;\r
3475 }\r
3476\r
3477 /* Reduce base by modulus in some cases:\r
3478 1. If base < 0. Forcing the base non-negative makes things easier.\r
3479 2. If base is obviously larger than the modulus. The "small\r
3480 exponent" case later can multiply directly by base repeatedly,\r
3481 while the "large exponent" case multiplies directly by base 31\r
3482 times. It can be unboundedly faster to multiply by\r
3483 base % modulus instead.\r
3484 We could _always_ do this reduction, but l_divmod() isn't cheap,\r
3485 so we only do it when it buys something. */\r
3486 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {\r
3487 if (l_divmod(a, c, NULL, &temp) < 0)\r
3488 goto Error;\r
3489 Py_DECREF(a);\r
3490 a = temp;\r
3491 temp = NULL;\r
3492 }\r
3493 }\r
3494\r
3495 /* At this point a, b, and c are guaranteed non-negative UNLESS\r
3496 c is NULL, in which case a may be negative. */\r
3497\r
3498 z = (PyLongObject *)PyLong_FromLong(1L);\r
3499 if (z == NULL)\r
3500 goto Error;\r
3501\r
3502 /* Perform a modular reduction, X = X % c, but leave X alone if c\r
3503 * is NULL.\r
3504 */\r
3505#define REDUCE(X) \\r
3506 do { \\r
3507 if (c != NULL) { \\r
3508 if (l_divmod(X, c, NULL, &temp) < 0) \\r
3509 goto Error; \\r
3510 Py_XDECREF(X); \\r
3511 X = temp; \\r
3512 temp = NULL; \\r
3513 } \\r
3514 } while(0)\r
3515\r
3516 /* Multiply two values, then reduce the result:\r
3517 result = X*Y % c. If c is NULL, skip the mod. */\r
3518#define MULT(X, Y, result) \\r
3519 do { \\r
3520 temp = (PyLongObject *)long_mul(X, Y); \\r
3521 if (temp == NULL) \\r
3522 goto Error; \\r
3523 Py_XDECREF(result); \\r
3524 result = temp; \\r
3525 temp = NULL; \\r
3526 REDUCE(result); \\r
3527 } while(0)\r
3528\r
3529 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {\r
3530 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */\r
3531 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */\r
3532 for (i = Py_SIZE(b) - 1; i >= 0; --i) {\r
3533 digit bi = b->ob_digit[i];\r
3534\r
3535 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {\r
3536 MULT(z, z, z);\r
3537 if (bi & j)\r
3538 MULT(z, a, z);\r
3539 }\r
3540 }\r
3541 }\r
3542 else {\r
3543 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */\r
3544 Py_INCREF(z); /* still holds 1L */\r
3545 table[0] = z;\r
3546 for (i = 1; i < 32; ++i)\r
3547 MULT(table[i-1], a, table[i]);\r
3548\r
3549 for (i = Py_SIZE(b) - 1; i >= 0; --i) {\r
3550 const digit bi = b->ob_digit[i];\r
3551\r
3552 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {\r
3553 const int index = (bi >> j) & 0x1f;\r
3554 for (k = 0; k < 5; ++k)\r
3555 MULT(z, z, z);\r
3556 if (index)\r
3557 MULT(z, table[index], z);\r
3558 }\r
3559 }\r
3560 }\r
3561\r
3562 if (negativeOutput && (Py_SIZE(z) != 0)) {\r
3563 temp = (PyLongObject *)long_sub(z, c);\r
3564 if (temp == NULL)\r
3565 goto Error;\r
3566 Py_DECREF(z);\r
3567 z = temp;\r
3568 temp = NULL;\r
3569 }\r
3570 goto Done;\r
3571\r
3572 Error:\r
3573 if (z != NULL) {\r
3574 Py_DECREF(z);\r
3575 z = NULL;\r
3576 }\r
3577 /* fall through */\r
3578 Done:\r
3579 if (Py_SIZE(b) > FIVEARY_CUTOFF) {\r
3580 for (i = 0; i < 32; ++i)\r
3581 Py_XDECREF(table[i]);\r
3582 }\r
3583 Py_DECREF(a);\r
3584 Py_DECREF(b);\r
3585 Py_XDECREF(c);\r
3586 Py_XDECREF(temp);\r
3587 return (PyObject *)z;\r
3588}\r
3589\r
3590static PyObject *\r
3591long_invert(PyLongObject *v)\r
3592{\r
3593 /* Implement ~x as -(x+1) */\r
3594 PyLongObject *x;\r
3595 PyLongObject *w;\r
3596 w = (PyLongObject *)PyLong_FromLong(1L);\r
3597 if (w == NULL)\r
3598 return NULL;\r
3599 x = (PyLongObject *) long_add(v, w);\r
3600 Py_DECREF(w);\r
3601 if (x == NULL)\r
3602 return NULL;\r
3603 Py_SIZE(x) = -(Py_SIZE(x));\r
3604 return (PyObject *)x;\r
3605}\r
3606\r
3607static PyObject *\r
3608long_neg(PyLongObject *v)\r
3609{\r
3610 PyLongObject *z;\r
3611 if (v->ob_size == 0 && PyLong_CheckExact(v)) {\r
3612 /* -0 == 0 */\r
3613 Py_INCREF(v);\r
3614 return (PyObject *) v;\r
3615 }\r
3616 z = (PyLongObject *)_PyLong_Copy(v);\r
3617 if (z != NULL)\r
3618 z->ob_size = -(v->ob_size);\r
3619 return (PyObject *)z;\r
3620}\r
3621\r
3622static PyObject *\r
3623long_abs(PyLongObject *v)\r
3624{\r
3625 if (v->ob_size < 0)\r
3626 return long_neg(v);\r
3627 else\r
3628 return long_long((PyObject *)v);\r
3629}\r
3630\r
3631static int\r
3632long_nonzero(PyLongObject *v)\r
3633{\r
3634 return Py_SIZE(v) != 0;\r
3635}\r
3636\r
3637static PyObject *\r
3638long_rshift(PyLongObject *v, PyLongObject *w)\r
3639{\r
3640 PyLongObject *a, *b;\r
3641 PyLongObject *z = NULL;\r
3642 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;\r
3643 digit lomask, himask;\r
3644\r
3645 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);\r
3646\r
3647 if (Py_SIZE(a) < 0) {\r
3648 /* Right shifting negative numbers is harder */\r
3649 PyLongObject *a1, *a2;\r
3650 a1 = (PyLongObject *) long_invert(a);\r
3651 if (a1 == NULL)\r
3652 goto rshift_error;\r
3653 a2 = (PyLongObject *) long_rshift(a1, b);\r
3654 Py_DECREF(a1);\r
3655 if (a2 == NULL)\r
3656 goto rshift_error;\r
3657 z = (PyLongObject *) long_invert(a2);\r
3658 Py_DECREF(a2);\r
3659 }\r
3660 else {\r
3661 shiftby = PyLong_AsSsize_t((PyObject *)b);\r
3662 if (shiftby == -1L && PyErr_Occurred())\r
3663 goto rshift_error;\r
3664 if (shiftby < 0) {\r
3665 PyErr_SetString(PyExc_ValueError,\r
3666 "negative shift count");\r
3667 goto rshift_error;\r
3668 }\r
3669 wordshift = shiftby / PyLong_SHIFT;\r
3670 newsize = ABS(Py_SIZE(a)) - wordshift;\r
3671 if (newsize <= 0) {\r
3672 z = _PyLong_New(0);\r
3673 Py_DECREF(a);\r
3674 Py_DECREF(b);\r
3675 return (PyObject *)z;\r
3676 }\r
3677 loshift = shiftby % PyLong_SHIFT;\r
3678 hishift = PyLong_SHIFT - loshift;\r
3679 lomask = ((digit)1 << hishift) - 1;\r
3680 himask = PyLong_MASK ^ lomask;\r
3681 z = _PyLong_New(newsize);\r
3682 if (z == NULL)\r
3683 goto rshift_error;\r
3684 if (Py_SIZE(a) < 0)\r
3685 Py_SIZE(z) = -(Py_SIZE(z));\r
3686 for (i = 0, j = wordshift; i < newsize; i++, j++) {\r
3687 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;\r
3688 if (i+1 < newsize)\r
3689 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;\r
3690 }\r
3691 z = long_normalize(z);\r
3692 }\r
3693 rshift_error:\r
3694 Py_DECREF(a);\r
3695 Py_DECREF(b);\r
3696 return (PyObject *) z;\r
3697\r
3698}\r
3699\r
3700static PyObject *\r
3701long_lshift(PyObject *v, PyObject *w)\r
3702{\r
3703 /* This version due to Tim Peters */\r
3704 PyLongObject *a, *b;\r
3705 PyLongObject *z = NULL;\r
3706 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;\r
3707 twodigits accum;\r
3708\r
3709 CONVERT_BINOP(v, w, &a, &b);\r
3710\r
3711 shiftby = PyLong_AsSsize_t((PyObject *)b);\r
3712 if (shiftby == -1L && PyErr_Occurred())\r
3713 goto lshift_error;\r
3714 if (shiftby < 0) {\r
3715 PyErr_SetString(PyExc_ValueError, "negative shift count");\r
3716 goto lshift_error;\r
3717 }\r
3718 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */\r
3719 wordshift = shiftby / PyLong_SHIFT;\r
3720 remshift = shiftby - wordshift * PyLong_SHIFT;\r
3721\r
3722 oldsize = ABS(a->ob_size);\r
3723 newsize = oldsize + wordshift;\r
3724 if (remshift)\r
3725 ++newsize;\r
3726 z = _PyLong_New(newsize);\r
3727 if (z == NULL)\r
3728 goto lshift_error;\r
3729 if (a->ob_size < 0)\r
3730 z->ob_size = -(z->ob_size);\r
3731 for (i = 0; i < wordshift; i++)\r
3732 z->ob_digit[i] = 0;\r
3733 accum = 0;\r
3734 for (i = wordshift, j = 0; j < oldsize; i++, j++) {\r
3735 accum |= (twodigits)a->ob_digit[j] << remshift;\r
3736 z->ob_digit[i] = (digit)(accum & PyLong_MASK);\r
3737 accum >>= PyLong_SHIFT;\r
3738 }\r
3739 if (remshift)\r
3740 z->ob_digit[newsize-1] = (digit)accum;\r
3741 else\r
3742 assert(!accum);\r
3743 z = long_normalize(z);\r
3744 lshift_error:\r
3745 Py_DECREF(a);\r
3746 Py_DECREF(b);\r
3747 return (PyObject *) z;\r
3748}\r
3749\r
3750/* Compute two's complement of digit vector a[0:m], writing result to\r
3751 z[0:m]. The digit vector a need not be normalized, but should not\r
3752 be entirely zero. a and z may point to the same digit vector. */\r
3753\r
3754static void\r
3755v_complement(digit *z, digit *a, Py_ssize_t m)\r
3756{\r
3757 Py_ssize_t i;\r
3758 digit carry = 1;\r
3759 for (i = 0; i < m; ++i) {\r
3760 carry += a[i] ^ PyLong_MASK;\r
3761 z[i] = carry & PyLong_MASK;\r
3762 carry >>= PyLong_SHIFT;\r
3763 }\r
3764 assert(carry == 0);\r
3765}\r
3766\r
3767/* Bitwise and/xor/or operations */\r
3768\r
3769static PyObject *\r
3770long_bitwise(PyLongObject *a,\r
3771 int op, /* '&', '|', '^' */\r
3772 PyLongObject *b)\r
3773{\r
3774 int nega, negb, negz;\r
3775 Py_ssize_t size_a, size_b, size_z, i;\r
3776 PyLongObject *z;\r
3777\r
3778 /* Bitwise operations for negative numbers operate as though\r
3779 on a two's complement representation. So convert arguments\r
3780 from sign-magnitude to two's complement, and convert the\r
3781 result back to sign-magnitude at the end. */\r
3782\r
3783 /* If a is negative, replace it by its two's complement. */\r
3784 size_a = ABS(Py_SIZE(a));\r
3785 nega = Py_SIZE(a) < 0;\r
3786 if (nega) {\r
3787 z = _PyLong_New(size_a);\r
3788 if (z == NULL)\r
3789 return NULL;\r
3790 v_complement(z->ob_digit, a->ob_digit, size_a);\r
3791 a = z;\r
3792 }\r
3793 else\r
3794 /* Keep reference count consistent. */\r
3795 Py_INCREF(a);\r
3796\r
3797 /* Same for b. */\r
3798 size_b = ABS(Py_SIZE(b));\r
3799 negb = Py_SIZE(b) < 0;\r
3800 if (negb) {\r
3801 z = _PyLong_New(size_b);\r
3802 if (z == NULL) {\r
3803 Py_DECREF(a);\r
3804 return NULL;\r
3805 }\r
3806 v_complement(z->ob_digit, b->ob_digit, size_b);\r
3807 b = z;\r
3808 }\r
3809 else\r
3810 Py_INCREF(b);\r
3811\r
3812 /* Swap a and b if necessary to ensure size_a >= size_b. */\r
3813 if (size_a < size_b) {\r
3814 z = a; a = b; b = z;\r
3815 size_z = size_a; size_a = size_b; size_b = size_z;\r
3816 negz = nega; nega = negb; negb = negz;\r
3817 }\r
3818\r
3819 /* JRH: The original logic here was to allocate the result value (z)\r
3820 as the longer of the two operands. However, there are some cases\r
3821 where the result is guaranteed to be shorter than that: AND of two\r
3822 positives, OR of two negatives: use the shorter number. AND with\r
3823 mixed signs: use the positive number. OR with mixed signs: use the\r
3824 negative number.\r
3825 */\r
3826 switch (op) {\r
3827 case '^':\r
3828 negz = nega ^ negb;\r
3829 size_z = size_a;\r
3830 break;\r
3831 case '&':\r
3832 negz = nega & negb;\r
3833 size_z = negb ? size_a : size_b;\r
3834 break;\r
3835 case '|':\r
3836 negz = nega | negb;\r
3837 size_z = negb ? size_b : size_a;\r
3838 break;\r
3839 default:\r
3840 PyErr_BadArgument();\r
3841 return NULL;\r
3842 }\r
3843\r
3844 /* We allow an extra digit if z is negative, to make sure that\r
3845 the final two's complement of z doesn't overflow. */\r
3846 z = _PyLong_New(size_z + negz);\r
3847 if (z == NULL) {\r
3848 Py_DECREF(a);\r
3849 Py_DECREF(b);\r
3850 return NULL;\r
3851 }\r
3852\r
3853 /* Compute digits for overlap of a and b. */\r
3854 switch(op) {\r
3855 case '&':\r
3856 for (i = 0; i < size_b; ++i)\r
3857 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];\r
3858 break;\r
3859 case '|':\r
3860 for (i = 0; i < size_b; ++i)\r
3861 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];\r
3862 break;\r
3863 case '^':\r
3864 for (i = 0; i < size_b; ++i)\r
3865 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];\r
3866 break;\r
3867 default:\r
3868 PyErr_BadArgument();\r
3869 return NULL;\r
3870 }\r
3871\r
3872 /* Copy any remaining digits of a, inverting if necessary. */\r
3873 if (op == '^' && negb)\r
3874 for (; i < size_z; ++i)\r
3875 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;\r
3876 else if (i < size_z)\r
3877 memcpy(&z->ob_digit[i], &a->ob_digit[i],\r
3878 (size_z-i)*sizeof(digit));\r
3879\r
3880 /* Complement result if negative. */\r
3881 if (negz) {\r
3882 Py_SIZE(z) = -(Py_SIZE(z));\r
3883 z->ob_digit[size_z] = PyLong_MASK;\r
3884 v_complement(z->ob_digit, z->ob_digit, size_z+1);\r
3885 }\r
3886\r
3887 Py_DECREF(a);\r
3888 Py_DECREF(b);\r
3889 return (PyObject *)long_normalize(z);\r
3890}\r
3891\r
3892static PyObject *\r
3893long_and(PyObject *v, PyObject *w)\r
3894{\r
3895 PyLongObject *a, *b;\r
3896 PyObject *c;\r
3897 CONVERT_BINOP(v, w, &a, &b);\r
3898 c = long_bitwise(a, '&', b);\r
3899 Py_DECREF(a);\r
3900 Py_DECREF(b);\r
3901 return c;\r
3902}\r
3903\r
3904static PyObject *\r
3905long_xor(PyObject *v, PyObject *w)\r
3906{\r
3907 PyLongObject *a, *b;\r
3908 PyObject *c;\r
3909 CONVERT_BINOP(v, w, &a, &b);\r
3910 c = long_bitwise(a, '^', b);\r
3911 Py_DECREF(a);\r
3912 Py_DECREF(b);\r
3913 return c;\r
3914}\r
3915\r
3916static PyObject *\r
3917long_or(PyObject *v, PyObject *w)\r
3918{\r
3919 PyLongObject *a, *b;\r
3920 PyObject *c;\r
3921 CONVERT_BINOP(v, w, &a, &b);\r
3922 c = long_bitwise(a, '|', b);\r
3923 Py_DECREF(a);\r
3924 Py_DECREF(b);\r
3925 return c;\r
3926}\r
3927\r
3928static int\r
3929long_coerce(PyObject **pv, PyObject **pw)\r
3930{\r
3931 if (PyInt_Check(*pw)) {\r
3932 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));\r
3933 if (*pw == NULL)\r
3934 return -1;\r
3935 Py_INCREF(*pv);\r
3936 return 0;\r
3937 }\r
3938 else if (PyLong_Check(*pw)) {\r
3939 Py_INCREF(*pv);\r
3940 Py_INCREF(*pw);\r
3941 return 0;\r
3942 }\r
3943 return 1; /* Can't do it */\r
3944}\r
3945\r
3946static PyObject *\r
3947long_long(PyObject *v)\r
3948{\r
3949 if (PyLong_CheckExact(v))\r
3950 Py_INCREF(v);\r
3951 else\r
3952 v = _PyLong_Copy((PyLongObject *)v);\r
3953 return v;\r
3954}\r
3955\r
3956static PyObject *\r
3957long_int(PyObject *v)\r
3958{\r
3959 long x;\r
3960 x = PyLong_AsLong(v);\r
3961 if (PyErr_Occurred()) {\r
3962 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {\r
3963 PyErr_Clear();\r
3964 if (PyLong_CheckExact(v)) {\r
3965 Py_INCREF(v);\r
3966 return v;\r
3967 }\r
3968 else\r
3969 return _PyLong_Copy((PyLongObject *)v);\r
3970 }\r
3971 else\r
3972 return NULL;\r
3973 }\r
3974 return PyInt_FromLong(x);\r
3975}\r
3976\r
3977static PyObject *\r
3978long_float(PyObject *v)\r
3979{\r
3980 double result;\r
3981 result = PyLong_AsDouble(v);\r
3982 if (result == -1.0 && PyErr_Occurred())\r
3983 return NULL;\r
3984 return PyFloat_FromDouble(result);\r
3985}\r
3986\r
3987static PyObject *\r
3988long_oct(PyObject *v)\r
3989{\r
3990 return _PyLong_Format(v, 8, 1, 0);\r
3991}\r
3992\r
3993static PyObject *\r
3994long_hex(PyObject *v)\r
3995{\r
3996 return _PyLong_Format(v, 16, 1, 0);\r
3997}\r
3998\r
3999static PyObject *\r
4000long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);\r
4001\r
4002static PyObject *\r
4003long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
4004{\r
4005 PyObject *x = NULL;\r
4006 int base = -909; /* unlikely! */\r
4007 static char *kwlist[] = {"x", "base", 0};\r
4008\r
4009 if (type != &PyLong_Type)\r
4010 return long_subtype_new(type, args, kwds); /* Wimp out */\r
4011 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,\r
4012 &x, &base))\r
4013 return NULL;\r
4014 if (x == NULL) {\r
4015 if (base != -909) {\r
4016 PyErr_SetString(PyExc_TypeError,\r
4017 "long() missing string argument");\r
4018 return NULL;\r
4019 }\r
4020 return PyLong_FromLong(0L);\r
4021 }\r
4022 if (base == -909)\r
4023 return PyNumber_Long(x);\r
4024 else if (PyString_Check(x)) {\r
4025 /* Since PyLong_FromString doesn't have a length parameter,\r
4026 * check here for possible NULs in the string. */\r
4027 char *string = PyString_AS_STRING(x);\r
4028 if (strlen(string) != (size_t)PyString_Size(x)) {\r
4029 /* create a repr() of the input string,\r
4030 * just like PyLong_FromString does. */\r
4031 PyObject *srepr;\r
4032 srepr = PyObject_Repr(x);\r
4033 if (srepr == NULL)\r
4034 return NULL;\r
4035 PyErr_Format(PyExc_ValueError,\r
4036 "invalid literal for long() with base %d: %s",\r
4037 base, PyString_AS_STRING(srepr));\r
4038 Py_DECREF(srepr);\r
4039 return NULL;\r
4040 }\r
4041 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);\r
4042 }\r
4043#ifdef Py_USING_UNICODE\r
4044 else if (PyUnicode_Check(x))\r
4045 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),\r
4046 PyUnicode_GET_SIZE(x),\r
4047 base);\r
4048#endif\r
4049 else {\r
4050 PyErr_SetString(PyExc_TypeError,\r
4051 "long() can't convert non-string with explicit base");\r
4052 return NULL;\r
4053 }\r
4054}\r
4055\r
4056/* Wimpy, slow approach to tp_new calls for subtypes of long:\r
4057 first create a regular long from whatever arguments we got,\r
4058 then allocate a subtype instance and initialize it from\r
4059 the regular long. The regular long is then thrown away.\r
4060*/\r
4061static PyObject *\r
4062long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
4063{\r
4064 PyLongObject *tmp, *newobj;\r
4065 Py_ssize_t i, n;\r
4066\r
4067 assert(PyType_IsSubtype(type, &PyLong_Type));\r
4068 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);\r
4069 if (tmp == NULL)\r
4070 return NULL;\r
4071 assert(PyLong_CheckExact(tmp));\r
4072 n = Py_SIZE(tmp);\r
4073 if (n < 0)\r
4074 n = -n;\r
4075 newobj = (PyLongObject *)type->tp_alloc(type, n);\r
4076 if (newobj == NULL) {\r
4077 Py_DECREF(tmp);\r
4078 return NULL;\r
4079 }\r
4080 assert(PyLong_Check(newobj));\r
4081 Py_SIZE(newobj) = Py_SIZE(tmp);\r
4082 for (i = 0; i < n; i++)\r
4083 newobj->ob_digit[i] = tmp->ob_digit[i];\r
4084 Py_DECREF(tmp);\r
4085 return (PyObject *)newobj;\r
4086}\r
4087\r
4088static PyObject *\r
4089long_getnewargs(PyLongObject *v)\r
4090{\r
4091 return Py_BuildValue("(N)", _PyLong_Copy(v));\r
4092}\r
4093\r
4094static PyObject *\r
4095long_get0(PyLongObject *v, void *context) {\r
4096 return PyLong_FromLong(0L);\r
4097}\r
4098\r
4099static PyObject *\r
4100long_get1(PyLongObject *v, void *context) {\r
4101 return PyLong_FromLong(1L);\r
4102}\r
4103\r
4104static PyObject *\r
4105long__format__(PyObject *self, PyObject *args)\r
4106{\r
4107 PyObject *format_spec;\r
4108\r
4109 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))\r
4110 return NULL;\r
4111 if (PyBytes_Check(format_spec))\r
4112 return _PyLong_FormatAdvanced(self,\r
4113 PyBytes_AS_STRING(format_spec),\r
4114 PyBytes_GET_SIZE(format_spec));\r
4115 if (PyUnicode_Check(format_spec)) {\r
4116 /* Convert format_spec to a str */\r
4117 PyObject *result;\r
4118 PyObject *str_spec = PyObject_Str(format_spec);\r
4119\r
4120 if (str_spec == NULL)\r
4121 return NULL;\r
4122\r
4123 result = _PyLong_FormatAdvanced(self,\r
4124 PyBytes_AS_STRING(str_spec),\r
4125 PyBytes_GET_SIZE(str_spec));\r
4126\r
4127 Py_DECREF(str_spec);\r
4128 return result;\r
4129 }\r
4130 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");\r
4131 return NULL;\r
4132}\r
4133\r
4134static PyObject *\r
4135long_sizeof(PyLongObject *v)\r
4136{\r
4137 Py_ssize_t res;\r
4138\r
4139 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);\r
4140 return PyInt_FromSsize_t(res);\r
4141}\r
4142\r
4143static PyObject *\r
4144long_bit_length(PyLongObject *v)\r
4145{\r
4146 PyLongObject *result, *x, *y;\r
4147 Py_ssize_t ndigits, msd_bits = 0;\r
4148 digit msd;\r
4149\r
4150 assert(v != NULL);\r
4151 assert(PyLong_Check(v));\r
4152\r
4153 ndigits = ABS(Py_SIZE(v));\r
4154 if (ndigits == 0)\r
4155 return PyInt_FromLong(0);\r
4156\r
4157 msd = v->ob_digit[ndigits-1];\r
4158 while (msd >= 32) {\r
4159 msd_bits += 6;\r
4160 msd >>= 6;\r
4161 }\r
4162 msd_bits += (long)(BitLengthTable[msd]);\r
4163\r
4164 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)\r
4165 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);\r
4166\r
4167 /* expression above may overflow; use Python integers instead */\r
4168 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);\r
4169 if (result == NULL)\r
4170 return NULL;\r
4171 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);\r
4172 if (x == NULL)\r
4173 goto error;\r
4174 y = (PyLongObject *)long_mul(result, x);\r
4175 Py_DECREF(x);\r
4176 if (y == NULL)\r
4177 goto error;\r
4178 Py_DECREF(result);\r
4179 result = y;\r
4180\r
4181 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);\r
4182 if (x == NULL)\r
4183 goto error;\r
4184 y = (PyLongObject *)long_add(result, x);\r
4185 Py_DECREF(x);\r
4186 if (y == NULL)\r
4187 goto error;\r
4188 Py_DECREF(result);\r
4189 result = y;\r
4190\r
4191 return (PyObject *)result;\r
4192\r
4193 error:\r
4194 Py_DECREF(result);\r
4195 return NULL;\r
4196}\r
4197\r
4198PyDoc_STRVAR(long_bit_length_doc,\r
4199"long.bit_length() -> int or long\n\\r
4200\n\\r
4201Number of bits necessary to represent self in binary.\n\\r
4202>>> bin(37L)\n\\r
4203'0b100101'\n\\r
4204>>> (37L).bit_length()\n\\r
42056");\r
4206\r
4207#if 0\r
4208static PyObject *\r
4209long_is_finite(PyObject *v)\r
4210{\r
4211 Py_RETURN_TRUE;\r
4212}\r
4213#endif\r
4214\r
4215static PyMethodDef long_methods[] = {\r
4216 {"conjugate", (PyCFunction)long_long, METH_NOARGS,\r
4217 "Returns self, the complex conjugate of any long."},\r
4218 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,\r
4219 long_bit_length_doc},\r
4220#if 0\r
4221 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,\r
4222 "Returns always True."},\r
4223#endif\r
4224 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,\r
4225 "Truncating an Integral returns itself."},\r
4226 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},\r
4227 {"__format__", (PyCFunction)long__format__, METH_VARARGS},\r
4228 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,\r
4229 "Returns size in memory, in bytes"},\r
4230 {NULL, NULL} /* sentinel */\r
4231};\r
4232\r
4233static PyGetSetDef long_getset[] = {\r
4234 {"real",\r
4235 (getter)long_long, (setter)NULL,\r
4236 "the real part of a complex number",\r
4237 NULL},\r
4238 {"imag",\r
4239 (getter)long_get0, (setter)NULL,\r
4240 "the imaginary part of a complex number",\r
4241 NULL},\r
4242 {"numerator",\r
4243 (getter)long_long, (setter)NULL,\r
4244 "the numerator of a rational number in lowest terms",\r
4245 NULL},\r
4246 {"denominator",\r
4247 (getter)long_get1, (setter)NULL,\r
4248 "the denominator of a rational number in lowest terms",\r
4249 NULL},\r
4250 {NULL} /* Sentinel */\r
4251};\r
4252\r
4253PyDoc_STRVAR(long_doc,\r
4254"long(x=0) -> long\n\\r
4255long(x, base=10) -> long\n\\r
4256\n\\r
4257Convert a number or string to a long integer, or return 0L if no arguments\n\\r
4258are given. If x is floating point, the conversion truncates towards zero.\n\\r
4259\n\\r
4260If x is not a number or if base is given, then x must be a string or\n\\r
4261Unicode object representing an integer literal in the given base. The\n\\r
4262literal can be preceded by '+' or '-' and be surrounded by whitespace.\n\\r
4263The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to\n\\r
4264interpret the base from the string as an integer literal.\n\\r
4265>>> int('0b100', base=0)\n\\r
42664L");\r
4267\r
4268static PyNumberMethods long_as_number = {\r
4269 (binaryfunc)long_add, /*nb_add*/\r
4270 (binaryfunc)long_sub, /*nb_subtract*/\r
4271 (binaryfunc)long_mul, /*nb_multiply*/\r
4272 long_classic_div, /*nb_divide*/\r
4273 long_mod, /*nb_remainder*/\r
4274 long_divmod, /*nb_divmod*/\r
4275 long_pow, /*nb_power*/\r
4276 (unaryfunc)long_neg, /*nb_negative*/\r
4277 (unaryfunc)long_long, /*tp_positive*/\r
4278 (unaryfunc)long_abs, /*tp_absolute*/\r
4279 (inquiry)long_nonzero, /*tp_nonzero*/\r
4280 (unaryfunc)long_invert, /*nb_invert*/\r
4281 long_lshift, /*nb_lshift*/\r
4282 (binaryfunc)long_rshift, /*nb_rshift*/\r
4283 long_and, /*nb_and*/\r
4284 long_xor, /*nb_xor*/\r
4285 long_or, /*nb_or*/\r
4286 long_coerce, /*nb_coerce*/\r
4287 long_int, /*nb_int*/\r
4288 long_long, /*nb_long*/\r
4289 long_float, /*nb_float*/\r
4290 long_oct, /*nb_oct*/\r
4291 long_hex, /*nb_hex*/\r
4292 0, /* nb_inplace_add */\r
4293 0, /* nb_inplace_subtract */\r
4294 0, /* nb_inplace_multiply */\r
4295 0, /* nb_inplace_divide */\r
4296 0, /* nb_inplace_remainder */\r
4297 0, /* nb_inplace_power */\r
4298 0, /* nb_inplace_lshift */\r
4299 0, /* nb_inplace_rshift */\r
4300 0, /* nb_inplace_and */\r
4301 0, /* nb_inplace_xor */\r
4302 0, /* nb_inplace_or */\r
4303 long_div, /* nb_floor_divide */\r
4304 long_true_divide, /* nb_true_divide */\r
4305 0, /* nb_inplace_floor_divide */\r
4306 0, /* nb_inplace_true_divide */\r
4307 long_long, /* nb_index */\r
4308};\r
4309\r
4310PyTypeObject PyLong_Type = {\r
4311 PyObject_HEAD_INIT(&PyType_Type)\r
4312 0, /* ob_size */\r
4313 "long", /* tp_name */\r
4314 offsetof(PyLongObject, ob_digit), /* tp_basicsize */\r
4315 sizeof(digit), /* tp_itemsize */\r
4316 long_dealloc, /* tp_dealloc */\r
4317 0, /* tp_print */\r
4318 0, /* tp_getattr */\r
4319 0, /* tp_setattr */\r
4320 (cmpfunc)long_compare, /* tp_compare */\r
4321 long_repr, /* tp_repr */\r
4322 &long_as_number, /* tp_as_number */\r
4323 0, /* tp_as_sequence */\r
4324 0, /* tp_as_mapping */\r
4325 (hashfunc)long_hash, /* tp_hash */\r
4326 0, /* tp_call */\r
4327 long_str, /* tp_str */\r
4328 PyObject_GenericGetAttr, /* tp_getattro */\r
4329 0, /* tp_setattro */\r
4330 0, /* tp_as_buffer */\r
4331 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
4332 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */\r
4333 long_doc, /* tp_doc */\r
4334 0, /* tp_traverse */\r
4335 0, /* tp_clear */\r
4336 0, /* tp_richcompare */\r
4337 0, /* tp_weaklistoffset */\r
4338 0, /* tp_iter */\r
4339 0, /* tp_iternext */\r
4340 long_methods, /* tp_methods */\r
4341 0, /* tp_members */\r
4342 long_getset, /* tp_getset */\r
4343 0, /* tp_base */\r
4344 0, /* tp_dict */\r
4345 0, /* tp_descr_get */\r
4346 0, /* tp_descr_set */\r
4347 0, /* tp_dictoffset */\r
4348 0, /* tp_init */\r
4349 0, /* tp_alloc */\r
4350 long_new, /* tp_new */\r
4351 PyObject_Del, /* tp_free */\r
4352};\r
4353\r
4354static PyTypeObject Long_InfoType;\r
4355\r
4356PyDoc_STRVAR(long_info__doc__,\r
4357"sys.long_info\n\\r
4358\n\\r
4359A struct sequence that holds information about Python's\n\\r
4360internal representation of integers. The attributes are read only.");\r
4361\r
4362static PyStructSequence_Field long_info_fields[] = {\r
4363 {"bits_per_digit", "size of a digit in bits"},\r
4364 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},\r
4365 {NULL, NULL}\r
4366};\r
4367\r
4368static PyStructSequence_Desc long_info_desc = {\r
4369 "sys.long_info", /* name */\r
4370 long_info__doc__, /* doc */\r
4371 long_info_fields, /* fields */\r
4372 2 /* number of fields */\r
4373};\r
4374\r
4375PyObject *\r
4376PyLong_GetInfo(void)\r
4377{\r
4378 PyObject* long_info;\r
4379 int field = 0;\r
4380 long_info = PyStructSequence_New(&Long_InfoType);\r
4381 if (long_info == NULL)\r
4382 return NULL;\r
4383 PyStructSequence_SET_ITEM(long_info, field++,\r
4384 PyInt_FromLong(PyLong_SHIFT));\r
4385 PyStructSequence_SET_ITEM(long_info, field++,\r
4386 PyInt_FromLong(sizeof(digit)));\r
4387 if (PyErr_Occurred()) {\r
4388 Py_CLEAR(long_info);\r
4389 return NULL;\r
4390 }\r
4391 return long_info;\r
4392}\r
4393\r
4394int\r
4395_PyLong_Init(void)\r
4396{\r
4397 /* initialize long_info */\r
4398 if (Long_InfoType.tp_name == 0)\r
4399 PyStructSequence_InitType(&Long_InfoType, &long_info_desc);\r
4400 return 1;\r
4401}\r