PageRenderTime 72ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/longobject.c

http://unladen-swallow.googlecode.com/
C | 3590 lines | 2711 code | 340 blank | 539 comment | 728 complexity | 251be7320969b50e535e9d86a3bcbd95 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* Long (arbitrary precision) integer object implementation */
  2. /* XXX The functional organization of this file is terrible */
  3. #include "Python.h"
  4. #include "longintrepr.h"
  5. #include <ctype.h>
  6. /* For long multiplication, use the O(N**2) school algorithm unless
  7. * both operands contain more than KARATSUBA_CUTOFF digits (this
  8. * being an internal Python long digit, in base PyLong_BASE).
  9. */
  10. #define KARATSUBA_CUTOFF 70
  11. #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
  12. /* For exponentiation, use the binary left-to-right algorithm
  13. * unless the exponent contains more than FIVEARY_CUTOFF digits.
  14. * In that case, do 5 bits at a time. The potential drawback is that
  15. * a table of 2**5 intermediate results is computed.
  16. */
  17. #define FIVEARY_CUTOFF 8
  18. #define ABS(x) ((x) < 0 ? -(x) : (x))
  19. #undef MIN
  20. #undef MAX
  21. #define MAX(x, y) ((x) < (y) ? (y) : (x))
  22. #define MIN(x, y) ((x) > (y) ? (y) : (x))
  23. /* Forward */
  24. static PyLongObject *long_normalize(PyLongObject *);
  25. static PyLongObject *mul1(PyLongObject *, wdigit);
  26. static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
  27. static PyLongObject *divrem1(PyLongObject *, digit, digit *);
  28. #define SIGCHECK(PyTryBlock) \
  29. if (--_Py_Ticker < 0) { \
  30. _Py_Ticker = _Py_CheckInterval; \
  31. if (PyErr_CheckSignals()) PyTryBlock \
  32. }
  33. /* Normalize (remove leading zeros from) a long int object.
  34. Doesn't attempt to free the storage--in most cases, due to the nature
  35. of the algorithms used, this could save at most be one word anyway. */
  36. static PyLongObject *
  37. long_normalize(register PyLongObject *v)
  38. {
  39. Py_ssize_t j = ABS(Py_SIZE(v));
  40. Py_ssize_t i = j;
  41. while (i > 0 && v->ob_digit[i-1] == 0)
  42. --i;
  43. if (i != j)
  44. Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
  45. return v;
  46. }
  47. /* Allocate a new long int object with size digits.
  48. Return NULL and set exception if we run out of memory. */
  49. PyLongObject *
  50. _PyLong_New(Py_ssize_t size)
  51. {
  52. if (size > PY_SSIZE_T_MAX) {
  53. PyErr_NoMemory();
  54. return NULL;
  55. }
  56. /* coverity[ampersand_in_size] */
  57. /* XXX(nnorwitz): This can overflow --
  58. PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
  59. return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
  60. }
  61. PyObject *
  62. _PyLong_Copy(PyLongObject *src)
  63. {
  64. PyLongObject *result;
  65. Py_ssize_t i;
  66. assert(src != NULL);
  67. i = src->ob_size;
  68. if (i < 0)
  69. i = -(i);
  70. result = _PyLong_New(i);
  71. if (result != NULL) {
  72. result->ob_size = src->ob_size;
  73. while (--i >= 0)
  74. result->ob_digit[i] = src->ob_digit[i];
  75. }
  76. return (PyObject *)result;
  77. }
  78. /* Create a new long int object from a C long int */
  79. PyObject *
  80. PyLong_FromLong(long ival)
  81. {
  82. PyLongObject *v;
  83. unsigned long abs_ival;
  84. unsigned long t; /* unsigned so >> doesn't propagate sign bit */
  85. int ndigits = 0;
  86. int negative = 0;
  87. if (ival < 0) {
  88. /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
  89. ANSI C says that the result of -ival is undefined when ival
  90. == LONG_MIN. Hence the following workaround. */
  91. abs_ival = (unsigned long)(-1-ival) + 1;
  92. negative = 1;
  93. }
  94. else {
  95. abs_ival = (unsigned long)ival;
  96. }
  97. /* Count the number of Python digits.
  98. We used to pick 5 ("big enough for anything"), but that's a
  99. waste of time and space given that 5*15 = 75 bits are rarely
  100. needed. */
  101. t = abs_ival;
  102. while (t) {
  103. ++ndigits;
  104. t >>= PyLong_SHIFT;
  105. }
  106. v = _PyLong_New(ndigits);
  107. if (v != NULL) {
  108. digit *p = v->ob_digit;
  109. v->ob_size = negative ? -ndigits : ndigits;
  110. t = abs_ival;
  111. while (t) {
  112. *p++ = (digit)(t & PyLong_MASK);
  113. t >>= PyLong_SHIFT;
  114. }
  115. }
  116. return (PyObject *)v;
  117. }
  118. /* Create a new long int object from a C unsigned long int */
  119. PyObject *
  120. PyLong_FromUnsignedLong(unsigned long ival)
  121. {
  122. PyLongObject *v;
  123. unsigned long t;
  124. int ndigits = 0;
  125. /* Count the number of Python digits. */
  126. t = (unsigned long)ival;
  127. while (t) {
  128. ++ndigits;
  129. t >>= PyLong_SHIFT;
  130. }
  131. v = _PyLong_New(ndigits);
  132. if (v != NULL) {
  133. digit *p = v->ob_digit;
  134. Py_SIZE(v) = ndigits;
  135. while (ival) {
  136. *p++ = (digit)(ival & PyLong_MASK);
  137. ival >>= PyLong_SHIFT;
  138. }
  139. }
  140. return (PyObject *)v;
  141. }
  142. /* Create a new long int object from a C double */
  143. PyObject *
  144. PyLong_FromDouble(double dval)
  145. {
  146. PyLongObject *v;
  147. double frac;
  148. int i, ndig, expo, neg;
  149. neg = 0;
  150. if (Py_IS_INFINITY(dval)) {
  151. PyErr_SetString(PyExc_OverflowError,
  152. "cannot convert float infinity to integer");
  153. return NULL;
  154. }
  155. if (Py_IS_NAN(dval)) {
  156. PyErr_SetString(PyExc_ValueError,
  157. "cannot convert float NaN to integer");
  158. return NULL;
  159. }
  160. if (dval < 0.0) {
  161. neg = 1;
  162. dval = -dval;
  163. }
  164. frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
  165. if (expo <= 0)
  166. return PyLong_FromLong(0L);
  167. ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
  168. v = _PyLong_New(ndig);
  169. if (v == NULL)
  170. return NULL;
  171. frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
  172. for (i = ndig; --i >= 0; ) {
  173. long bits = (long)frac;
  174. v->ob_digit[i] = (digit) bits;
  175. frac = frac - (double)bits;
  176. frac = ldexp(frac, PyLong_SHIFT);
  177. }
  178. if (neg)
  179. Py_SIZE(v) = -(Py_SIZE(v));
  180. return (PyObject *)v;
  181. }
  182. /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
  183. * anything about what happens when a signed integer operation overflows,
  184. * and some compilers think they're doing you a favor by being "clever"
  185. * then. The bit pattern for the largest postive signed long is
  186. * (unsigned long)LONG_MAX, and for the smallest negative signed long
  187. * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
  188. * However, some other compilers warn about applying unary minus to an
  189. * unsigned operand. Hence the weird "0-".
  190. */
  191. #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
  192. #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
  193. /* Get a C long int from a long int object.
  194. Returns -1 and sets an error condition if overflow occurs. */
  195. long
  196. PyLong_AsLong(PyObject *vv)
  197. {
  198. /* This version by Tim Peters */
  199. register PyLongObject *v;
  200. unsigned long x, prev;
  201. Py_ssize_t i;
  202. int sign;
  203. if (vv == NULL || !PyLong_Check(vv)) {
  204. if (vv != NULL && PyInt_Check(vv))
  205. return PyInt_AsLong(vv);
  206. PyErr_BadInternalCall();
  207. return -1;
  208. }
  209. v = (PyLongObject *)vv;
  210. i = v->ob_size;
  211. sign = 1;
  212. x = 0;
  213. if (i < 0) {
  214. sign = -1;
  215. i = -(i);
  216. }
  217. while (--i >= 0) {
  218. prev = x;
  219. x = (x << PyLong_SHIFT) + v->ob_digit[i];
  220. if ((x >> PyLong_SHIFT) != prev)
  221. goto overflow;
  222. }
  223. /* Haven't lost any bits, but casting to long requires extra care
  224. * (see comment above).
  225. */
  226. if (x <= (unsigned long)LONG_MAX) {
  227. return (long)x * sign;
  228. }
  229. else if (sign < 0 && x == PY_ABS_LONG_MIN) {
  230. return LONG_MIN;
  231. }
  232. /* else overflow */
  233. overflow:
  234. PyErr_SetString(PyExc_OverflowError,
  235. "long int too large to convert to int");
  236. return -1;
  237. }
  238. /* Get a Py_ssize_t from a long int object.
  239. Returns -1 and sets an error condition if overflow occurs. */
  240. Py_ssize_t
  241. PyLong_AsSsize_t(PyObject *vv) {
  242. register PyLongObject *v;
  243. size_t x, prev;
  244. Py_ssize_t i;
  245. int sign;
  246. if (vv == NULL || !PyLong_Check(vv)) {
  247. PyErr_BadInternalCall();
  248. return -1;
  249. }
  250. v = (PyLongObject *)vv;
  251. i = v->ob_size;
  252. sign = 1;
  253. x = 0;
  254. if (i < 0) {
  255. sign = -1;
  256. i = -(i);
  257. }
  258. while (--i >= 0) {
  259. prev = x;
  260. x = (x << PyLong_SHIFT) + v->ob_digit[i];
  261. if ((x >> PyLong_SHIFT) != prev)
  262. goto overflow;
  263. }
  264. /* Haven't lost any bits, but casting to a signed type requires
  265. * extra care (see comment above).
  266. */
  267. if (x <= (size_t)PY_SSIZE_T_MAX) {
  268. return (Py_ssize_t)x * sign;
  269. }
  270. else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
  271. return PY_SSIZE_T_MIN;
  272. }
  273. /* else overflow */
  274. overflow:
  275. PyErr_SetString(PyExc_OverflowError,
  276. "long int too large to convert to int");
  277. return -1;
  278. }
  279. /* Get a C unsigned long int from a long int object.
  280. Returns -1 and sets an error condition if overflow occurs. */
  281. unsigned long
  282. PyLong_AsUnsignedLong(PyObject *vv)
  283. {
  284. register PyLongObject *v;
  285. unsigned long x, prev;
  286. Py_ssize_t i;
  287. if (vv == NULL || !PyLong_Check(vv)) {
  288. if (vv != NULL && PyInt_Check(vv)) {
  289. long val = PyInt_AsLong(vv);
  290. if (val < 0) {
  291. PyErr_SetString(PyExc_OverflowError,
  292. "can't convert negative value to unsigned long");
  293. return (unsigned long) -1;
  294. }
  295. return val;
  296. }
  297. PyErr_BadInternalCall();
  298. return (unsigned long) -1;
  299. }
  300. v = (PyLongObject *)vv;
  301. i = Py_SIZE(v);
  302. x = 0;
  303. if (i < 0) {
  304. PyErr_SetString(PyExc_OverflowError,
  305. "can't convert negative value to unsigned long");
  306. return (unsigned long) -1;
  307. }
  308. while (--i >= 0) {
  309. prev = x;
  310. x = (x << PyLong_SHIFT) + v->ob_digit[i];
  311. if ((x >> PyLong_SHIFT) != prev) {
  312. PyErr_SetString(PyExc_OverflowError,
  313. "long int too large to convert");
  314. return (unsigned long) -1;
  315. }
  316. }
  317. return x;
  318. }
  319. /* Get a C unsigned long int from a long int object, ignoring the high bits.
  320. Returns -1 and sets an error condition if an error occurs. */
  321. unsigned long
  322. PyLong_AsUnsignedLongMask(PyObject *vv)
  323. {
  324. register PyLongObject *v;
  325. unsigned long x;
  326. Py_ssize_t i;
  327. int sign;
  328. if (vv == NULL || !PyLong_Check(vv)) {
  329. if (vv != NULL && PyInt_Check(vv))
  330. return PyInt_AsUnsignedLongMask(vv);
  331. PyErr_BadInternalCall();
  332. return (unsigned long) -1;
  333. }
  334. v = (PyLongObject *)vv;
  335. i = v->ob_size;
  336. sign = 1;
  337. x = 0;
  338. if (i < 0) {
  339. sign = -1;
  340. i = -i;
  341. }
  342. while (--i >= 0) {
  343. x = (x << PyLong_SHIFT) + v->ob_digit[i];
  344. }
  345. return x * sign;
  346. }
  347. int
  348. _PyLong_Sign(PyObject *vv)
  349. {
  350. PyLongObject *v = (PyLongObject *)vv;
  351. assert(v != NULL);
  352. assert(PyLong_Check(v));
  353. return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
  354. }
  355. size_t
  356. _PyLong_NumBits(PyObject *vv)
  357. {
  358. PyLongObject *v = (PyLongObject *)vv;
  359. size_t result = 0;
  360. Py_ssize_t ndigits;
  361. assert(v != NULL);
  362. assert(PyLong_Check(v));
  363. ndigits = ABS(Py_SIZE(v));
  364. assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
  365. if (ndigits > 0) {
  366. digit msd = v->ob_digit[ndigits - 1];
  367. result = (ndigits - 1) * PyLong_SHIFT;
  368. if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
  369. goto Overflow;
  370. do {
  371. ++result;
  372. if (result == 0)
  373. goto Overflow;
  374. msd >>= 1;
  375. } while (msd);
  376. }
  377. return result;
  378. Overflow:
  379. PyErr_SetString(PyExc_OverflowError, "long has too many bits "
  380. "to express in a platform size_t");
  381. return (size_t)-1;
  382. }
  383. PyObject *
  384. _PyLong_FromByteArray(const unsigned char* bytes, size_t n,
  385. int little_endian, int is_signed)
  386. {
  387. const unsigned char* pstartbyte;/* LSB of bytes */
  388. int incr; /* direction to move pstartbyte */
  389. const unsigned char* pendbyte; /* MSB of bytes */
  390. size_t numsignificantbytes; /* number of bytes that matter */
  391. size_t ndigits; /* number of Python long digits */
  392. PyLongObject* v; /* result */
  393. int idigit = 0; /* next free index in v->ob_digit */
  394. if (n == 0)
  395. return PyLong_FromLong(0L);
  396. if (little_endian) {
  397. pstartbyte = bytes;
  398. pendbyte = bytes + n - 1;
  399. incr = 1;
  400. }
  401. else {
  402. pstartbyte = bytes + n - 1;
  403. pendbyte = bytes;
  404. incr = -1;
  405. }
  406. if (is_signed)
  407. is_signed = *pendbyte >= 0x80;
  408. /* Compute numsignificantbytes. This consists of finding the most
  409. significant byte. Leading 0 bytes are insignficant if the number
  410. is positive, and leading 0xff bytes if negative. */
  411. {
  412. size_t i;
  413. const unsigned char* p = pendbyte;
  414. const int pincr = -incr; /* search MSB to LSB */
  415. const unsigned char insignficant = is_signed ? 0xff : 0x00;
  416. for (i = 0; i < n; ++i, p += pincr) {
  417. if (*p != insignficant)
  418. break;
  419. }
  420. numsignificantbytes = n - i;
  421. /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
  422. actually has 2 significant bytes. OTOH, 0xff0001 ==
  423. -0x00ffff, so we wouldn't *need* to bump it there; but we
  424. do for 0xffff = -0x0001. To be safe without bothering to
  425. check every case, bump it regardless. */
  426. if (is_signed && numsignificantbytes < n)
  427. ++numsignificantbytes;
  428. }
  429. /* How many Python long digits do we need? We have
  430. 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
  431. bits, so it's the ceiling of the quotient. */
  432. ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
  433. if (ndigits > (size_t)INT_MAX)
  434. return PyErr_NoMemory();
  435. v = _PyLong_New((int)ndigits);
  436. if (v == NULL)
  437. return NULL;
  438. /* Copy the bits over. The tricky parts are computing 2's-comp on
  439. the fly for signed numbers, and dealing with the mismatch between
  440. 8-bit bytes and (probably) 15-bit Python digits.*/
  441. {
  442. size_t i;
  443. twodigits carry = 1; /* for 2's-comp calculation */
  444. twodigits accum = 0; /* sliding register */
  445. unsigned int accumbits = 0; /* number of bits in accum */
  446. const unsigned char* p = pstartbyte;
  447. for (i = 0; i < numsignificantbytes; ++i, p += incr) {
  448. twodigits thisbyte = *p;
  449. /* Compute correction for 2's comp, if needed. */
  450. if (is_signed) {
  451. thisbyte = (0xff ^ thisbyte) + carry;
  452. carry = thisbyte >> 8;
  453. thisbyte &= 0xff;
  454. }
  455. /* Because we're going LSB to MSB, thisbyte is
  456. more significant than what's already in accum,
  457. so needs to be prepended to accum. */
  458. accum |= (twodigits)thisbyte << accumbits;
  459. accumbits += 8;
  460. if (accumbits >= PyLong_SHIFT) {
  461. /* There's enough to fill a Python digit. */
  462. assert(idigit < (int)ndigits);
  463. v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
  464. ++idigit;
  465. accum >>= PyLong_SHIFT;
  466. accumbits -= PyLong_SHIFT;
  467. assert(accumbits < PyLong_SHIFT);
  468. }
  469. }
  470. assert(accumbits < PyLong_SHIFT);
  471. if (accumbits) {
  472. assert(idigit < (int)ndigits);
  473. v->ob_digit[idigit] = (digit)accum;
  474. ++idigit;
  475. }
  476. }
  477. Py_SIZE(v) = is_signed ? -idigit : idigit;
  478. return (PyObject *)long_normalize(v);
  479. }
  480. int
  481. _PyLong_AsByteArray(PyLongObject* v,
  482. unsigned char* bytes, size_t n,
  483. int little_endian, int is_signed)
  484. {
  485. Py_ssize_t i; /* index into v->ob_digit */
  486. Py_ssize_t ndigits; /* |v->ob_size| */
  487. twodigits accum; /* sliding register */
  488. unsigned int accumbits; /* # bits in accum */
  489. int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
  490. digit carry; /* for computing 2's-comp */
  491. size_t j; /* # bytes filled */
  492. unsigned char* p; /* pointer to next byte in bytes */
  493. int pincr; /* direction to move p */
  494. assert(v != NULL && PyLong_Check(v));
  495. if (Py_SIZE(v) < 0) {
  496. ndigits = -(Py_SIZE(v));
  497. if (!is_signed) {
  498. PyErr_SetString(PyExc_TypeError,
  499. "can't convert negative long to unsigned");
  500. return -1;
  501. }
  502. do_twos_comp = 1;
  503. }
  504. else {
  505. ndigits = Py_SIZE(v);
  506. do_twos_comp = 0;
  507. }
  508. if (little_endian) {
  509. p = bytes;
  510. pincr = 1;
  511. }
  512. else {
  513. p = bytes + n - 1;
  514. pincr = -1;
  515. }
  516. /* Copy over all the Python digits.
  517. It's crucial that every Python digit except for the MSD contribute
  518. exactly PyLong_SHIFT bits to the total, so first assert that the long is
  519. normalized. */
  520. assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
  521. j = 0;
  522. accum = 0;
  523. accumbits = 0;
  524. carry = do_twos_comp ? 1 : 0;
  525. for (i = 0; i < ndigits; ++i) {
  526. digit thisdigit = v->ob_digit[i];
  527. if (do_twos_comp) {
  528. thisdigit = (thisdigit ^ PyLong_MASK) + carry;
  529. carry = thisdigit >> PyLong_SHIFT;
  530. thisdigit &= PyLong_MASK;
  531. }
  532. /* Because we're going LSB to MSB, thisdigit is more
  533. significant than what's already in accum, so needs to be
  534. prepended to accum. */
  535. accum |= (twodigits)thisdigit << accumbits;
  536. /* The most-significant digit may be (probably is) at least
  537. partly empty. */
  538. if (i == ndigits - 1) {
  539. /* Count # of sign bits -- they needn't be stored,
  540. * although for signed conversion we need later to
  541. * make sure at least one sign bit gets stored. */
  542. digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
  543. thisdigit;
  544. while (s != 0) {
  545. s >>= 1;
  546. accumbits++;
  547. }
  548. }
  549. else
  550. accumbits += PyLong_SHIFT;
  551. /* Store as many bytes as possible. */
  552. while (accumbits >= 8) {
  553. if (j >= n)
  554. goto Overflow;
  555. ++j;
  556. *p = (unsigned char)(accum & 0xff);
  557. p += pincr;
  558. accumbits -= 8;
  559. accum >>= 8;
  560. }
  561. }
  562. /* Store the straggler (if any). */
  563. assert(accumbits < 8);
  564. assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
  565. if (accumbits > 0) {
  566. if (j >= n)
  567. goto Overflow;
  568. ++j;
  569. if (do_twos_comp) {
  570. /* Fill leading bits of the byte with sign bits
  571. (appropriately pretending that the long had an
  572. infinite supply of sign bits). */
  573. accum |= (~(twodigits)0) << accumbits;
  574. }
  575. *p = (unsigned char)(accum & 0xff);
  576. p += pincr;
  577. }
  578. else if (j == n && n > 0 && is_signed) {
  579. /* The main loop filled the byte array exactly, so the code
  580. just above didn't get to ensure there's a sign bit, and the
  581. loop below wouldn't add one either. Make sure a sign bit
  582. exists. */
  583. unsigned char msb = *(p - pincr);
  584. int sign_bit_set = msb >= 0x80;
  585. assert(accumbits == 0);
  586. if (sign_bit_set == do_twos_comp)
  587. return 0;
  588. else
  589. goto Overflow;
  590. }
  591. /* Fill remaining bytes with copies of the sign bit. */
  592. {
  593. unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
  594. for ( ; j < n; ++j, p += pincr)
  595. *p = signbyte;
  596. }
  597. return 0;
  598. Overflow:
  599. PyErr_SetString(PyExc_OverflowError, "long too big to convert");
  600. return -1;
  601. }
  602. double
  603. _PyLong_AsScaledDouble(PyObject *vv, int *exponent)
  604. {
  605. /* NBITS_WANTED should be > the number of bits in a double's precision,
  606. but small enough so that 2**NBITS_WANTED is within the normal double
  607. range. nbitsneeded is set to 1 less than that because the most-significant
  608. Python digit contains at least 1 significant bit, but we don't want to
  609. bother counting them (catering to the worst case cheaply).
  610. 57 is one more than VAX-D double precision; I (Tim) don't know of a double
  611. format with more precision than that; it's 1 larger so that we add in at
  612. least one round bit to stand in for the ignored least-significant bits.
  613. */
  614. #define NBITS_WANTED 57
  615. PyLongObject *v;
  616. double x;
  617. const double multiplier = (double)(1L << PyLong_SHIFT);
  618. Py_ssize_t i;
  619. int sign;
  620. int nbitsneeded;
  621. if (vv == NULL || !PyLong_Check(vv)) {
  622. PyErr_BadInternalCall();
  623. return -1;
  624. }
  625. v = (PyLongObject *)vv;
  626. i = Py_SIZE(v);
  627. sign = 1;
  628. if (i < 0) {
  629. sign = -1;
  630. i = -(i);
  631. }
  632. else if (i == 0) {
  633. *exponent = 0;
  634. return 0.0;
  635. }
  636. --i;
  637. x = (double)v->ob_digit[i];
  638. nbitsneeded = NBITS_WANTED - 1;
  639. /* Invariant: i Python digits remain unaccounted for. */
  640. while (i > 0 && nbitsneeded > 0) {
  641. --i;
  642. x = x * multiplier + (double)v->ob_digit[i];
  643. nbitsneeded -= PyLong_SHIFT;
  644. }
  645. /* There are i digits we didn't shift in. Pretending they're all
  646. zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
  647. *exponent = i;
  648. assert(x > 0.0);
  649. return x * sign;
  650. #undef NBITS_WANTED
  651. }
  652. /* Get a C double from a long int object. */
  653. double
  654. PyLong_AsDouble(PyObject *vv)
  655. {
  656. int e = -1;
  657. double x;
  658. if (vv == NULL || !PyLong_Check(vv)) {
  659. PyErr_BadInternalCall();
  660. return -1;
  661. }
  662. x = _PyLong_AsScaledDouble(vv, &e);
  663. if (x == -1.0 && PyErr_Occurred())
  664. return -1.0;
  665. /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
  666. set correctly after a successful _PyLong_AsScaledDouble() call */
  667. assert(e >= 0);
  668. if (e > INT_MAX / PyLong_SHIFT)
  669. goto overflow;
  670. errno = 0;
  671. x = ldexp(x, e * PyLong_SHIFT);
  672. if (Py_OVERFLOWED(x))
  673. goto overflow;
  674. return x;
  675. overflow:
  676. PyErr_SetString(PyExc_OverflowError,
  677. "long int too large to convert to float");
  678. return -1.0;
  679. }
  680. /* Create a new long (or int) object from a C pointer */
  681. PyObject *
  682. PyLong_FromVoidPtr(void *p)
  683. {
  684. #if SIZEOF_VOID_P <= SIZEOF_LONG
  685. if ((long)p < 0)
  686. return PyLong_FromUnsignedLong((unsigned long)p);
  687. return PyInt_FromLong((long)p);
  688. #else
  689. #ifndef HAVE_LONG_LONG
  690. # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
  691. #endif
  692. #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
  693. # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
  694. #endif
  695. /* optimize null pointers */
  696. if (p == NULL)
  697. return PyInt_FromLong(0);
  698. return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
  699. #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
  700. }
  701. /* Get a C pointer from a long object (or an int object in some cases) */
  702. void *
  703. PyLong_AsVoidPtr(PyObject *vv)
  704. {
  705. /* This function will allow int or long objects. If vv is neither,
  706. then the PyLong_AsLong*() functions will raise the exception:
  707. PyExc_SystemError, "bad argument to internal function"
  708. */
  709. #if SIZEOF_VOID_P <= SIZEOF_LONG
  710. long x;
  711. if (PyInt_Check(vv))
  712. x = PyInt_AS_LONG(vv);
  713. else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
  714. x = PyLong_AsLong(vv);
  715. else
  716. x = PyLong_AsUnsignedLong(vv);
  717. #else
  718. #ifndef HAVE_LONG_LONG
  719. # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
  720. #endif
  721. #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
  722. # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
  723. #endif
  724. PY_LONG_LONG x;
  725. if (PyInt_Check(vv))
  726. x = PyInt_AS_LONG(vv);
  727. else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
  728. x = PyLong_AsLongLong(vv);
  729. else
  730. x = PyLong_AsUnsignedLongLong(vv);
  731. #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
  732. if (x == -1 && PyErr_Occurred())
  733. return NULL;
  734. return (void *)x;
  735. }
  736. #ifdef HAVE_LONG_LONG
  737. /* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
  738. * rewritten to use the newer PyLong_{As,From}ByteArray API.
  739. */
  740. #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
  741. /* Create a new long int object from a C PY_LONG_LONG int. */
  742. PyObject *
  743. PyLong_FromLongLong(PY_LONG_LONG ival)
  744. {
  745. PyLongObject *v;
  746. unsigned PY_LONG_LONG abs_ival;
  747. unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
  748. int ndigits = 0;
  749. int negative = 0;
  750. if (ival < 0) {
  751. /* avoid signed overflow on negation; see comments
  752. in PyLong_FromLong above. */
  753. abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
  754. negative = 1;
  755. }
  756. else {
  757. abs_ival = (unsigned PY_LONG_LONG)ival;
  758. }
  759. /* Count the number of Python digits.
  760. We used to pick 5 ("big enough for anything"), but that's a
  761. waste of time and space given that 5*15 = 75 bits are rarely
  762. needed. */
  763. t = abs_ival;
  764. while (t) {
  765. ++ndigits;
  766. t >>= PyLong_SHIFT;
  767. }
  768. v = _PyLong_New(ndigits);
  769. if (v != NULL) {
  770. digit *p = v->ob_digit;
  771. Py_SIZE(v) = negative ? -ndigits : ndigits;
  772. t = abs_ival;
  773. while (t) {
  774. *p++ = (digit)(t & PyLong_MASK);
  775. t >>= PyLong_SHIFT;
  776. }
  777. }
  778. return (PyObject *)v;
  779. }
  780. /* Create a new long int object from a C unsigned PY_LONG_LONG int. */
  781. PyObject *
  782. PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
  783. {
  784. PyLongObject *v;
  785. unsigned PY_LONG_LONG t;
  786. int ndigits = 0;
  787. /* Count the number of Python digits. */
  788. t = (unsigned PY_LONG_LONG)ival;
  789. while (t) {
  790. ++ndigits;
  791. t >>= PyLong_SHIFT;
  792. }
  793. v = _PyLong_New(ndigits);
  794. if (v != NULL) {
  795. digit *p = v->ob_digit;
  796. Py_SIZE(v) = ndigits;
  797. while (ival) {
  798. *p++ = (digit)(ival & PyLong_MASK);
  799. ival >>= PyLong_SHIFT;
  800. }
  801. }
  802. return (PyObject *)v;
  803. }
  804. /* Create a new long int object from a C Py_ssize_t. */
  805. PyObject *
  806. PyLong_FromSsize_t(Py_ssize_t ival)
  807. {
  808. Py_ssize_t bytes = ival;
  809. int one = 1;
  810. return _PyLong_FromByteArray(
  811. (unsigned char *)&bytes,
  812. SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
  813. }
  814. /* Create a new long int object from a C size_t. */
  815. PyObject *
  816. PyLong_FromSize_t(size_t ival)
  817. {
  818. size_t bytes = ival;
  819. int one = 1;
  820. return _PyLong_FromByteArray(
  821. (unsigned char *)&bytes,
  822. SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
  823. }
  824. /* Get a C PY_LONG_LONG int from a long int object.
  825. Return -1 and set an error if overflow occurs. */
  826. PY_LONG_LONG
  827. PyLong_AsLongLong(PyObject *vv)
  828. {
  829. PY_LONG_LONG bytes;
  830. int one = 1;
  831. int res;
  832. if (vv == NULL) {
  833. PyErr_BadInternalCall();
  834. return -1;
  835. }
  836. if (!PyLong_Check(vv)) {
  837. PyNumberMethods *nb;
  838. PyObject *io;
  839. if (PyInt_Check(vv))
  840. return (PY_LONG_LONG)PyInt_AsLong(vv);
  841. if ((nb = vv->ob_type->tp_as_number) == NULL ||
  842. nb->nb_int == NULL) {
  843. PyErr_SetString(PyExc_TypeError, "an integer is required");
  844. return -1;
  845. }
  846. io = (*nb->nb_int) (vv);
  847. if (io == NULL)
  848. return -1;
  849. if (PyInt_Check(io)) {
  850. bytes = PyInt_AsLong(io);
  851. Py_DECREF(io);
  852. return bytes;
  853. }
  854. if (PyLong_Check(io)) {
  855. bytes = PyLong_AsLongLong(io);
  856. Py_DECREF(io);
  857. return bytes;
  858. }
  859. Py_DECREF(io);
  860. PyErr_SetString(PyExc_TypeError, "integer conversion failed");
  861. return -1;
  862. }
  863. res = _PyLong_AsByteArray(
  864. (PyLongObject *)vv, (unsigned char *)&bytes,
  865. SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
  866. /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
  867. if (res < 0)
  868. return (PY_LONG_LONG)-1;
  869. else
  870. return bytes;
  871. }
  872. /* Get a C unsigned PY_LONG_LONG int from a long int object.
  873. Return -1 and set an error if overflow occurs. */
  874. unsigned PY_LONG_LONG
  875. PyLong_AsUnsignedLongLong(PyObject *vv)
  876. {
  877. unsigned PY_LONG_LONG bytes;
  878. int one = 1;
  879. int res;
  880. if (vv == NULL || !PyLong_Check(vv)) {
  881. PyErr_BadInternalCall();
  882. return (unsigned PY_LONG_LONG)-1;
  883. }
  884. res = _PyLong_AsByteArray(
  885. (PyLongObject *)vv, (unsigned char *)&bytes,
  886. SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
  887. /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
  888. if (res < 0)
  889. return (unsigned PY_LONG_LONG)res;
  890. else
  891. return bytes;
  892. }
  893. /* Get a C unsigned long int from a long int object, ignoring the high bits.
  894. Returns -1 and sets an error condition if an error occurs. */
  895. unsigned PY_LONG_LONG
  896. PyLong_AsUnsignedLongLongMask(PyObject *vv)
  897. {
  898. register PyLongObject *v;
  899. unsigned PY_LONG_LONG x;
  900. Py_ssize_t i;
  901. int sign;
  902. if (vv == NULL || !PyLong_Check(vv)) {
  903. PyErr_BadInternalCall();
  904. return (unsigned long) -1;
  905. }
  906. v = (PyLongObject *)vv;
  907. i = v->ob_size;
  908. sign = 1;
  909. x = 0;
  910. if (i < 0) {
  911. sign = -1;
  912. i = -i;
  913. }
  914. while (--i >= 0) {
  915. x = (x << PyLong_SHIFT) + v->ob_digit[i];
  916. }
  917. return x * sign;
  918. }
  919. #undef IS_LITTLE_ENDIAN
  920. #endif /* HAVE_LONG_LONG */
  921. static int
  922. convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
  923. if (PyLong_Check(v)) {
  924. *a = (PyLongObject *) v;
  925. Py_INCREF(v);
  926. }
  927. else if (PyInt_Check(v)) {
  928. *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
  929. }
  930. else {
  931. return 0;
  932. }
  933. if (PyLong_Check(w)) {
  934. *b = (PyLongObject *) w;
  935. Py_INCREF(w);
  936. }
  937. else if (PyInt_Check(w)) {
  938. *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
  939. }
  940. else {
  941. Py_DECREF(*a);
  942. return 0;
  943. }
  944. return 1;
  945. }
  946. #define CONVERT_BINOP(v, w, a, b) \
  947. if (!convert_binop(v, w, a, b)) { \
  948. Py_INCREF(Py_NotImplemented); \
  949. return Py_NotImplemented; \
  950. }
  951. /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
  952. * is modified in place, by adding y to it. Carries are propagated as far as
  953. * x[m-1], and the remaining carry (0 or 1) is returned.
  954. */
  955. static digit
  956. v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
  957. {
  958. Py_ssize_t i;
  959. digit carry = 0;
  960. assert(m >= n);
  961. for (i = 0; i < n; ++i) {
  962. carry += x[i] + y[i];
  963. x[i] = carry & PyLong_MASK;
  964. carry >>= PyLong_SHIFT;
  965. assert((carry & 1) == carry);
  966. }
  967. for (; carry && i < m; ++i) {
  968. carry += x[i];
  969. x[i] = carry & PyLong_MASK;
  970. carry >>= PyLong_SHIFT;
  971. assert((carry & 1) == carry);
  972. }
  973. return carry;
  974. }
  975. /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
  976. * is modified in place, by subtracting y from it. Borrows are propagated as
  977. * far as x[m-1], and the remaining borrow (0 or 1) is returned.
  978. */
  979. static digit
  980. v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
  981. {
  982. Py_ssize_t i;
  983. digit borrow = 0;
  984. assert(m >= n);
  985. for (i = 0; i < n; ++i) {
  986. borrow = x[i] - y[i] - borrow;
  987. x[i] = borrow & PyLong_MASK;
  988. borrow >>= PyLong_SHIFT;
  989. borrow &= 1; /* keep only 1 sign bit */
  990. }
  991. for (; borrow && i < m; ++i) {
  992. borrow = x[i] - borrow;
  993. x[i] = borrow & PyLong_MASK;
  994. borrow >>= PyLong_SHIFT;
  995. borrow &= 1;
  996. }
  997. return borrow;
  998. }
  999. /* Multiply by a single digit, ignoring the sign. */
  1000. static PyLongObject *
  1001. mul1(PyLongObject *a, wdigit n)
  1002. {
  1003. return muladd1(a, n, (digit)0);
  1004. }
  1005. /* Multiply by a single digit and add a single digit, ignoring the sign. */
  1006. static PyLongObject *
  1007. muladd1(PyLongObject *a, wdigit n, wdigit extra)
  1008. {
  1009. Py_ssize_t size_a = ABS(Py_SIZE(a));
  1010. PyLongObject *z = _PyLong_New(size_a+1);
  1011. twodigits carry = extra;
  1012. Py_ssize_t i;
  1013. if (z == NULL)
  1014. return NULL;
  1015. for (i = 0; i < size_a; ++i) {
  1016. carry += (twodigits)a->ob_digit[i] * n;
  1017. z->ob_digit[i] = (digit) (carry & PyLong_MASK);
  1018. carry >>= PyLong_SHIFT;
  1019. }
  1020. z->ob_digit[i] = (digit) carry;
  1021. return long_normalize(z);
  1022. }
  1023. /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
  1024. in pout, and returning the remainder. pin and pout point at the LSD.
  1025. It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
  1026. _PyLong_Format, but that should be done with great care since longs are
  1027. immutable. */
  1028. static digit
  1029. inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
  1030. {
  1031. twodigits rem = 0;
  1032. assert(n > 0 && n <= PyLong_MASK);
  1033. pin += size;
  1034. pout += size;
  1035. while (--size >= 0) {
  1036. digit hi;
  1037. rem = (rem << PyLong_SHIFT) + *--pin;
  1038. *--pout = hi = (digit)(rem / n);
  1039. rem -= (twodigits)hi * n;
  1040. }
  1041. return (digit)rem;
  1042. }
  1043. /* Divide a long integer by a digit, returning both the quotient
  1044. (as function result) and the remainder (through *prem).
  1045. The sign of a is ignored; n should not be zero. */
  1046. static PyLongObject *
  1047. divrem1(PyLongObject *a, digit n, digit *prem)
  1048. {
  1049. const Py_ssize_t size = ABS(Py_SIZE(a));
  1050. PyLongObject *z;
  1051. assert(n > 0 && n <= PyLong_MASK);
  1052. z = _PyLong_New(size);
  1053. if (z == NULL)
  1054. return NULL;
  1055. *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
  1056. return long_normalize(z);
  1057. }
  1058. /* Convert the long to a string object with given base,
  1059. appending a base prefix of 0[box] if base is 2, 8 or 16.
  1060. Add a trailing "L" if addL is non-zero.
  1061. If newstyle is zero, then use the pre-2.6 behavior of octal having
  1062. a leading "0", instead of the prefix "0o" */
  1063. PyAPI_FUNC(PyObject *)
  1064. _PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
  1065. {
  1066. register PyLongObject *a = (PyLongObject *)aa;
  1067. PyStringObject *str;
  1068. Py_ssize_t i, sz;
  1069. Py_ssize_t size_a;
  1070. char *p;
  1071. int bits;
  1072. char sign = '\0';
  1073. if (a == NULL || !PyLong_Check(a)) {
  1074. PyErr_BadInternalCall();
  1075. return NULL;
  1076. }
  1077. assert(base >= 2 && base <= 36);
  1078. size_a = ABS(Py_SIZE(a));
  1079. /* Compute a rough upper bound for the length of the string */
  1080. i = base;
  1081. bits = 0;
  1082. while (i > 1) {
  1083. ++bits;
  1084. i >>= 1;
  1085. }
  1086. i = 5 + (addL ? 1 : 0);
  1087. /* ensure we don't get signed overflow in sz calculation */
  1088. if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
  1089. PyErr_SetString(PyExc_OverflowError,
  1090. "long is too large to format");
  1091. return NULL;
  1092. }
  1093. sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
  1094. assert(sz >= 0);
  1095. str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
  1096. if (str == NULL)
  1097. return NULL;
  1098. p = PyString_AS_STRING(str) + sz;
  1099. *p = '\0';
  1100. if (addL)
  1101. *--p = 'L';
  1102. if (a->ob_size < 0)
  1103. sign = '-';
  1104. if (a->ob_size == 0) {
  1105. *--p = '0';
  1106. }
  1107. else if ((base & (base - 1)) == 0) {
  1108. /* JRH: special case for power-of-2 bases */
  1109. twodigits accum = 0;
  1110. int accumbits = 0; /* # of bits in accum */
  1111. int basebits = 1; /* # of bits in base-1 */
  1112. i = base;
  1113. while ((i >>= 1) > 1)
  1114. ++basebits;
  1115. for (i = 0; i < size_a; ++i) {
  1116. accum |= (twodigits)a->ob_digit[i] << accumbits;
  1117. accumbits += PyLong_SHIFT;
  1118. assert(accumbits >= basebits);
  1119. do {
  1120. char cdigit = (char)(accum & (base - 1));
  1121. cdigit += (cdigit < 10) ? '0' : 'a'-10;
  1122. assert(p > PyString_AS_STRING(str));
  1123. *--p = cdigit;
  1124. accumbits -= basebits;
  1125. accum >>= basebits;
  1126. } while (i < size_a-1 ? accumbits >= basebits :
  1127. accum > 0);
  1128. }
  1129. }
  1130. else {
  1131. /* Not 0, and base not a power of 2. Divide repeatedly by
  1132. base, but for speed use the highest power of base that
  1133. fits in a digit. */
  1134. Py_ssize_t size = size_a;
  1135. digit *pin = a->ob_digit;
  1136. PyLongObject *scratch;
  1137. /* powbasw <- largest power of base that fits in a digit. */
  1138. digit powbase = base; /* powbase == base ** power */
  1139. int power = 1;
  1140. for (;;) {
  1141. unsigned long newpow = powbase * (unsigned long)base;
  1142. if (newpow >> PyLong_SHIFT)
  1143. /* doesn't fit in a digit */
  1144. break;
  1145. powbase = (digit)newpow;
  1146. ++power;
  1147. }
  1148. /* Get a scratch area for repeated division. */
  1149. scratch = _PyLong_New(size);
  1150. if (scratch == NULL) {
  1151. Py_DECREF(str);
  1152. return NULL;
  1153. }
  1154. /* Repeatedly divide by powbase. */
  1155. do {
  1156. int ntostore = power;
  1157. digit rem = inplace_divrem1(scratch->ob_digit,
  1158. pin, size, powbase);
  1159. pin = scratch->ob_digit; /* no need to use a again */
  1160. if (pin[size - 1] == 0)
  1161. --size;
  1162. SIGCHECK({
  1163. Py_DECREF(scratch);
  1164. Py_DECREF(str);
  1165. return NULL;
  1166. })
  1167. /* Break rem into digits. */
  1168. assert(ntostore > 0);
  1169. do {
  1170. digit nextrem = (digit)(rem / base);
  1171. char c = (char)(rem - nextrem * base);
  1172. assert(p > PyString_AS_STRING(str));
  1173. c += (c < 10) ? '0' : 'a'-10;
  1174. *--p = c;
  1175. rem = nextrem;
  1176. --ntostore;
  1177. /* Termination is a bit delicate: must not
  1178. store leading zeroes, so must get out if
  1179. remaining quotient and rem are both 0. */
  1180. } while (ntostore && (size || rem));
  1181. } while (size != 0);
  1182. Py_DECREF(scratch);
  1183. }
  1184. if (base == 2) {
  1185. *--p = 'b';
  1186. *--p = '0';
  1187. }
  1188. else if (base == 8) {
  1189. if (newstyle) {
  1190. *--p = 'o';
  1191. *--p = '0';
  1192. }
  1193. else
  1194. if (size_a != 0)
  1195. *--p = '0';
  1196. }
  1197. else if (base == 16) {
  1198. *--p = 'x';
  1199. *--p = '0';
  1200. }
  1201. else if (base != 10) {
  1202. *--p = '#';
  1203. *--p = '0' + base%10;
  1204. if (base > 10)
  1205. *--p = '0' + base/10;
  1206. }
  1207. if (sign)
  1208. *--p = sign;
  1209. if (p != PyString_AS_STRING(str)) {
  1210. char *q = PyString_AS_STRING(str);
  1211. assert(p > q);
  1212. do {
  1213. } while ((*q++ = *p++) != '\0');
  1214. q--;
  1215. _PyString_Resize((PyObject **)&str,
  1216. (Py_ssize_t) (q - PyString_AS_STRING(str)));
  1217. }
  1218. return (PyObject *)str;
  1219. }
  1220. /* Table of digit values for 8-bit string -> integer conversion.
  1221. * '0' maps to 0, ..., '9' maps to 9.
  1222. * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
  1223. * All other indices map to 37.
  1224. * Note that when converting a base B string, a char c is a legitimate
  1225. * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
  1226. */
  1227. int _PyLong_DigitValue[256] = {
  1228. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1229. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1230. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1231. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
  1232. 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  1233. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
  1234. 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  1235. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
  1236. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1237. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1238. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1239. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1240. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1241. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1242. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1243. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1244. };
  1245. /* *str points to the first digit in a string of base `base` digits. base
  1246. * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
  1247. * non-digit (which may be *str!). A normalized long is returned.
  1248. * The point to this routine is that it takes time linear in the number of
  1249. * string characters.
  1250. */
  1251. static PyLongObject *
  1252. long_from_binary_base(char **str, int base)
  1253. {
  1254. char *p = *str;
  1255. char *start = p;
  1256. int bits_per_char;
  1257. Py_ssize_t n;
  1258. PyLongObject *z;
  1259. twodigits accum;
  1260. int bits_in_accum;
  1261. digit *pdigit;
  1262. assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
  1263. n = base;
  1264. for (bits_per_char = -1; n; ++bits_per_char)
  1265. n >>= 1;
  1266. /* n <- total # of bits needed, while setting p to end-of-string */
  1267. while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
  1268. ++p;
  1269. *str = p;
  1270. /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
  1271. n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
  1272. if (n / bits_per_char < p - start) {
  1273. PyErr_SetString(PyExc_ValueError,
  1274. "long string too large to convert");
  1275. return NULL;
  1276. }
  1277. n = n / PyLong_SHIFT;
  1278. z = _PyLong_New(n);
  1279. if (z == NULL)
  1280. return NULL;
  1281. /* Read string from right, and fill in long from left; i.e.,
  1282. * from least to most significant in both.
  1283. */
  1284. accum = 0;
  1285. bits_in_accum = 0;
  1286. pdigit = z->ob_digit;
  1287. while (--p >= start) {
  1288. int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
  1289. assert(k >= 0 && k < base);
  1290. accum |= (twodigits)k << bits_in_accum;
  1291. bits_in_accum += bits_per_char;
  1292. if (bits_in_accum >= PyLong_SHIFT) {
  1293. *pdigit++ = (digit)(accum & PyLong_MASK);
  1294. assert(pdigit - z->ob_digit <= n);
  1295. accum >>= PyLong_SHIFT;
  1296. bits_in_accum -= PyLong_SHIFT;
  1297. assert(bits_in_accum < PyLong_SHIFT);
  1298. }
  1299. }
  1300. if (bits_in_accum) {
  1301. assert(bits_in_accum <= PyLong_SHIFT);
  1302. *pdigit++ = (digit)accum;
  1303. assert(pdigit - z->ob_digit <= n);
  1304. }
  1305. while (pdigit - z->ob_digit < n)
  1306. *pdigit++ = 0;
  1307. return long_normalize(z);
  1308. }
  1309. PyObject *
  1310. PyLong_FromString(char *str, char **pend, int base)
  1311. {
  1312. int sign = 1;
  1313. char *start, *orig_str = str;
  1314. PyLongObject *z;
  1315. PyObject *strobj, *strrepr;
  1316. Py_ssize_t slen;
  1317. if ((base != 0 && base < 2) || base > 36) {
  1318. PyErr_SetString(PyExc_ValueError,
  1319. "long() arg 2 must be >= 2 and <= 36");
  1320. return NULL;
  1321. }
  1322. while (*str != '\0' && isspace(Py_CHARMASK(*str)))
  1323. str++;
  1324. if (*str == '+')
  1325. ++str;
  1326. else if (*str == '-') {
  1327. ++str;
  1328. sign = -1;
  1329. }
  1330. while (*str != '\0' && isspace(Py_CHARMASK(*str)))
  1331. str++;
  1332. if (base == 0) {
  1333. /* No base given. Deduce the base from the contents
  1334. of the string */
  1335. if (str[0] != '0')
  1336. base = 10;
  1337. else if (str[1] == 'x' || str[1] == 'X')
  1338. base = 16;
  1339. else if (str[1] == 'o' || str[1] == 'O')
  1340. base = 8;
  1341. else if (str[1] == 'b' || str[1] == 'B')
  1342. base = 2;
  1343. else
  1344. /* "old" (C-style) octal literal, still valid in
  1345. 2.x, although illegal in 3.x */
  1346. base = 8;
  1347. }
  1348. /* Whether or not we were deducing the base, skip leading chars
  1349. as needed */
  1350. if (str[0] == '0' &&
  1351. ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
  1352. (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
  1353. (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
  1354. str += 2;
  1355. start = str;
  1356. if ((base & (base - 1)) == 0)
  1357. z = long_from_binary_base(&str, base);
  1358. else {
  1359. /***
  1360. Binary bases can be converted in time linear in the number of digits, because
  1361. Python's representation base is binary. Other bases (including decimal!) use
  1362. the simple quadratic-time algorithm below, complicated by some speed tricks.
  1363. First some math: the largest integer that can be expressed in N base-B digits
  1364. is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
  1365. case number of Python digits needed to hold it is the smallest integer n s.t.
  1366. PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
  1367. PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
  1368. n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
  1369. The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
  1370. this quickly. A Python long with that much space is reserved near the start,
  1371. and the result is computed into it.
  1372. The input string is actually treated as being in base base**i (i.e., i digits
  1373. are processed at a time), where two more static arrays hold:
  1374. convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
  1375. convmultmax_base[base] = base ** convwidth_base[base]
  1376. The first of these is the largest i such that i consecutive input digits
  1377. must fit in a single Python digit. The second is effectively the input
  1378. base we're really using.
  1379. Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
  1380. convmultmax_base[base], the result is "simply"
  1381. (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
  1382. where B = convmultmax_base[base].
  1383. Error analysis: as above, the number of Python digits `n` needed is worst-
  1384. case
  1385. n >= N * log(B)/log(PyLong_BASE)
  1386. where `N` is the number of input digits in base `B`. This is computed via
  1387. size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
  1388. below. Two numeric concerns are how much space this can waste, and whether
  1389. the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
  1390. which is the default (and it's unlikely anyone changes that).
  1391. Waste isn't a problem: provided the first input digit isn't 0, the difference
  1392. between the worst-case input with N digits and the smallest input with N
  1393. digits is about a factor of B, but B is small compared to PyLong_BASE so at most
  1394. one allocated Python digit can remain unused on that count. If
  1395. N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
  1396. and adding 1 returns a result 1 larger than necessary. However, that can't
  1397. happen: whenever B is a power of 2, long_from_binary_base() is called
  1398. instead, and it's impossible for B**i to be an integer power of 2**15 when
  1399. B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be
  1400. an exact integer when B is not a power of 2, since B**i has a prime factor
  1401. other than 2 in that case, but (2**15)**j's only prime factor is 2).
  1402. The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
  1403. is a little bit larger than an exact integer, but due to roundoff errors (in
  1404. computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
  1405. yields a numeric result a little less than that integer. Unfortunately, "how
  1406. close can a transcendental function get to an integer over some range?"
  1407. questions are generally theoretically intractable. Computer analysis via
  1408. continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
  1409. fractions, giving a sequence i/j of "the best" rational approximations. Then
  1410. j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
  1411. we can get very close to being in trouble, but very rarely. For example,
  1412. 76573 is a denominator in one of the continued-fraction approximations to
  1413. log(10)/log(2**15), and indeed:
  1414. >>> log(10)/log(2**15)*76573
  1415. 16958.000000654003
  1416. is very close to an integer. If we were working with IEEE single-precision,
  1417. rounding errors could kill us. Finding worst cases in IEEE double-precision
  1418. requires better-than-double-precision log() functions, and Tim didn't bother.
  1419. Instead the code checks to see whether the allocated space is enough as each
  1420. new Python digit is added, and copies the whole thing to a larger long if not.
  1421. This should happen extremely rarely, and in fact I don't have a test case
  1422. that triggers it(!). Instead the code was tested by artificially allocating
  1423. just 1 digit at the start, so that the copying code was exercised for every
  1424. digit beyond the first.
  1425. ***/
  1426. register twodigits c; /* current input character */
  1427. Py_ssize_t size_z;
  1428. int i;
  1429. int convwidth;
  1430. twodigits convmultmax, convmult;
  1431. digit *pz, *pzstop;
  1432. char* scan;
  1433. static double log_base_PyLong_BASE[37] = {0.0e0,};
  1434. static int convwidth_base[37] = {0,};
  1435. static twodigits convmultmax_base[37] = {0,};
  1436. if (log_base_PyLong_BASE[base] == 0.0) {
  1437. twodigits convmax = base;
  1438. int i = 1;
  1439. log_base_PyLong_BASE[base] = log((double)base) /
  1440. log((double)PyLong_BASE);
  1441. for (;;) {
  1442. twodigits next = convmax * base;
  1443. if (next > PyLong_BASE)
  1444. break;
  1445. convmax = next;
  1446. ++i;
  1447. }
  1448. convmultmax_base[base] = convmax;
  1449. assert(i > 0);
  1450. convwidth_base[base] = i;
  1451. }
  1452. /* Find length of the string of numeric characters. */
  1453. scan = str;
  1454. while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
  1455. ++scan;
  1456. /* Create a long object that can contain the largest possible
  1457. * integer with this base and length. Note that there's no
  1458. * need to initialize z->ob_digit -- no slot is read up before
  1459. * being stored into.
  1460. */
  1461. size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
  1462. /* Uncomment next line to test exceedingly rare copy code */
  1463. /* size_z = 1; */
  1464. assert(size_z > 0);
  1465. z = _PyLong_New(size_z);
  1466. if (z == NULL)
  1467. return NULL;
  1468. Py_SIZE(z) = 0;
  1469. /* `convwidth` consecutive input digits are treated as a single
  1470. * digit in base `convmultmax`.
  1471. */
  1472. convwidth = convwidth_base[base];
  1473. convmultmax = convmultmax_base[base];
  1474. /* Work ;-) */
  1475. while (str < scan) {
  1476. /* grab up to convwidth digits from the input string */
  1477. c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
  1478. for (i = 1; i < convwidth && str != scan; ++i, ++str) {
  1479. c = (twodigits)(c * base +
  1480. _PyLong_DigitValue[Py_CHARMASK(*str)]);
  1481. assert(c < PyLong_BASE);
  1482. }
  1483. convmult = convmultmax;
  1484. /* Calculate the shift only if we couldn't get
  1485. * convwidth digits.
  1486. */
  1487. if (i != convwidth) {
  1488. convmult = base;
  1489. for ( ; i > 1; --i)
  1490. convmult *= base;
  1491. }
  1492. /* Multiply z by convmult, and add c. */
  1493. pz = z->ob_digit;
  1494. pzstop = pz + Py_SIZE(z);
  1495. for (; pz < pzstop; ++pz) {
  1496. c += (twodigits)*pz * convmult;
  1497. *pz = (digit)(c & PyLong_MASK);
  1498. c >>= PyLong_SHIFT;
  1499. }
  1500. /* carry off the current end? */
  1501. if (c) {
  1502. assert(c < PyLong_BASE);
  1503. if (Py_SIZE(z) < size_z) {
  1504. *pz = (digit)c;
  1505. ++Py_SIZE(z);
  1506. }
  1507. else {
  1508. PyLongObject *tmp;
  1509. /* Extremely rare. Get more space. */
  1510. assert(Py_SIZE(z) == size_z);
  1511. tmp = _PyLong_New(size_z + 1);
  1512. if (tmp == NULL) {
  1513. Py_DECREF(z);
  1514. return NULL;
  1515. }
  1516. memcpy(tmp->ob_digit,
  1517. z->ob_digit,
  1518. sizeof(digit) * size_z);
  1519. Py_DECREF(z);
  1520. z = tmp;
  1521. z->ob_digit[size_z] = (digit)c;
  1522. ++size_z;
  1523. }
  1524. }
  1525. }
  1526. }
  1527. if (z == NULL)
  1528. return NULL;
  1529. if (str == start)
  1530. goto onError;
  1531. if (sign < 0)
  1532. Py_SIZE(z) = -(Py_SIZE(z));
  1533. if (*str == 'L' || *str == 'l')
  1534. str++;
  1535. while (*str && isspace(Py_CHARMASK(*str)))
  1536. str++;
  1537. if (*str != '\0')
  1538. goto onError;
  1539. if (pend)
  1540. *pend = str;
  1541. return (PyObject *) z;
  1542. onError:
  1543. Py_XDECREF(z);
  1544. slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
  1545. strobj = PyString_FromStringAndSize(orig_str, slen);
  1546. if (strobj == NULL)
  1547. return NULL;
  1548. strrepr = PyObject_Repr(strobj);
  1549. Py_DECREF(strobj);
  1550. if (strrepr == NULL)
  1551. return NULL;
  1552. PyErr_Format(PyExc_ValueError,
  1553. "invalid literal for long() with base %d: %s",
  1554. base, PyString_AS_STRING(strrepr));
  1555. Py_DECREF(strrepr);
  1556. return NULL;
  1557. }
  1558. #ifdef Py_USING_UNICODE
  1559. PyObject *
  1560. PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
  1561. {
  1562. PyObject *result;
  1563. char *buffer = (char *)PyMem_MALLOC(length+1);
  1564. if (buffer == NULL)
  1565. return NULL;
  1566. if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
  1567. PyMem_FREE(buffer);
  1568. return NULL;
  1569. }
  1570. result = PyLong_FromString(buffer, NULL, base);
  1571. PyMem_FREE(buffer);
  1572. return result;
  1573. }
  1574. #endif
  1575. /* forward */
  1576. static PyLongObject *x_divrem
  1577. (PyLongObject *, PyLongObject *, PyLongObject **);
  1578. static PyObject *long_long(PyObject *v);
  1579. static int long_divrem(PyLongObject *, PyLongObject *,
  1580. PyLongObject **, PyLongObject **);
  1581. /* Long division with remainder, top-level routine */
  1582. static int
  1583. long_divrem(PyLongObject *a, PyLongObject *b,
  1584. PyLongObject **pdiv, PyLongObject **prem)
  1585. {
  1586. Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
  1587. PyLongObject *z;
  1588. if (size_b == 0) {
  1589. PyErr_SetString(PyExc_ZeroDivisionError,
  1590. "long division or modulo by zero");
  1591. return -1;
  1592. }
  1593. if (size_a < size_b ||
  1594. (size_a == size_b &&
  1595. a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
  1596. /* |a| < |b|. */
  1597. *pdiv = _PyLong_New(0);
  1598. if (*pdiv == NULL)
  1599. return -1;
  1600. Py_INCREF(a);
  1601. *prem = (PyLongObject *) a;
  1602. return 0;
  1603. }
  1604. if (size_b == 1) {
  1605. digit rem = 0;
  1606. z = divrem1(a, b->ob_digit[0], &rem);
  1607. if (z == NULL)
  1608. return -1;
  1609. *prem = (PyLongObject *) PyLong_FromLong((long)rem);
  1610. if (*prem == NULL) {
  1611. Py_DECREF(z);
  1612. return -1;
  1613. }
  1614. }
  1615. else {
  1616. z = x_divrem(a, b, prem);
  1617. if (z == NULL)
  1618. return -1;
  1619. }
  1620. /* Set the signs.
  1621. The quotient z has the sign of a*b;
  1622. the remainder r has the sign of a,
  1623. so a = b*z + r. */
  1624. if ((a->ob_size < 0) != (b->ob_size < 0))
  1625. z->ob_size = -(z->ob_size);
  1626. if (a->ob_size < 0 && (*prem)->ob_size != 0)
  1627. (*prem)->ob_size = -((*prem)->ob_size);
  1628. *pdiv = z;
  1629. return 0;
  1630. }
  1631. /* Unsigned long division with remainder -- the algorithm */
  1632. static PyLongObject *
  1633. x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
  1634. {
  1635. Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
  1636. digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
  1637. PyLongObject *v = mul1(v1, d);
  1638. PyLongObject *w = mul1(w1, d);
  1639. PyLongObject *a;
  1640. Py_ssize_t j, k;
  1641. if (v == NULL || w == NULL) {
  1642. Py_XDECREF(v);
  1643. Py_XDECREF(w);
  1644. return NULL;
  1645. }
  1646. assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
  1647. assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
  1648. assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
  1649. size_v = ABS(Py_SIZE(v));
  1650. k = size_v - size_w;
  1651. a = _PyLong_New(k + 1);
  1652. for (j = size_v; a != NULL && k >= 0; --j, --k) {
  1653. digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
  1654. twodigits q;
  1655. stwodigits carry = 0;
  1656. Py_ssize_t i;
  1657. SIGCHECK({
  1658. Py_DECREF(a);
  1659. a = NULL;
  1660. break;
  1661. })
  1662. if (vj == w->ob_digit[size_w-1])
  1663. q = PyLong_MASK;
  1664. else
  1665. q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
  1666. w->ob_digit[size_w-1];
  1667. while (w->ob_digit[size_w-2]*q >
  1668. ((
  1669. ((twodigits)vj << PyLong_SHIFT)
  1670. + v->ob_digit[j-1]
  1671. - q*w->ob_digit[size_w-1]
  1672. ) << PyLong_SHIFT)
  1673. + v->ob_digit[j-2])
  1674. --q;
  1675. for (i = 0; i < size_w && i+k < size_v; ++i) {
  1676. twodigits z = w->ob_digit[i] * q;
  1677. digit zz = (digit) (z >> PyLong_SHIFT);
  1678. carry += v->ob_digit[i+k] - z
  1679. + ((twodigits)zz << PyLong_SHIFT);
  1680. v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
  1681. carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
  1682. carry, PyLong_SHIFT);
  1683. carry -= zz;
  1684. }
  1685. if (i+k < size_v) {
  1686. carry += v->ob_digit[i+k];
  1687. v->ob_digit[i+k] = 0;
  1688. }
  1689. if (carry == 0)
  1690. a->ob_digit[k] = (digit) q;
  1691. else {
  1692. assert(carry == -1);
  1693. a->ob_digit[k] = (digit) q-1;
  1694. carry = 0;
  1695. for (i = 0; i < size_w && i+k < size_v; ++i) {
  1696. carry += v->ob_digit[i+k] + w->ob_digit[i];
  1697. v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
  1698. carry = Py_ARITHMETIC_RIGHT_SHIFT(
  1699. BASE_TWODIGITS_TYPE,
  1700. carry, PyLong_SHIFT);
  1701. }
  1702. }
  1703. } /* for j, k */
  1704. if (a == NULL)
  1705. *prem = NULL;
  1706. else {
  1707. a = long_normalize(a);
  1708. *prem = divrem1(v, d, &d);
  1709. /* d receives the (unused) remainder */
  1710. if (*prem == NULL) {
  1711. Py_DECREF(a);
  1712. a = NULL;
  1713. }
  1714. }
  1715. Py_DECREF(v);
  1716. Py_DECREF(w);
  1717. return a;
  1718. }
  1719. /* Methods */
  1720. static void
  1721. long_dealloc(PyObject *v)
  1722. {
  1723. Py_TYPE(v)->tp_free(v);
  1724. }
  1725. static PyObject *
  1726. long_repr(PyObject *v)
  1727. {
  1728. return _PyLong_Format(v, 10, 1, 0);
  1729. }
  1730. static PyObject *
  1731. long_str(PyObject *v)
  1732. {
  1733. return _PyLong_Format(v, 10, 0, 0);
  1734. }
  1735. static int
  1736. long_compare(PyLongObject *a, PyLongObject *b)
  1737. {
  1738. Py_ssize_t sign;
  1739. if (Py_SIZE(a) != Py_SIZE(b)) {
  1740. if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
  1741. sign = 0;
  1742. else
  1743. sign = Py_SIZE(a) - Py_SIZE(b);
  1744. }
  1745. else {
  1746. Py_ssize_t i = ABS(Py_SIZE(a));
  1747. while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
  1748. ;
  1749. if (i < 0)
  1750. sign = 0;
  1751. else {
  1752. sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
  1753. if (Py_SIZE(a) < 0)
  1754. sign = -sign;
  1755. }
  1756. }
  1757. return sign < 0 ? -1 : sign > 0 ? 1 : 0;
  1758. }
  1759. static long
  1760. long_hash(PyLongObject *v)
  1761. {
  1762. unsigned long x;
  1763. Py_ssize_t i;
  1764. int sign;
  1765. /* This is designed so that Python ints and longs with the
  1766. same value hash to the same value, otherwise comparisons
  1767. of mapping keys will turn out weird */
  1768. i = v->ob_size;
  1769. sign = 1;
  1770. x = 0;
  1771. if (i < 0) {
  1772. sign = -1;
  1773. i = -(i);
  1774. }
  1775. #define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
  1776. /* The following loop produces a C unsigned long x such that x is
  1777. congruent to the absolute value of v modulo ULONG_MAX. The
  1778. resulting x is nonzero if and only if v is. */
  1779. while (--i >= 0) {
  1780. /* Force a native long #-bits (32 or 64) circular shift */
  1781. x = ((x << PyLong_SHIFT) & ~PyLong_MASK) |
  1782. ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
  1783. x += v->ob_digit[i];
  1784. /* If the addition above overflowed we compensate by
  1785. incrementing. This preserves the value modulo
  1786. ULONG_MAX. */
  1787. if (x < v->ob_digit[i])
  1788. x++;
  1789. }
  1790. #undef LONG_BIT_PyLong_SHIFT
  1791. x = x * sign;
  1792. if (x == -1)
  1793. x = -2;
  1794. return x;
  1795. }
  1796. /* Add the absolute values of two long integers. */
  1797. static PyLongObject *
  1798. x_add(PyLongObject *a, PyLongObject *b)
  1799. {
  1800. Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
  1801. PyLongObject *z;
  1802. Py_ssize_t i;
  1803. digit carry = 0;
  1804. /* Ensure a is the larger of the two: */
  1805. if (size_a < size_b) {
  1806. { PyLongObject *temp = a; a = b; b = temp; }
  1807. { Py_ssize_t size_temp = size_a;
  1808. size_a = size_b;
  1809. size_b = size_temp; }
  1810. }
  1811. z = _PyLong_New(size_a+1);
  1812. if (z == NULL)
  1813. return NULL;
  1814. for (i = 0; i < size_b; ++i) {
  1815. carry += a->ob_digit[i] + b->ob_digit[i];
  1816. z->ob_digit[i] = carry & PyLong_MASK;
  1817. carry >>= PyLong_SHIFT;
  1818. }
  1819. for (; i < size_a; ++i) {
  1820. carry += a->ob_digit[i];
  1821. z->ob_digit[i] = carry & PyLong_MASK;
  1822. carry >>= PyLong_SHIFT;
  1823. }
  1824. z->ob_digit[i] = carry;
  1825. return long_normalize(z);
  1826. }
  1827. /* Subtract the absolute values of two integers. */
  1828. static PyLongObject *
  1829. x_sub(PyLongObject *a, PyLongObject *b)
  1830. {
  1831. Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
  1832. PyLongObject *z;
  1833. Py_ssize_t i;
  1834. int sign = 1;
  1835. digit borrow = 0;
  1836. /* Ensure a is the larger of the two: */
  1837. if (size_a < size_b) {
  1838. sign = -1;
  1839. { PyLongObject *temp = a; a = b; b = temp; }
  1840. { Py_ssize_t size_temp = size_a;
  1841. size_a = size_b;
  1842. size_b = size_temp; }
  1843. }
  1844. else if (size_a == size_b) {
  1845. /* Find highest digit where a and b differ: */
  1846. i = size_a;
  1847. while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
  1848. ;
  1849. if (i < 0)
  1850. return _PyLong_New(0);
  1851. if (a->ob_digit[i] < b->ob_digit[i]) {
  1852. sign = -1;
  1853. { PyLongObject *temp = a; a = b; b = temp; }
  1854. }
  1855. size_a = size_b = i+1;
  1856. }
  1857. z = _PyLong_New(size_a);
  1858. if (z == NULL)
  1859. return NULL;
  1860. for (i = 0; i < size_b; ++i) {
  1861. /* The following assumes unsigned arithmetic
  1862. works module 2**N for some N>PyLong_SHIFT. */
  1863. borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
  1864. z->ob_digit[i] = borrow & PyLong_MASK;
  1865. borrow >>= PyLong_SHIFT;
  1866. borrow &= 1; /* Keep only one sign bit */
  1867. }
  1868. for (; i < size_a; ++i) {
  1869. borrow = a->ob_digit[i] - borrow;
  1870. z->ob_digit[i] = borrow & PyLong_MASK;
  1871. borrow >>= PyLong_SHIFT;
  1872. borrow &= 1; /* Keep only one sign bit */
  1873. }
  1874. assert(borrow == 0);
  1875. if (sign < 0)
  1876. z->ob_size = -(z->ob_size);
  1877. return long_normalize(z);
  1878. }
  1879. static PyObject *
  1880. long_add(PyLongObject *v, PyLongObject *w)
  1881. {
  1882. PyLongObject *a, *b, *z;
  1883. CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
  1884. if (a->ob_size < 0) {
  1885. if (b->ob_size < 0) {
  1886. z = x_add(a, b);
  1887. if (z != NULL && z->ob_size != 0)
  1888. z->ob_size = -(z->ob_size);
  1889. }
  1890. else
  1891. z = x_sub(b, a);
  1892. }
  1893. else {
  1894. if (b->ob_size < 0)
  1895. z = x_sub(a, b);
  1896. else
  1897. z = x_add(a, b);
  1898. }
  1899. Py_DECREF(a);
  1900. Py_DECREF(b);
  1901. return (PyObject *)z;
  1902. }
  1903. static PyObject *
  1904. long_sub(PyLongObject *v, PyLongObject *w)
  1905. {
  1906. PyLongObject *a, *b, *z;
  1907. CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
  1908. if (a->ob_size < 0) {
  1909. if (b->ob_size < 0)
  1910. z = x_sub(a, b);
  1911. else
  1912. z = x_add(a, b);
  1913. if (z != NULL && z->ob_size != 0)
  1914. z->ob_size = -(z->ob_size);
  1915. }
  1916. else {
  1917. if (b->ob_size < 0)
  1918. z = x_add(a, b);
  1919. else
  1920. z = x_sub(a, b);
  1921. }
  1922. Py_DECREF(a);
  1923. Py_DECREF(b);
  1924. return (PyObject *)z;
  1925. }
  1926. /* Grade school multiplication, ignoring the signs.
  1927. * Returns the absolute value of the product, or NULL if error.
  1928. */
  1929. static PyLongObject *
  1930. x_mul(PyLongObject *a, PyLongObject *b)
  1931. {
  1932. PyLongObject *z;
  1933. Py_ssize_t size_a = ABS(Py_SIZE(a));
  1934. Py_ssize_t size_b = ABS(Py_SIZE(b));
  1935. Py_ssize_t i;
  1936. z = _PyLong_New(size_a + size_b);
  1937. if (z == NULL)
  1938. return NULL;
  1939. memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
  1940. if (a == b) {
  1941. /* Efficient squaring per HAC, Algorithm 14.16:
  1942. * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
  1943. * Gives slightly less than a 2x speedup when a == b,
  1944. * via exploiting that each entry in the multiplication
  1945. * pyramid appears twice (except for the size_a squares).
  1946. */
  1947. for (i = 0; i < size_a; ++i) {
  1948. twodigits carry;
  1949. twodigits f = a->ob_digit[i];
  1950. digit *pz = z->ob_digit + (i << 1);
  1951. digit *pa = a->ob_digit + i + 1;
  1952. digit *paend = a->ob_digit + size_a;
  1953. SIGCHECK({
  1954. Py_DECREF(z);
  1955. return NULL;
  1956. })
  1957. carry = *pz + f * f;
  1958. *pz++ = (digit)(carry & PyLong_MASK);
  1959. carry >>= PyLong_SHIFT;
  1960. assert(carry <= PyLong_MASK);
  1961. /* Now f is added in twice in each column of the
  1962. * pyramid it appears. Same as adding f<<1 once.
  1963. */
  1964. f <<= 1;
  1965. while (pa < paend) {
  1966. carry += *pz + *pa++ * f;
  1967. *pz++ = (digit)(carry & PyLong_MASK);
  1968. carry >>= PyLong_SHIFT;
  1969. assert(carry <= (PyLong_MASK << 1));
  1970. }
  1971. if (carry) {
  1972. carry += *pz;
  1973. *pz++ = (digit)(carry & PyLong_MASK);
  1974. carry >>= PyLong_SHIFT;
  1975. }
  1976. if (carry)
  1977. *pz += (digit)(carry & PyLong_MASK);
  1978. assert((carry >> PyLong_SHIFT) == 0);
  1979. }
  1980. }
  1981. else { /* a is not the same as b -- gradeschool long mult */
  1982. for (i = 0; i < size_a; ++i) {
  1983. twodigits carry = 0;
  1984. twodigits f = a->ob_digit[i];
  1985. digit *pz = z->ob_digit + i;
  1986. digit *pb = b->ob_digit;
  1987. digit *pbend = b->ob_digit + size_b;
  1988. SIGCHECK({
  1989. Py_DECREF(z);
  1990. return NULL;
  1991. })
  1992. while (pb < pbend) {
  1993. carry += *pz + *pb++ * f;
  1994. *pz++ = (digit)(carry & PyLong_MASK);
  1995. carry >>= PyLong_SHIFT;
  1996. assert(carry <= PyLong_MASK);
  1997. }
  1998. if (carry)
  1999. *pz += (digit)(carry & PyLong_MASK);
  2000. assert((carry >> PyLong_SHIFT) == 0);
  2001. }
  2002. }
  2003. return long_normalize(z);
  2004. }
  2005. /* A helper for Karatsuba multiplication (k_mul).
  2006. Takes a long "n" and an integer "size" representing the place to
  2007. split, and sets low and high such that abs(n) == (high << size) + low,
  2008. viewing the shift as being by digits. The sign bit is ignored, and
  2009. the return values are >= 0.
  2010. Returns 0 on success, -1 on failure.
  2011. */
  2012. static int
  2013. kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
  2014. {
  2015. PyLongObject *hi, *lo;
  2016. Py_ssize_t size_lo, size_hi;
  2017. const Py_ssize_t size_n = ABS(Py_SIZE(n));
  2018. size_lo = MIN(size_n, size);
  2019. size_hi = size_n - size_lo;
  2020. if ((hi = _PyLong_New(size_hi)) == NULL)
  2021. return -1;
  2022. if ((lo = _PyLong_New(size_lo)) == NULL) {
  2023. Py_DECREF(hi);
  2024. return -1;
  2025. }
  2026. memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
  2027. memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
  2028. *high = long_normalize(hi);
  2029. *low = long_normalize(lo);
  2030. return 0;
  2031. }
  2032. static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
  2033. /* Karatsuba multiplication. Ignores the input signs, and returns the
  2034. * absolute value of the product (or NULL if error).
  2035. * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
  2036. */
  2037. static PyLongObject *
  2038. k_mul(PyLongObject *a, PyLongObject *b)
  2039. {
  2040. Py_ssize_t asize = ABS(Py_SIZE(a));
  2041. Py_ssize_t bsize = ABS(Py_SIZE(b));
  2042. PyLongObject *ah = NULL;
  2043. PyLongObject *al = NULL;
  2044. PyLongObject *bh = NULL;
  2045. PyLongObject *bl = NULL;
  2046. PyLongObject *ret = NULL;
  2047. PyLongObject *t1, *t2, *t3;
  2048. Py_ssize_t shift; /* the number of digits we split off */
  2049. Py_ssize_t i;
  2050. /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
  2051. * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
  2052. * Then the original product is
  2053. * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
  2054. * By picking X to be a power of 2, "*X" is just shifting, and it's
  2055. * been reduced to 3 multiplies on numbers half the size.
  2056. */
  2057. /* We want to split based on the larger number; fiddle so that b
  2058. * is largest.
  2059. */
  2060. if (asize > bsize) {
  2061. t1 = a;
  2062. a = b;
  2063. b = t1;
  2064. i = asize;
  2065. asize = bsize;
  2066. bsize = i;
  2067. }
  2068. /* Use gradeschool math when either number is too small. */
  2069. i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
  2070. if (asize <= i) {
  2071. if (asize == 0)
  2072. return _PyLong_New(0);
  2073. else
  2074. return x_mul(a, b);
  2075. }
  2076. /* If a is small compared to b, splitting on b gives a degenerate
  2077. * case with ah==0, and Karatsuba may be (even much) less efficient
  2078. * than "grade school" then. However, we can still win, by viewing
  2079. * b as a string of "big digits", each of width a->ob_size. That
  2080. * leads to a sequence of balanced calls to k_mul.
  2081. */
  2082. if (2 * asize <= bsize)
  2083. return k_lopsided_mul(a, b);
  2084. /* Split a & b into hi & lo pieces. */
  2085. shift = bsize >> 1;
  2086. if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
  2087. assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
  2088. if (a == b) {
  2089. bh = ah;
  2090. bl = al;
  2091. Py_INCREF(bh);
  2092. Py_INCREF(bl);
  2093. }
  2094. else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
  2095. /* The plan:
  2096. * 1. Allocate result space (asize + bsize digits: that's always
  2097. * enough).
  2098. * 2. Compute ah*bh, and copy into result at 2*shift.
  2099. * 3. Compute al*bl, and copy into result at 0. Note that this
  2100. * can't overlap with #2.
  2101. * 4. Subtract al*bl from the result, starting at shift. This may
  2102. * underflow (borrow out of the high digit), but we don't care:
  2103. * we're effectively doing unsigned arithmetic mod
  2104. * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
  2105. * borrows and carries out of the high digit can be ignored.
  2106. * 5. Subtract ah*bh from the result, starting at shift.
  2107. * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
  2108. * at shift.
  2109. */
  2110. /* 1. Allocate result space. */
  2111. ret = _PyLong_New(asize + bsize);
  2112. if (ret == NULL) goto fail;
  2113. #ifdef Py_DEBUG
  2114. /* Fill with trash, to catch reference to uninitialized digits. */
  2115. memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
  2116. #endif
  2117. /* 2. t1 <- ah*bh, and copy into high digits of result. */
  2118. if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
  2119. assert(Py_SIZE(t1) >= 0);
  2120. assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
  2121. memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
  2122. Py_SIZE(t1) * sizeof(digit));
  2123. /* Zero-out the digits higher than the ah*bh copy. */
  2124. i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
  2125. if (i)
  2126. memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
  2127. i * sizeof(digit));
  2128. /* 3. t2 <- al*bl, and copy into the low digits. */
  2129. if ((t2 = k_mul(al, bl)) == NULL) {
  2130. Py_DECREF(t1);
  2131. goto fail;
  2132. }
  2133. assert(Py_SIZE(t2) >= 0);
  2134. assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
  2135. memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
  2136. /* Zero out remaining digits. */
  2137. i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
  2138. if (i)
  2139. memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
  2140. /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
  2141. * because it's fresher in cache.
  2142. */
  2143. i = Py_SIZE(ret) - shift; /* # digits after shift */
  2144. (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
  2145. Py_DECREF(t2);
  2146. (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
  2147. Py_DECREF(t1);
  2148. /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
  2149. if ((t1 = x_add(ah, al)) == NULL) goto fail;
  2150. Py_DECREF(ah);
  2151. Py_DECREF(al);
  2152. ah = al = NULL;
  2153. if (a == b) {
  2154. t2 = t1;
  2155. Py_INCREF(t2);
  2156. }
  2157. else if ((t2 = x_add(bh, bl)) == NULL) {
  2158. Py_DECREF(t1);
  2159. goto fail;
  2160. }
  2161. Py_DECREF(bh);
  2162. Py_DECREF(bl);
  2163. bh = bl = NULL;
  2164. t3 = k_mul(t1, t2);
  2165. Py_DECREF(t1);
  2166. Py_DECREF(t2);
  2167. if (t3 == NULL) goto fail;
  2168. assert(Py_SIZE(t3) >= 0);
  2169. /* Add t3. It's not obvious why we can't run out of room here.
  2170. * See the (*) comment after this function.
  2171. */
  2172. (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
  2173. Py_DECREF(t3);
  2174. return long_normalize(ret);
  2175. fail:
  2176. Py_XDECREF(ret);
  2177. Py_XDECREF(ah);
  2178. Py_XDECREF(al);
  2179. Py_XDECREF(bh);
  2180. Py_XDECREF(bl);
  2181. return NULL;
  2182. }
  2183. /* (*) Why adding t3 can't "run out of room" above.
  2184. Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
  2185. to start with:
  2186. 1. For any integer i, i = c(i/2) + f(i/2). In particular,
  2187. bsize = c(bsize/2) + f(bsize/2).
  2188. 2. shift = f(bsize/2)
  2189. 3. asize <= bsize
  2190. 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
  2191. routine, so asize > bsize/2 >= f(bsize/2) in this routine.
  2192. We allocated asize + bsize result digits, and add t3 into them at an offset
  2193. of shift. This leaves asize+bsize-shift allocated digit positions for t3
  2194. to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
  2195. asize + c(bsize/2) available digit positions.
  2196. bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
  2197. at most c(bsize/2) digits + 1 bit.
  2198. If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
  2199. digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
  2200. most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
  2201. The product (ah+al)*(bh+bl) therefore has at most
  2202. c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
  2203. and we have asize + c(bsize/2) available digit positions. We need to show
  2204. this is always enough. An instance of c(bsize/2) cancels out in both, so
  2205. the question reduces to whether asize digits is enough to hold
  2206. (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
  2207. then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
  2208. asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
  2209. digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
  2210. asize == bsize, then we're asking whether bsize digits is enough to hold
  2211. c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
  2212. is enough to hold 2 bits. This is so if bsize >= 2, which holds because
  2213. bsize >= KARATSUBA_CUTOFF >= 2.
  2214. Note that since there's always enough room for (ah+al)*(bh+bl), and that's
  2215. clearly >= each of ah*bh and al*bl, there's always enough room to subtract
  2216. ah*bh and al*bl too.
  2217. */
  2218. /* b has at least twice the digits of a, and a is big enough that Karatsuba
  2219. * would pay off *if* the inputs had balanced sizes. View b as a sequence
  2220. * of slices, each with a->ob_size digits, and multiply the slices by a,
  2221. * one at a time. This gives k_mul balanced inputs to work with, and is
  2222. * also cache-friendly (we compute one double-width slice of the result
  2223. * at a time, then move on, never bactracking except for the helpful
  2224. * single-width slice overlap between successive partial sums).
  2225. */
  2226. static PyLongObject *
  2227. k_lopsided_mul(PyLongObject *a, PyLongObject *b)
  2228. {
  2229. const Py_ssize_t asize = ABS(Py_SIZE(a));
  2230. Py_ssize_t bsize = ABS(Py_SIZE(b));
  2231. Py_ssize_t nbdone; /* # of b digits already multiplied */
  2232. PyLongObject *ret;
  2233. PyLongObject *bslice = NULL;
  2234. assert(asize > KARATSUBA_CUTOFF);
  2235. assert(2 * asize <= bsize);
  2236. /* Allocate result space, and zero it out. */
  2237. ret = _PyLong_New(asize + bsize);
  2238. if (ret == NULL)
  2239. return NULL;
  2240. memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
  2241. /* Successive slices of b are copied into bslice. */
  2242. bslice = _PyLong_New(asize);
  2243. if (bslice == NULL)
  2244. goto fail;
  2245. nbdone = 0;
  2246. while (bsize > 0) {
  2247. PyLongObject *product;
  2248. const Py_ssize_t nbtouse = MIN(bsize, asize);
  2249. /* Multiply the next slice of b by a. */
  2250. memcpy(bslice->ob_digit, b->ob_digit + nbdone,
  2251. nbtouse * sizeof(digit));
  2252. Py_SIZE(bslice) = nbtouse;
  2253. product = k_mul(a, bslice);
  2254. if (product == NULL)
  2255. goto fail;
  2256. /* Add into result. */
  2257. (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
  2258. product->ob_digit, Py_SIZE(product));
  2259. Py_DECREF(product);
  2260. bsize -= nbtouse;
  2261. nbdone += nbtouse;
  2262. }
  2263. Py_DECREF(bslice);
  2264. return long_normalize(ret);
  2265. fail:
  2266. Py_DECREF(ret);
  2267. Py_XDECREF(bslice);
  2268. return NULL;
  2269. }
  2270. static PyObject *
  2271. long_mul(PyLongObject *v, PyLongObject *w)
  2272. {
  2273. PyLongObject *a, *b, *z;
  2274. if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
  2275. Py_INCREF(Py_NotImplemented);
  2276. return Py_NotImplemented;
  2277. }
  2278. z = k_mul(a, b);
  2279. /* Negate if exactly one of the inputs is negative. */
  2280. if (((a->ob_size ^ b->ob_size) < 0) && z)
  2281. z->ob_size = -(z->ob_size);
  2282. Py_DECREF(a);
  2283. Py_DECREF(b);
  2284. return (PyObject *)z;
  2285. }
  2286. /* The / and % operators are now defined in terms of divmod().
  2287. The expression a mod b has the value a - b*floor(a/b).
  2288. The long_divrem function gives the remainder after division of
  2289. |a| by |b|, with the sign of a. This is also expressed
  2290. as a - b*trunc(a/b), if trunc truncates towards zero.
  2291. Some examples:
  2292. a b a rem b a mod b
  2293. 13 10 3 3
  2294. -13 10 -3 7
  2295. 13 -10 3 -7
  2296. -13 -10 -3 -3
  2297. So, to get from rem to mod, we have to add b if a and b
  2298. have different signs. We then subtract one from the 'div'
  2299. part of the outcome to keep the invariant intact. */
  2300. /* Compute
  2301. * *pdiv, *pmod = divmod(v, w)
  2302. * NULL can be passed for pdiv or pmod, in which case that part of
  2303. * the result is simply thrown away. The caller owns a reference to
  2304. * each of these it requests (does not pass NULL for).
  2305. */
  2306. static int
  2307. l_divmod(PyLongObject *v, PyLongObject *w,
  2308. PyLongObject **pdiv, PyLongObject **pmod)
  2309. {
  2310. PyLongObject *div, *mod;
  2311. if (long_divrem(v, w, &div, &mod) < 0)
  2312. return -1;
  2313. if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
  2314. (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
  2315. PyLongObject *temp;
  2316. PyLongObject *one;
  2317. temp = (PyLongObject *) long_add(mod, w);
  2318. Py_DECREF(mod);
  2319. mod = temp;
  2320. if (mod == NULL) {
  2321. Py_DECREF(div);
  2322. return -1;
  2323. }
  2324. one = (PyLongObject *) PyLong_FromLong(1L);
  2325. if (one == NULL ||
  2326. (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
  2327. Py_DECREF(mod);
  2328. Py_DECREF(div);
  2329. Py_XDECREF(one);
  2330. return -1;
  2331. }
  2332. Py_DECREF(one);
  2333. Py_DECREF(div);
  2334. div = temp;
  2335. }
  2336. if (pdiv != NULL)
  2337. *pdiv = div;
  2338. else
  2339. Py_DECREF(div);
  2340. if (pmod != NULL)
  2341. *pmod = mod;
  2342. else
  2343. Py_DECREF(mod);
  2344. return 0;
  2345. }
  2346. static PyObject *
  2347. long_div(PyObject *v, PyObject *w)
  2348. {
  2349. PyLongObject *a, *b, *div;
  2350. CONVERT_BINOP(v, w, &a, &b);
  2351. if (l_divmod(a, b, &div, NULL) < 0)
  2352. div = NULL;
  2353. Py_DECREF(a);
  2354. Py_DECREF(b);
  2355. return (PyObject *)div;
  2356. }
  2357. static PyObject *
  2358. long_classic_div(PyObject *v, PyObject *w)
  2359. {
  2360. PyLongObject *a, *b, *div;
  2361. CONVERT_BINOP(v, w, &a, &b);
  2362. if (Py_DivisionWarningFlag &&
  2363. PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
  2364. div = NULL;
  2365. else if (l_divmod(a, b, &div, NULL) < 0)
  2366. div = NULL;
  2367. Py_DECREF(a);
  2368. Py_DECREF(b);
  2369. return (PyObject *)div;
  2370. }
  2371. static PyObject *
  2372. long_true_divide(PyObject *v, PyObject *w)
  2373. {
  2374. PyLongObject *a, *b;
  2375. double ad, bd;
  2376. int failed, aexp = -1, bexp = -1;
  2377. CONVERT_BINOP(v, w, &a, &b);
  2378. ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
  2379. bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
  2380. failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
  2381. Py_DECREF(a);
  2382. Py_DECREF(b);
  2383. if (failed)
  2384. return NULL;
  2385. /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
  2386. but should really be set correctly after sucessful calls to
  2387. _PyLong_AsScaledDouble() */
  2388. assert(aexp >= 0 && bexp >= 0);
  2389. if (bd == 0.0) {
  2390. PyErr_SetString(PyExc_ZeroDivisionError,
  2391. "long division or modulo by zero");
  2392. return NULL;
  2393. }
  2394. /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
  2395. ad /= bd; /* overflow/underflow impossible here */
  2396. aexp -= bexp;
  2397. if (aexp > INT_MAX / PyLong_SHIFT)
  2398. goto overflow;
  2399. else if (aexp < -(INT_MAX / PyLong_SHIFT))
  2400. return PyFloat_FromDouble(0.0); /* underflow to 0 */
  2401. errno = 0;
  2402. ad = ldexp(ad, aexp * PyLong_SHIFT);
  2403. if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
  2404. goto overflow;
  2405. return PyFloat_FromDouble(ad);
  2406. overflow:
  2407. PyErr_SetString(PyExc_OverflowError,
  2408. "long/long too large for a float");
  2409. return NULL;
  2410. }
  2411. static PyObject *
  2412. long_mod(PyObject *v, PyObject *w)
  2413. {
  2414. PyLongObject *a, *b, *mod;
  2415. CONVERT_BINOP(v, w, &a, &b);
  2416. if (l_divmod(a, b, NULL, &mod) < 0)
  2417. mod = NULL;
  2418. Py_DECREF(a);
  2419. Py_DECREF(b);
  2420. return (PyObject *)mod;
  2421. }
  2422. static PyObject *
  2423. long_divmod(PyObject *v, PyObject *w)
  2424. {
  2425. PyLongObject *a, *b, *div, *mod;
  2426. PyObject *z;
  2427. CONVERT_BINOP(v, w, &a, &b);
  2428. if (l_divmod(a, b, &div, &mod) < 0) {
  2429. Py_DECREF(a);
  2430. Py_DECREF(b);
  2431. return NULL;
  2432. }
  2433. z = PyTuple_New(2);
  2434. if (z != NULL) {
  2435. PyTuple_SetItem(z, 0, (PyObject *) div);
  2436. PyTuple_SetItem(z, 1, (PyObject *) mod);
  2437. }
  2438. else {
  2439. Py_DECREF(div);
  2440. Py_DECREF(mod);
  2441. }
  2442. Py_DECREF(a);
  2443. Py_DECREF(b);
  2444. return z;
  2445. }
  2446. /* pow(v, w, x) */
  2447. static PyObject *
  2448. long_pow(PyObject *v, PyObject *w, PyObject *x)
  2449. {
  2450. PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
  2451. int negativeOutput = 0; /* if x<0 return negative output */
  2452. PyLongObject *z = NULL; /* accumulated result */
  2453. Py_ssize_t i, j, k; /* counters */
  2454. PyLongObject *temp = NULL;
  2455. /* 5-ary values. If the exponent is large enough, table is
  2456. * precomputed so that table[i] == a**i % c for i in range(32).
  2457. */
  2458. PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  2459. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  2460. /* a, b, c = v, w, x */
  2461. CONVERT_BINOP(v, w, &a, &b);
  2462. if (PyLong_Check(x)) {
  2463. c = (PyLongObject *)x;
  2464. Py_INCREF(x);
  2465. }
  2466. else if (PyInt_Check(x)) {
  2467. c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
  2468. if (c == NULL)
  2469. goto Error;
  2470. }
  2471. else if (x == Py_None)
  2472. c = NULL;
  2473. else {
  2474. Py_DECREF(a);
  2475. Py_DECREF(b);
  2476. Py_INCREF(Py_NotImplemented);
  2477. return Py_NotImplemented;
  2478. }
  2479. if (Py_SIZE(b) < 0) { /* if exponent is negative */
  2480. if (c) {
  2481. PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
  2482. "cannot be negative when 3rd argument specified");
  2483. goto Error;
  2484. }
  2485. else {
  2486. /* else return a float. This works because we know
  2487. that this calls float_pow() which converts its
  2488. arguments to double. */
  2489. Py_DECREF(a);
  2490. Py_DECREF(b);
  2491. return PyFloat_Type.tp_as_number->nb_power(v, w, x);
  2492. }
  2493. }
  2494. if (c) {
  2495. /* if modulus == 0:
  2496. raise ValueError() */
  2497. if (Py_SIZE(c) == 0) {
  2498. PyErr_SetString(PyExc_ValueError,
  2499. "pow() 3rd argument cannot be 0");
  2500. goto Error;
  2501. }
  2502. /* if modulus < 0:
  2503. negativeOutput = True
  2504. modulus = -modulus */
  2505. if (Py_SIZE(c) < 0) {
  2506. negativeOutput = 1;
  2507. temp = (PyLongObject *)_PyLong_Copy(c);
  2508. if (temp == NULL)
  2509. goto Error;
  2510. Py_DECREF(c);
  2511. c = temp;
  2512. temp = NULL;
  2513. c->ob_size = - c->ob_size;
  2514. }
  2515. /* if modulus == 1:
  2516. return 0 */
  2517. if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
  2518. z = (PyLongObject *)PyLong_FromLong(0L);
  2519. goto Done;
  2520. }
  2521. /* if base < 0:
  2522. base = base % modulus
  2523. Having the base positive just makes things easier. */
  2524. if (Py_SIZE(a) < 0) {
  2525. if (l_divmod(a, c, NULL, &temp) < 0)
  2526. goto Error;
  2527. Py_DECREF(a);
  2528. a = temp;
  2529. temp = NULL;
  2530. }
  2531. }
  2532. /* At this point a, b, and c are guaranteed non-negative UNLESS
  2533. c is NULL, in which case a may be negative. */
  2534. z = (PyLongObject *)PyLong_FromLong(1L);
  2535. if (z == NULL)
  2536. goto Error;
  2537. /* Perform a modular reduction, X = X % c, but leave X alone if c
  2538. * is NULL.
  2539. */
  2540. #define REDUCE(X) \
  2541. if (c != NULL) { \
  2542. if (l_divmod(X, c, NULL, &temp) < 0) \
  2543. goto Error; \
  2544. Py_XDECREF(X); \
  2545. X = temp; \
  2546. temp = NULL; \
  2547. }
  2548. /* Multiply two values, then reduce the result:
  2549. result = X*Y % c. If c is NULL, skip the mod. */
  2550. #define MULT(X, Y, result) \
  2551. { \
  2552. temp = (PyLongObject *)long_mul(X, Y); \
  2553. if (temp == NULL) \
  2554. goto Error; \
  2555. Py_XDECREF(result); \
  2556. result = temp; \
  2557. temp = NULL; \
  2558. REDUCE(result) \
  2559. }
  2560. if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
  2561. /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
  2562. /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
  2563. for (i = Py_SIZE(b) - 1; i >= 0; --i) {
  2564. digit bi = b->ob_digit[i];
  2565. for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
  2566. MULT(z, z, z)
  2567. if (bi & j)
  2568. MULT(z, a, z)
  2569. }
  2570. }
  2571. }
  2572. else {
  2573. /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
  2574. Py_INCREF(z); /* still holds 1L */
  2575. table[0] = z;
  2576. for (i = 1; i < 32; ++i)
  2577. MULT(table[i-1], a, table[i])
  2578. for (i = Py_SIZE(b) - 1; i >= 0; --i) {
  2579. const digit bi = b->ob_digit[i];
  2580. for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
  2581. const int index = (bi >> j) & 0x1f;
  2582. for (k = 0; k < 5; ++k)
  2583. MULT(z, z, z)
  2584. if (index)
  2585. MULT(z, table[index], z)
  2586. }
  2587. }
  2588. }
  2589. if (negativeOutput && (Py_SIZE(z) != 0)) {
  2590. temp = (PyLongObject *)long_sub(z, c);
  2591. if (temp == NULL)
  2592. goto Error;
  2593. Py_DECREF(z);
  2594. z = temp;
  2595. temp = NULL;
  2596. }
  2597. goto Done;
  2598. Error:
  2599. if (z != NULL) {
  2600. Py_DECREF(z);
  2601. z = NULL;
  2602. }
  2603. /* fall through */
  2604. Done:
  2605. if (Py_SIZE(b) > FIVEARY_CUTOFF) {
  2606. for (i = 0; i < 32; ++i)
  2607. Py_XDECREF(table[i]);
  2608. }
  2609. Py_DECREF(a);
  2610. Py_DECREF(b);
  2611. Py_XDECREF(c);
  2612. Py_XDECREF(temp);
  2613. return (PyObject *)z;
  2614. }
  2615. static PyObject *
  2616. long_invert(PyLongObject *v)
  2617. {
  2618. /* Implement ~x as -(x+1) */
  2619. PyLongObject *x;
  2620. PyLongObject *w;
  2621. w = (PyLongObject *)PyLong_FromLong(1L);
  2622. if (w == NULL)
  2623. return NULL;
  2624. x = (PyLongObject *) long_add(v, w);
  2625. Py_DECREF(w);
  2626. if (x == NULL)
  2627. return NULL;
  2628. Py_SIZE(x) = -(Py_SIZE(x));
  2629. return (PyObject *)x;
  2630. }
  2631. static PyObject *
  2632. long_neg(PyLongObject *v)
  2633. {
  2634. PyLongObject *z;
  2635. if (v->ob_size == 0 && PyLong_CheckExact(v)) {
  2636. /* -0 == 0 */
  2637. Py_INCREF(v);
  2638. return (PyObject *) v;
  2639. }
  2640. z = (PyLongObject *)_PyLong_Copy(v);
  2641. if (z != NULL)
  2642. z->ob_size = -(v->ob_size);
  2643. return (PyObject *)z;
  2644. }
  2645. static PyObject *
  2646. long_abs(PyLongObject *v)
  2647. {
  2648. if (v->ob_size < 0)
  2649. return long_neg(v);
  2650. else
  2651. return long_long((PyObject *)v);
  2652. }
  2653. static int
  2654. long_nonzero(PyLongObject *v)
  2655. {
  2656. return ABS(Py_SIZE(v)) != 0;
  2657. }
  2658. static PyObject *
  2659. long_rshift(PyLongObject *v, PyLongObject *w)
  2660. {
  2661. PyLongObject *a, *b;
  2662. PyLongObject *z = NULL;
  2663. long shiftby;
  2664. Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
  2665. digit lomask, himask;
  2666. CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
  2667. if (Py_SIZE(a) < 0) {
  2668. /* Right shifting negative numbers is harder */
  2669. PyLongObject *a1, *a2;
  2670. a1 = (PyLongObject *) long_invert(a);
  2671. if (a1 == NULL)
  2672. goto rshift_error;
  2673. a2 = (PyLongObject *) long_rshift(a1, b);
  2674. Py_DECREF(a1);
  2675. if (a2 == NULL)
  2676. goto rshift_error;
  2677. z = (PyLongObject *) long_invert(a2);
  2678. Py_DECREF(a2);
  2679. }
  2680. else {
  2681. shiftby = PyLong_AsLong((PyObject *)b);
  2682. if (shiftby == -1L && PyErr_Occurred())
  2683. goto rshift_error;
  2684. if (shiftby < 0) {
  2685. PyErr_SetString(PyExc_ValueError,
  2686. "negative shift count");
  2687. goto rshift_error;
  2688. }
  2689. wordshift = shiftby / PyLong_SHIFT;
  2690. newsize = ABS(Py_SIZE(a)) - wordshift;
  2691. if (newsize <= 0) {
  2692. z = _PyLong_New(0);
  2693. Py_DECREF(a);
  2694. Py_DECREF(b);
  2695. return (PyObject *)z;
  2696. }
  2697. loshift = shiftby % PyLong_SHIFT;
  2698. hishift = PyLong_SHIFT - loshift;
  2699. lomask = ((digit)1 << hishift) - 1;
  2700. himask = PyLong_MASK ^ lomask;
  2701. z = _PyLong_New(newsize);
  2702. if (z == NULL)
  2703. goto rshift_error;
  2704. if (Py_SIZE(a) < 0)
  2705. Py_SIZE(z) = -(Py_SIZE(z));
  2706. for (i = 0, j = wordshift; i < newsize; i++, j++) {
  2707. z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
  2708. if (i+1 < newsize)
  2709. z->ob_digit[i] |=
  2710. (a->ob_digit[j+1] << hishift) & himask;
  2711. }
  2712. z = long_normalize(z);
  2713. }
  2714. rshift_error:
  2715. Py_DECREF(a);
  2716. Py_DECREF(b);
  2717. return (PyObject *) z;
  2718. }
  2719. static PyObject *
  2720. long_lshift(PyObject *v, PyObject *w)
  2721. {
  2722. /* This version due to Tim Peters */
  2723. PyLongObject *a, *b;
  2724. PyLongObject *z = NULL;
  2725. long shiftby;
  2726. Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
  2727. twodigits accum;
  2728. CONVERT_BINOP(v, w, &a, &b);
  2729. shiftby = PyLong_AsLong((PyObject *)b);
  2730. if (shiftby == -1L && PyErr_Occurred())
  2731. goto lshift_error;
  2732. if (shiftby < 0) {
  2733. PyErr_SetString(PyExc_ValueError, "negative shift count");
  2734. goto lshift_error;
  2735. }
  2736. if ((long)(int)shiftby != shiftby) {
  2737. PyErr_SetString(PyExc_ValueError,
  2738. "outrageous left shift count");
  2739. goto lshift_error;
  2740. }
  2741. /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
  2742. wordshift = (int)shiftby / PyLong_SHIFT;
  2743. remshift = (int)shiftby - wordshift * PyLong_SHIFT;
  2744. oldsize = ABS(a->ob_size);
  2745. newsize = oldsize + wordshift;
  2746. if (remshift)
  2747. ++newsize;
  2748. z = _PyLong_New(newsize);
  2749. if (z == NULL)
  2750. goto lshift_error;
  2751. if (a->ob_size < 0)
  2752. z->ob_size = -(z->ob_size);
  2753. for (i = 0; i < wordshift; i++)
  2754. z->ob_digit[i] = 0;
  2755. accum = 0;
  2756. for (i = wordshift, j = 0; j < oldsize; i++, j++) {
  2757. accum |= (twodigits)a->ob_digit[j] << remshift;
  2758. z->ob_digit[i] = (digit)(accum & PyLong_MASK);
  2759. accum >>= PyLong_SHIFT;
  2760. }
  2761. if (remshift)
  2762. z->ob_digit[newsize-1] = (digit)accum;
  2763. else
  2764. assert(!accum);
  2765. z = long_normalize(z);
  2766. lshift_error:
  2767. Py_DECREF(a);
  2768. Py_DECREF(b);
  2769. return (PyObject *) z;
  2770. }
  2771. /* Bitwise and/xor/or operations */
  2772. static PyObject *
  2773. long_bitwise(PyLongObject *a,
  2774. int op, /* '&', '|', '^' */
  2775. PyLongObject *b)
  2776. {
  2777. digit maska, maskb; /* 0 or PyLong_MASK */
  2778. int negz;
  2779. Py_ssize_t size_a, size_b, size_z;
  2780. PyLongObject *z;
  2781. int i;
  2782. digit diga, digb;
  2783. PyObject *v;
  2784. if (Py_SIZE(a) < 0) {
  2785. a = (PyLongObject *) long_invert(a);
  2786. if (a == NULL)
  2787. return NULL;
  2788. maska = PyLong_MASK;
  2789. }
  2790. else {
  2791. Py_INCREF(a);
  2792. maska = 0;
  2793. }
  2794. if (Py_SIZE(b) < 0) {
  2795. b = (PyLongObject *) long_invert(b);
  2796. if (b == NULL) {
  2797. Py_DECREF(a);
  2798. return NULL;
  2799. }
  2800. maskb = PyLong_MASK;
  2801. }
  2802. else {
  2803. Py_INCREF(b);
  2804. maskb = 0;
  2805. }
  2806. negz = 0;
  2807. switch (op) {
  2808. case '^':
  2809. if (maska != maskb) {
  2810. maska ^= PyLong_MASK;
  2811. negz = -1;
  2812. }
  2813. break;
  2814. case '&':
  2815. if (maska && maskb) {
  2816. op = '|';
  2817. maska ^= PyLong_MASK;
  2818. maskb ^= PyLong_MASK;
  2819. negz = -1;
  2820. }
  2821. break;
  2822. case '|':
  2823. if (maska || maskb) {
  2824. op = '&';
  2825. maska ^= PyLong_MASK;
  2826. maskb ^= PyLong_MASK;
  2827. negz = -1;
  2828. }
  2829. break;
  2830. }
  2831. /* JRH: The original logic here was to allocate the result value (z)
  2832. as the longer of the two operands. However, there are some cases
  2833. where the result is guaranteed to be shorter than that: AND of two
  2834. positives, OR of two negatives: use the shorter number. AND with
  2835. mixed signs: use the positive number. OR with mixed signs: use the
  2836. negative number. After the transformations above, op will be '&'
  2837. iff one of these cases applies, and mask will be non-0 for operands
  2838. whose length should be ignored.
  2839. */
  2840. size_a = Py_SIZE(a);
  2841. size_b = Py_SIZE(b);
  2842. size_z = op == '&'
  2843. ? (maska
  2844. ? size_b
  2845. : (maskb ? size_a : MIN(size_a, size_b)))
  2846. : MAX(size_a, size_b);
  2847. z = _PyLong_New(size_z);
  2848. if (z == NULL) {
  2849. Py_DECREF(a);
  2850. Py_DECREF(b);
  2851. return NULL;
  2852. }
  2853. for (i = 0; i < size_z; ++i) {
  2854. diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
  2855. digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
  2856. switch (op) {
  2857. case '&': z->ob_digit[i] = diga & digb; break;
  2858. case '|': z->ob_digit[i] = diga | digb; break;
  2859. case '^': z->ob_digit[i] = diga ^ digb; break;
  2860. }
  2861. }
  2862. Py_DECREF(a);
  2863. Py_DECREF(b);
  2864. z = long_normalize(z);
  2865. if (negz == 0)
  2866. return (PyObject *) z;
  2867. v = long_invert(z);
  2868. Py_DECREF(z);
  2869. return v;
  2870. }
  2871. static PyObject *
  2872. long_and(PyObject *v, PyObject *w)
  2873. {
  2874. PyLongObject *a, *b;
  2875. PyObject *c;
  2876. CONVERT_BINOP(v, w, &a, &b);
  2877. c = long_bitwise(a, '&', b);
  2878. Py_DECREF(a);
  2879. Py_DECREF(b);
  2880. return c;
  2881. }
  2882. static PyObject *
  2883. long_xor(PyObject *v, PyObject *w)
  2884. {
  2885. PyLongObject *a, *b;
  2886. PyObject *c;
  2887. CONVERT_BINOP(v, w, &a, &b);
  2888. c = long_bitwise(a, '^', b);
  2889. Py_DECREF(a);
  2890. Py_DECREF(b);
  2891. return c;
  2892. }
  2893. static PyObject *
  2894. long_or(PyObject *v, PyObject *w)
  2895. {
  2896. PyLongObject *a, *b;
  2897. PyObject *c;
  2898. CONVERT_BINOP(v, w, &a, &b);
  2899. c = long_bitwise(a, '|', b);
  2900. Py_DECREF(a);
  2901. Py_DECREF(b);
  2902. return c;
  2903. }
  2904. static int
  2905. long_coerce(PyObject **pv, PyObject **pw)
  2906. {
  2907. if (PyInt_Check(*pw)) {
  2908. *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
  2909. if (*pw == NULL)
  2910. return -1;
  2911. Py_INCREF(*pv);
  2912. return 0;
  2913. }
  2914. else if (PyLong_Check(*pw)) {
  2915. Py_INCREF(*pv);
  2916. Py_INCREF(*pw);
  2917. return 0;
  2918. }
  2919. return 1; /* Can't do it */
  2920. }
  2921. static PyObject *
  2922. long_long(PyObject *v)
  2923. {
  2924. if (PyLong_CheckExact(v))
  2925. Py_INCREF(v);
  2926. else
  2927. v = _PyLong_Copy((PyLongObject *)v);
  2928. return v;
  2929. }
  2930. static PyObject *
  2931. long_int(PyObject *v)
  2932. {
  2933. long x;
  2934. x = PyLong_AsLong(v);
  2935. if (PyErr_Occurred()) {
  2936. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  2937. PyErr_Clear();
  2938. if (PyLong_CheckExact(v)) {
  2939. Py_INCREF(v);
  2940. return v;
  2941. }
  2942. else
  2943. return _PyLong_Copy((PyLongObject *)v);
  2944. }
  2945. else
  2946. return NULL;
  2947. }
  2948. return PyInt_FromLong(x);
  2949. }
  2950. static PyObject *
  2951. long_float(PyObject *v)
  2952. {
  2953. double result;
  2954. result = PyLong_AsDouble(v);
  2955. if (result == -1.0 && PyErr_Occurred())
  2956. return NULL;
  2957. return PyFloat_FromDouble(result);
  2958. }
  2959. static PyObject *
  2960. long_oct(PyObject *v)
  2961. {
  2962. return _PyLong_Format(v, 8, 1, 0);
  2963. }
  2964. static PyObject *
  2965. long_hex(PyObject *v)
  2966. {
  2967. return _PyLong_Format(v, 16, 1, 0);
  2968. }
  2969. static PyObject *
  2970. long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  2971. static PyObject *
  2972. long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2973. {
  2974. PyObject *x = NULL;
  2975. int base = -909; /* unlikely! */
  2976. static char *kwlist[] = {"x", "base", 0};
  2977. if (type != &PyLong_Type)
  2978. return long_subtype_new(type, args, kwds); /* Wimp out */
  2979. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
  2980. &x, &base))
  2981. return NULL;
  2982. if (x == NULL)
  2983. return PyLong_FromLong(0L);
  2984. if (base == -909)
  2985. return PyNumber_Long(x);
  2986. else if (PyString_Check(x)) {
  2987. /* Since PyLong_FromString doesn't have a length parameter,
  2988. * check here for possible NULs in the string. */
  2989. char *string = PyString_AS_STRING(x);
  2990. if (strlen(string) != PyString_Size(x)) {
  2991. /* create a repr() of the input string,
  2992. * just like PyLong_FromString does. */
  2993. PyObject *srepr;
  2994. srepr = PyObject_Repr(x);
  2995. if (srepr == NULL)
  2996. return NULL;
  2997. PyErr_Format(PyExc_ValueError,
  2998. "invalid literal for long() with base %d: %s",
  2999. base, PyString_AS_STRING(srepr));
  3000. Py_DECREF(srepr);
  3001. return NULL;
  3002. }
  3003. return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
  3004. }
  3005. #ifdef Py_USING_UNICODE
  3006. else if (PyUnicode_Check(x))
  3007. return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
  3008. PyUnicode_GET_SIZE(x),
  3009. base);
  3010. #endif
  3011. else {
  3012. PyErr_SetString(PyExc_TypeError,
  3013. "long() can't convert non-string with explicit base");
  3014. return NULL;
  3015. }
  3016. }
  3017. /* Wimpy, slow approach to tp_new calls for subtypes of long:
  3018. first create a regular long from whatever arguments we got,
  3019. then allocate a subtype instance and initialize it from
  3020. the regular long. The regular long is then thrown away.
  3021. */
  3022. static PyObject *
  3023. long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3024. {
  3025. PyLongObject *tmp, *newobj;
  3026. Py_ssize_t i, n;
  3027. assert(PyType_IsSubtype(type, &PyLong_Type));
  3028. tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
  3029. if (tmp == NULL)
  3030. return NULL;
  3031. assert(PyLong_CheckExact(tmp));
  3032. n = Py_SIZE(tmp);
  3033. if (n < 0)
  3034. n = -n;
  3035. newobj = (PyLongObject *)type->tp_alloc(type, n);
  3036. if (newobj == NULL) {
  3037. Py_DECREF(tmp);
  3038. return NULL;
  3039. }
  3040. assert(PyLong_Check(newobj));
  3041. Py_SIZE(newobj) = Py_SIZE(tmp);
  3042. for (i = 0; i < n; i++)
  3043. newobj->ob_digit[i] = tmp->ob_digit[i];
  3044. Py_DECREF(tmp);
  3045. return (PyObject *)newobj;
  3046. }
  3047. static PyObject *
  3048. long_getnewargs(PyLongObject *v)
  3049. {
  3050. return Py_BuildValue("(N)", _PyLong_Copy(v));
  3051. }
  3052. static PyObject *
  3053. long_getN(PyLongObject *v, void *context) {
  3054. return PyLong_FromLong((Py_intptr_t)context);
  3055. }
  3056. static PyObject *
  3057. long__format__(PyObject *self, PyObject *args)
  3058. {
  3059. PyObject *format_spec;
  3060. if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
  3061. return NULL;
  3062. if (PyBytes_Check(format_spec))
  3063. return _PyLong_FormatAdvanced(self,
  3064. PyBytes_AS_STRING(format_spec),
  3065. PyBytes_GET_SIZE(format_spec));
  3066. if (PyUnicode_Check(format_spec)) {
  3067. /* Convert format_spec to a str */
  3068. PyObject *result;
  3069. PyObject *str_spec = PyObject_Str(format_spec);
  3070. if (str_spec == NULL)
  3071. return NULL;
  3072. result = _PyLong_FormatAdvanced(self,
  3073. PyBytes_AS_STRING(str_spec),
  3074. PyBytes_GET_SIZE(str_spec));
  3075. Py_DECREF(str_spec);
  3076. return result;
  3077. }
  3078. PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
  3079. return NULL;
  3080. }
  3081. static PyObject *
  3082. long_sizeof(PyLongObject *v)
  3083. {
  3084. Py_ssize_t res;
  3085. res = v->ob_type->tp_basicsize;
  3086. if (v->ob_size != 0)
  3087. res += abs(v->ob_size) * sizeof(digit);
  3088. return PyInt_FromSsize_t(res);
  3089. }
  3090. #if 0
  3091. static PyObject *
  3092. long_is_finite(PyObject *v)
  3093. {
  3094. Py_RETURN_TRUE;
  3095. }
  3096. #endif
  3097. static PyMethodDef long_methods[] = {
  3098. {"conjugate", (PyCFunction)long_long, METH_NOARGS,
  3099. "Returns self, the complex conjugate of any long."},
  3100. #if 0
  3101. {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
  3102. "Returns always True."},
  3103. #endif
  3104. {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
  3105. "Truncating an Integral returns itself."},
  3106. {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
  3107. {"__format__", (PyCFunction)long__format__, METH_VARARGS},
  3108. {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
  3109. "Returns size in memory, in bytes"},
  3110. {NULL, NULL} /* sentinel */
  3111. };
  3112. static PyGetSetDef long_getset[] = {
  3113. {"real",
  3114. (getter)long_long, (setter)NULL,
  3115. "the real part of a complex number",
  3116. NULL},
  3117. {"imag",
  3118. (getter)long_getN, (setter)NULL,
  3119. "the imaginary part of a complex number",
  3120. (void*)0},
  3121. {"numerator",
  3122. (getter)long_long, (setter)NULL,
  3123. "the numerator of a rational number in lowest terms",
  3124. NULL},
  3125. {"denominator",
  3126. (getter)long_getN, (setter)NULL,
  3127. "the denominator of a rational number in lowest terms",
  3128. (void*)1},
  3129. {NULL} /* Sentinel */
  3130. };
  3131. PyDoc_STRVAR(long_doc,
  3132. "long(x[, base]) -> integer\n\
  3133. \n\
  3134. Convert a string or number to a long integer, if possible. A floating\n\
  3135. point argument will be truncated towards zero (this does not include a\n\
  3136. string representation of a floating point number!) When converting a\n\
  3137. string, use the optional base. It is an error to supply a base when\n\
  3138. converting a non-string.");
  3139. static PyNumberMethods long_as_number = {
  3140. (binaryfunc) long_add, /*nb_add*/
  3141. (binaryfunc) long_sub, /*nb_subtract*/
  3142. (binaryfunc) long_mul, /*nb_multiply*/
  3143. long_classic_div, /*nb_divide*/
  3144. long_mod, /*nb_remainder*/
  3145. long_divmod, /*nb_divmod*/
  3146. long_pow, /*nb_power*/
  3147. (unaryfunc) long_neg, /*nb_negative*/
  3148. (unaryfunc) long_long, /*tp_positive*/
  3149. (unaryfunc) long_abs, /*tp_absolute*/
  3150. (inquiry) long_nonzero, /*tp_nonzero*/
  3151. (unaryfunc) long_invert, /*nb_invert*/
  3152. long_lshift, /*nb_lshift*/
  3153. (binaryfunc) long_rshift, /*nb_rshift*/
  3154. long_and, /*nb_and*/
  3155. long_xor, /*nb_xor*/
  3156. long_or, /*nb_or*/
  3157. long_coerce, /*nb_coerce*/
  3158. long_int, /*nb_int*/
  3159. long_long, /*nb_long*/
  3160. long_float, /*nb_float*/
  3161. long_oct, /*nb_oct*/
  3162. long_hex, /*nb_hex*/
  3163. 0, /* nb_inplace_add */
  3164. 0, /* nb_inplace_subtract */
  3165. 0, /* nb_inplace_multiply */
  3166. 0, /* nb_inplace_divide */
  3167. 0, /* nb_inplace_remainder */
  3168. 0, /* nb_inplace_power */
  3169. 0, /* nb_inplace_lshift */
  3170. 0, /* nb_inplace_rshift */
  3171. 0, /* nb_inplace_and */
  3172. 0, /* nb_inplace_xor */
  3173. 0, /* nb_inplace_or */
  3174. long_div, /* nb_floor_divide */
  3175. long_true_divide, /* nb_true_divide */
  3176. 0, /* nb_inplace_floor_divide */
  3177. 0, /* nb_inplace_true_divide */
  3178. long_long, /* nb_index */
  3179. };
  3180. PyTypeObject PyLong_Type = {
  3181. PyObject_HEAD_INIT(&PyType_Type)
  3182. 0, /* ob_size */
  3183. "long", /* tp_name */
  3184. sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
  3185. sizeof(digit), /* tp_itemsize */
  3186. long_dealloc, /* tp_dealloc */
  3187. 0, /* tp_print */
  3188. 0, /* tp_getattr */
  3189. 0, /* tp_setattr */
  3190. (cmpfunc)long_compare, /* tp_compare */
  3191. long_repr, /* tp_repr */
  3192. &long_as_number, /* tp_as_number */
  3193. 0, /* tp_as_sequence */
  3194. 0, /* tp_as_mapping */
  3195. (hashfunc)long_hash, /* tp_hash */
  3196. 0, /* tp_call */
  3197. long_str, /* tp_str */
  3198. PyObject_GenericGetAttr, /* tp_getattro */
  3199. 0, /* tp_setattro */
  3200. 0, /* tp_as_buffer */
  3201. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
  3202. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
  3203. long_doc, /* tp_doc */
  3204. 0, /* tp_traverse */
  3205. 0, /* tp_clear */
  3206. 0, /* tp_richcompare */
  3207. 0, /* tp_weaklistoffset */
  3208. 0, /* tp_iter */
  3209. 0, /* tp_iternext */
  3210. long_methods, /* tp_methods */
  3211. 0, /* tp_members */
  3212. long_getset, /* tp_getset */
  3213. 0, /* tp_base */
  3214. 0, /* tp_dict */
  3215. 0, /* tp_descr_get */
  3216. 0, /* tp_descr_set */
  3217. 0, /* tp_dictoffset */
  3218. 0, /* tp_init */
  3219. 0, /* tp_alloc */
  3220. long_new, /* tp_new */
  3221. PyObject_Del, /* tp_free */
  3222. };