home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Objects / longobject.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  41KB  |  1,802 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Long (arbitrary precision) integer object implementation */
  33.  
  34. /* XXX The functional organization of this file is terrible */
  35.  
  36. #include "Python.h"
  37. #include "longintrepr.h"
  38. #include "mymath.h"
  39.  
  40. #include <assert.h>
  41. #include <ctype.h>
  42.  
  43. #define ABS(x) ((x) < 0 ? -(x) : (x))
  44.  
  45. /* Forward */
  46. static PyLongObject *long_normalize Py_PROTO((PyLongObject *));
  47. static PyLongObject *mul1 Py_PROTO((PyLongObject *, wdigit));
  48. static PyLongObject *muladd1 Py_PROTO((PyLongObject *, wdigit, wdigit));
  49. static PyLongObject *divrem1 Py_PROTO((PyLongObject *, wdigit, digit *));
  50. static PyObject *long_format Py_PROTO((PyObject *aa, int base));
  51.  
  52. static int ticker;    /* XXX Could be shared with ceval? */
  53.  
  54. #define SIGCHECK(PyTryBlock) \
  55.     if (--ticker < 0) { \
  56.         ticker = 100; \
  57.         if (PyErr_CheckSignals()) { PyTryBlock; } \
  58.     }
  59.  
  60. /* Normalize (remove leading zeros from) a long int object.
  61.    Doesn't attempt to free the storage--in most cases, due to the nature
  62.    of the algorithms used, this could save at most be one word anyway. */
  63.  
  64. static PyLongObject *
  65. long_normalize(v)
  66.     register PyLongObject *v;
  67. {
  68.     int j = ABS(v->ob_size);
  69.     register int i = j;
  70.     
  71.     while (i > 0 && v->ob_digit[i-1] == 0)
  72.         --i;
  73.     if (i != j)
  74.         v->ob_size = (v->ob_size < 0) ? -(i) : i;
  75.     return v;
  76. }
  77.  
  78. /* Allocate a new long int object with size digits.
  79.    Return NULL and set exception if we run out of memory. */
  80.  
  81. PyLongObject *
  82. _PyLong_New(size)
  83.     int size;
  84. {
  85.     return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
  86. }
  87.  
  88. /* Create a new long int object from a C long int */
  89.  
  90. PyObject *
  91. PyLong_FromLong(ival)
  92.     long ival;
  93. {
  94.     /* Assume a C long fits in at most 5 'digits' */
  95.     /* Works on both 32- and 64-bit machines */
  96.     PyLongObject *v = _PyLong_New(5);
  97.     if (v != NULL) {
  98.         unsigned long t = ival;
  99.         int i;
  100.         if (ival < 0) {
  101.             t = -ival;
  102.             v->ob_size = -(v->ob_size);
  103.           }
  104.         for (i = 0; i < 5; i++) {
  105.             v->ob_digit[i] = (digit) (t & MASK);
  106.             t >>= SHIFT;
  107.         }
  108.         v = long_normalize(v);
  109.     }
  110.     return (PyObject *)v;
  111. }
  112.  
  113. /* Create a new long int object from a C unsigned long int */
  114.  
  115. PyObject *
  116. PyLong_FromUnsignedLong(ival)
  117.     unsigned long ival;
  118. {
  119.     /* Assume a C long fits in at most 5 'digits' */
  120.     /* Works on both 32- and 64-bit machines */
  121.     PyLongObject *v = _PyLong_New(5);
  122.     if (v != NULL) {
  123.         unsigned long t = ival;
  124.         int i;
  125.         for (i = 0; i < 5; i++) {
  126.             v->ob_digit[i] = (digit) (t & MASK);
  127.             t >>= SHIFT;
  128.         }
  129.         v = long_normalize(v);
  130.     }
  131.     return (PyObject *)v;
  132. }
  133.  
  134. /* Create a new long int object from a C double */
  135.  
  136. PyObject *
  137. #ifdef MPW
  138. PyLong_FromDouble(double dval)
  139. #else
  140. PyLong_FromDouble(dval)
  141.     double dval;
  142. #endif /* MPW */
  143. {
  144.     PyLongObject *v;
  145.     double frac;
  146.     int i, ndig, expo, neg;
  147.     neg = 0;
  148.     if (dval < 0.0) {
  149.         neg = 1;
  150.         dval = -dval;
  151.     }
  152.     frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
  153.     if (expo <= 0)
  154.         return PyLong_FromLong(0L);
  155.     ndig = (expo-1) / SHIFT + 1; /* Number of 'digits' in result */
  156.     v = _PyLong_New(ndig);
  157.     if (v == NULL)
  158.         return NULL;
  159.     frac = ldexp(frac, (expo-1) % SHIFT + 1);
  160.     for (i = ndig; --i >= 0; ) {
  161.         long bits = (long)frac;
  162.         v->ob_digit[i] = (digit) bits;
  163.         frac = frac - (double)bits;
  164.         frac = ldexp(frac, SHIFT);
  165.     }
  166.     if (neg)
  167.         v->ob_size = -(v->ob_size);
  168.     return (PyObject *)v;
  169. }
  170.  
  171. /* Get a C long int from a long int object.
  172.    Returns -1 and sets an error condition if overflow occurs. */
  173.  
  174. long
  175. PyLong_AsLong(vv)
  176.     PyObject *vv;
  177. {
  178.     /* This version by Tim Peters */
  179.     register PyLongObject *v;
  180.     unsigned long x, prev;
  181.     int i, sign;
  182.  
  183.     if (vv == NULL || !PyLong_Check(vv)) {
  184.         PyErr_BadInternalCall();
  185.         return -1;
  186.     }
  187.     v = (PyLongObject *)vv;
  188.     i = v->ob_size;
  189.     sign = 1;
  190.     x = 0;
  191.     if (i < 0) {
  192.         sign = -1;
  193.         i = -(i);
  194.     }
  195.     while (--i >= 0) {
  196.         prev = x;
  197.         x = (x << SHIFT) + v->ob_digit[i];
  198.         if ((x >> SHIFT) != prev)
  199.             goto overflow;
  200.     }
  201.     /* Haven't lost any bits, but if the sign bit is set we're in
  202.      * trouble *unless* this is the min negative number.  So,
  203.      * trouble iff sign bit set && (positive || some bit set other
  204.      * than the sign bit).
  205.      */
  206.     if ((long)x < 0 && (sign > 0 || (x << 1) != 0))
  207.         goto overflow;
  208.     return (long)x * sign;
  209.  
  210.  overflow:
  211.     PyErr_SetString(PyExc_OverflowError,
  212.             "long int too long to convert");
  213.     return -1;
  214. }
  215.  
  216. /* Get a C long int from a long int object.
  217.    Returns -1 and sets an error condition if overflow occurs. */
  218.  
  219. unsigned long
  220. PyLong_AsUnsignedLong(vv)
  221.     PyObject *vv;
  222. {
  223.     register PyLongObject *v;
  224.     unsigned long x, prev;
  225.     int i;
  226.     
  227.     if (vv == NULL || !PyLong_Check(vv)) {
  228.         PyErr_BadInternalCall();
  229.         return (unsigned long) -1;
  230.     }
  231.     v = (PyLongObject *)vv;
  232.     i = v->ob_size;
  233.     x = 0;
  234.     if (i < 0) {
  235.         PyErr_SetString(PyExc_OverflowError,
  236.                "can't convert negative value to unsigned long");
  237.         return (unsigned long) -1;
  238.     }
  239.     while (--i >= 0) {
  240.         prev = x;
  241.         x = (x << SHIFT) + v->ob_digit[i];
  242.         if ((x >> SHIFT) != prev) {
  243.             PyErr_SetString(PyExc_OverflowError,
  244.                 "long int too long to convert");
  245.             return (unsigned long) -1;
  246.         }
  247.     }
  248.     return x;
  249. }
  250.  
  251. /* Get a C double from a long int object. */
  252.  
  253. double
  254. PyLong_AsDouble(vv)
  255.     PyObject *vv;
  256. {
  257.     register PyLongObject *v;
  258.     double x;
  259.     double multiplier = (double) (1L << SHIFT);
  260.     int i, sign;
  261.     
  262.     if (vv == NULL || !PyLong_Check(vv)) {
  263.         PyErr_BadInternalCall();
  264.         return -1;
  265.     }
  266.     v = (PyLongObject *)vv;
  267.     i = v->ob_size;
  268.     sign = 1;
  269.     x = 0.0;
  270.     if (i < 0) {
  271.         sign = -1;
  272.         i = -(i);
  273.     }
  274.     while (--i >= 0) {
  275.         x = x*multiplier + (double)v->ob_digit[i];
  276.     }
  277.     return x * sign;
  278. }
  279.  
  280. /* Create a new long (or int) object from a C pointer */
  281.  
  282. PyObject *
  283. PyLong_FromVoidPtr(p)
  284.     void *p;
  285. {
  286. #if SIZEOF_VOID_P == SIZEOF_LONG
  287.     return PyInt_FromLong((long)p);
  288. #else
  289.     /* optimize null pointers */
  290.     if ( p == NULL )
  291.         return PyInt_FromLong(0);
  292.  
  293.     /* we can assume that HAVE_LONG_LONG is true. if not, then the
  294.        configuration process should have bailed (having big pointers
  295.        without long longs seems non-sensical) */
  296.     return PyLong_FromLongLong((LONG_LONG)p);
  297. #endif /* SIZEOF_VOID_P == SIZEOF_LONG */
  298. }
  299.  
  300. /* Get a C pointer from a long object (or an int object in some cases) */
  301.  
  302. void *
  303. PyLong_AsVoidPtr(vv)
  304.     PyObject *vv;
  305. {
  306.     /* This function will allow int or long objects. If vv is neither,
  307.        then the PyLong_AsLong*() functions will raise the exception:
  308.        PyExc_SystemError, "bad argument to internal function"
  309.     */
  310.  
  311. #if SIZEOF_VOID_P == SIZEOF_LONG
  312.     long x;
  313.  
  314.     if ( PyInt_Check(vv) )
  315.         x = PyInt_AS_LONG(vv);
  316.     else
  317.         x = PyLong_AsLong(vv);
  318. #else
  319.     /* we can assume that HAVE_LONG_LONG is true. if not, then the
  320.        configuration process should have bailed (having big pointers
  321.        without long longs seems non-sensical) */
  322.     LONG_LONG x;
  323.  
  324.     if ( PyInt_Check(vv) )
  325.         x = PyInt_AS_LONG(vv);
  326.     else
  327.         x = PyLong_AsLongLong(vv);
  328. #endif /* SIZEOF_VOID_P == SIZEOF_LONG */
  329.  
  330.     if (x == -1 && PyErr_Occurred())
  331.         return NULL;
  332.     return (void *)x;
  333. }
  334.  
  335. #ifdef HAVE_LONG_LONG
  336. /*
  337.  * LONG_LONG support by Chris Herborth (chrish@qnx.com)
  338.  *
  339.  * For better or worse :-), I tried to follow the coding style already
  340.  * here.
  341.  */
  342.  
  343. /* Create a new long int object from a C LONG_LONG int */
  344.  
  345. PyObject *
  346. PyLong_FromLongLong(ival)
  347.     LONG_LONG ival;
  348. {
  349. #if SIZEOF_LONG_LONG == SIZEOF_LONG
  350.     /* In case the compiler is faking it. */
  351.     return PyLong_FromLong( (long)ival );
  352. #else
  353.     if( ival <= (LONG_LONG)LONG_MAX ) {
  354.         return PyLong_FromLong( (long)ival );
  355.     }
  356.     else if( ival <= (unsigned LONG_LONG)ULONG_MAX ) {
  357.         return PyLong_FromUnsignedLong( (unsigned long)ival );
  358.     }
  359.     else {
  360.         /* Assume a C LONG_LONG fits in at most 10 'digits'.
  361.          * Should be OK if we're assuming long fits in 5.
  362.          */
  363.         PyLongObject *v = _PyLong_New(10);
  364.  
  365.         if (v != NULL) {
  366.             unsigned LONG_LONG t = ival;
  367.             int i;
  368.             if (ival < 0) {
  369.                 t = -ival;
  370.                 v->ob_size = -(v->ob_size);
  371.               }
  372.  
  373.             for (i = 0; i < 10; i++) {
  374.                 v->ob_digit[i] = (digit) (t & MASK);
  375.                 t >>= SHIFT;
  376.             }
  377.  
  378.             v = long_normalize(v);
  379.         }
  380.  
  381.         return (PyObject *)v;
  382.     }
  383. #endif
  384. }
  385.  
  386. /* Create a new long int object from a C unsigned LONG_LONG int */
  387. PyObject *
  388. PyLong_FromUnsignedLongLong(ival)
  389.     unsigned LONG_LONG ival;
  390. {
  391. #if SIZEOF_LONG_LONG == SIZEOF_LONG
  392.     /* In case the compiler is faking it. */
  393.     return PyLong_FromUnsignedLong( (unsigned long)ival );
  394. #else
  395.     if( ival <= (unsigned LONG_LONG)ULONG_MAX ) {
  396.         return PyLong_FromUnsignedLong( (unsigned long)ival );
  397.     }
  398.     else {
  399.         /* Assume a C long fits in at most 10 'digits'. */
  400.         PyLongObject *v = _PyLong_New(10);
  401.  
  402.         if (v != NULL) {
  403.             unsigned LONG_LONG t = ival;
  404.             int i;
  405.             for (i = 0; i < 10; i++) {
  406.                 v->ob_digit[i] = (digit) (t & MASK);
  407.                 t >>= SHIFT;
  408.             }
  409.  
  410.             v = long_normalize(v);
  411.         }
  412.  
  413.         return (PyObject *)v;
  414.     }
  415. #endif
  416. }
  417.  
  418. /* Get a C LONG_LONG int from a long int object.
  419.    Returns -1 and sets an error condition if overflow occurs. */
  420.  
  421. LONG_LONG
  422. PyLong_AsLongLong(vv)
  423.     PyObject *vv;
  424. {
  425. #if SIZEOF_LONG_LONG == SIZEOF_LONG
  426.     /* In case the compiler is faking it. */
  427.     return (LONG_LONG)PyLong_AsLong( vv );
  428. #else
  429.     register PyLongObject *v;
  430.     LONG_LONG x, prev;
  431.     int i, sign;
  432.     
  433.     if (vv == NULL || !PyLong_Check(vv)) {
  434.         PyErr_BadInternalCall();
  435.         return -1;
  436.     }
  437.  
  438.     v = (PyLongObject *)vv;
  439.     i = v->ob_size;
  440.     sign = 1;
  441.     x = 0;
  442.  
  443.     if (i < 0) {
  444.         sign = -1;
  445.         i = -(i);
  446.     }
  447.  
  448.     while (--i >= 0) {
  449.         prev = x;
  450.         x = (x << SHIFT) + v->ob_digit[i];
  451.         if ((x >> SHIFT) != prev) {
  452.             PyErr_SetString(PyExc_OverflowError,
  453.                 "long int too long to convert");
  454.             return -1;
  455.         }
  456.     }
  457.  
  458.     return x * sign;
  459. #endif
  460. }
  461.  
  462. unsigned LONG_LONG
  463. PyLong_AsUnsignedLongLong(vv)
  464.     PyObject *vv;
  465. {
  466. #if SIZEOF_LONG_LONG == 4
  467.     /* In case the compiler is faking it. */
  468.     return (unsigned LONG_LONG)PyLong_AsUnsignedLong( vv );
  469. #else
  470.     register PyLongObject *v;
  471.     unsigned LONG_LONG x, prev;
  472.     int i;
  473.     
  474.     if (vv == NULL || !PyLong_Check(vv)) {
  475.         PyErr_BadInternalCall();
  476.         return (unsigned LONG_LONG) -1;
  477.     }
  478.  
  479.     v = (PyLongObject *)vv;
  480.     i = v->ob_size;
  481.     x = 0;
  482.  
  483.     if (i < 0) {
  484.         PyErr_SetString(PyExc_OverflowError,
  485.                "can't convert negative value to unsigned long");
  486.         return (unsigned LONG_LONG) -1;
  487.     }
  488.  
  489.     while (--i >= 0) {
  490.         prev = x;
  491.         x = (x << SHIFT) + v->ob_digit[i];
  492.         if ((x >> SHIFT) != prev) {
  493.             PyErr_SetString(PyExc_OverflowError,
  494.                 "long int too long to convert");
  495.             return (unsigned LONG_LONG) -1;
  496.         }
  497.     }
  498.  
  499.     return x;
  500. #endif
  501. }
  502. #endif /* HAVE_LONG_LONG */
  503.  
  504. /* Multiply by a single digit, ignoring the sign. */
  505.  
  506. static PyLongObject *
  507. mul1(a, n)
  508.     PyLongObject *a;
  509.     wdigit n;
  510. {
  511.     return muladd1(a, n, (digit)0);
  512. }
  513.  
  514. /* Multiply by a single digit and add a single digit, ignoring the sign. */
  515.  
  516. static PyLongObject *
  517. muladd1(a, n, extra)
  518.     PyLongObject *a;
  519.     wdigit n;
  520.     wdigit extra;
  521. {
  522.     int size_a = ABS(a->ob_size);
  523.     PyLongObject *z = _PyLong_New(size_a+1);
  524.     twodigits carry = extra;
  525.     int i;
  526.     
  527.     if (z == NULL)
  528.         return NULL;
  529.     for (i = 0; i < size_a; ++i) {
  530.         carry += (twodigits)a->ob_digit[i] * n;
  531.         z->ob_digit[i] = (digit) (carry & MASK);
  532.         carry >>= SHIFT;
  533.     }
  534.     z->ob_digit[i] = (digit) carry;
  535.     return long_normalize(z);
  536. }
  537.  
  538. /* Divide a long integer by a digit, returning both the quotient
  539.    (as function result) and the remainder (through *prem).
  540.    The sign of a is ignored; n should not be zero. */
  541.  
  542. static PyLongObject *
  543. divrem1(a, n, prem)
  544.     PyLongObject *a;
  545.     wdigit n;
  546.     digit *prem;
  547. {
  548.     int size = ABS(a->ob_size);
  549.     PyLongObject *z;
  550.     int i;
  551.     twodigits rem = 0;
  552.     
  553.     assert(n > 0 && n <= MASK);
  554.     z = _PyLong_New(size);
  555.     if (z == NULL)
  556.         return NULL;
  557.     for (i = size; --i >= 0; ) {
  558.         rem = (rem << SHIFT) + a->ob_digit[i];
  559.         z->ob_digit[i] = (digit) (rem/n);
  560.         rem %= n;
  561.     }
  562.     *prem = (digit) rem;
  563.     return long_normalize(z);
  564. }
  565.  
  566. /* Convert a long int object to a string, using a given conversion base.
  567.    Return a string object.
  568.    If base is 8 or 16, add the proper prefix '0' or '0x'.
  569.    External linkage: used in bltinmodule.c by hex() and oct(). */
  570.  
  571. static PyObject *
  572. long_format(aa, base)
  573.     PyObject *aa;
  574.     int base;
  575. {
  576.     register PyLongObject *a = (PyLongObject *)aa;
  577.     PyStringObject *str;
  578.     int i;
  579.     int size_a = ABS(a->ob_size);
  580.     char *p;
  581.     int bits;
  582.     char sign = '\0';
  583.  
  584.     if (a == NULL || !PyLong_Check(a)) {
  585.         PyErr_BadInternalCall();
  586.         return NULL;
  587.     }
  588.     assert(base >= 2 && base <= 36);
  589.     
  590.     /* Compute a rough upper bound for the length of the string */
  591.     i = base;
  592.     bits = 0;
  593.     while (i > 1) {
  594.         ++bits;
  595.         i >>= 1;
  596.     }
  597.     i = 6 + (size_a*SHIFT + bits-1) / bits;
  598.     str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i);
  599.     if (str == NULL)
  600.         return NULL;
  601.     p = PyString_AS_STRING(str) + i;
  602.     *p = '\0';
  603.     *--p = 'L';
  604.     if (a->ob_size < 0)
  605.         sign = '-';
  606.     
  607.     if (a->ob_size == 0) {
  608.         *--p = '0';
  609.     }
  610.     else if ((base & (base - 1)) == 0) {
  611.         /* JRH: special case for power-of-2 bases */
  612.         twodigits temp = a->ob_digit[0];
  613.         int bitsleft = SHIFT;
  614.         int rem;
  615.         int last = abs(a->ob_size);
  616.         int basebits = 1;
  617.         i = base;
  618.         while ((i >>= 1) > 1) ++basebits;
  619.         
  620.         i = 0;
  621.         for (;;) {
  622.             while (bitsleft >= basebits) {
  623.                 if ((temp == 0) && (i >= last - 1)) break;
  624.                 rem = temp & (base - 1);
  625.                 if (rem < 10)
  626.                     rem += '0';
  627.                 else
  628.                     rem += 'A' - 10;
  629.                 assert(p > PyString_AS_STRING(str));
  630.                 *--p = (char) rem;
  631.                 bitsleft -= basebits;
  632.                 temp >>= basebits;
  633.             }
  634.             if (++i >= last) {
  635.                 if (temp == 0) break;
  636.                 bitsleft = 99;
  637.                 /* loop again to pick up final digits */
  638.             }
  639.             else {
  640.                 temp = (a->ob_digit[i] << bitsleft) | temp;
  641.                 bitsleft += SHIFT;
  642.             }
  643.         }
  644.     }
  645.     else {
  646.         Py_INCREF(a);
  647.         do {
  648.             digit rem;
  649.             PyLongObject *temp = divrem1(a, (digit)base, &rem);
  650.             if (temp == NULL) {
  651.                 Py_DECREF(a);
  652.                 Py_DECREF(str);
  653.                 return NULL;
  654.             }
  655.             if (rem < 10)
  656.                 rem += '0';
  657.             else
  658.                 rem += 'A'-10;
  659.             assert(p > PyString_AS_STRING(str));
  660.             *--p = (char) rem;
  661.             Py_DECREF(a);
  662.             a = temp;
  663.             SIGCHECK({
  664.                 Py_DECREF(a);
  665.                 Py_DECREF(str);
  666.                 return NULL;
  667.             })
  668.         } while (ABS(a->ob_size) != 0);
  669.         Py_DECREF(a);
  670.     }
  671.  
  672.     if (base == 8) {
  673.         if (size_a != 0)
  674.             *--p = '0';
  675.     }
  676.     else if (base == 16) {
  677.         *--p = 'x';
  678.         *--p = '0';
  679.     }
  680.     else if (base != 10) {
  681.         *--p = '#';
  682.         *--p = '0' + base%10;
  683.         if (base > 10)
  684.             *--p = '0' + base/10;
  685.     }
  686.     if (sign)
  687.         *--p = sign;
  688.     if (p != PyString_AS_STRING(str)) {
  689.         char *q = PyString_AS_STRING(str);
  690.         assert(p > q);
  691.         do {
  692.         } while ((*q++ = *p++) != '\0');
  693.         q--;
  694.         _PyString_Resize((PyObject **)&str,
  695.                  (int) (q - PyString_AS_STRING(str)));
  696.     }
  697.     return (PyObject *)str;
  698. }
  699.  
  700. #if 0
  701. /* Convert a string to a long int object, in a given base.
  702.    Base zero implies a default depending on the number.
  703.    External linkage: used in compile.c and stropmodule.c. */
  704.  
  705. PyObject *
  706. long_scan(str, base)
  707.     char *str;
  708.     int base;
  709. {
  710.     return PyLong_FromString(str, (char **)NULL, base);
  711. }
  712. #endif
  713.  
  714. PyObject *
  715. PyLong_FromString(str, pend, base)
  716.     char *str;
  717.     char **pend;
  718.     int base;
  719. {
  720.     int sign = 1;
  721.     char *start;
  722.     PyLongObject *z;
  723.     
  724.     if ((base != 0 && base < 2) || base > 36) {
  725.         PyErr_SetString(PyExc_ValueError,
  726.                 "invalid base for long literal");
  727.         return NULL;
  728.     }
  729.     while (*str != '\0' && isspace(Py_CHARMASK(*str)))
  730.         str++;
  731.     if (*str == '+')
  732.         ++str;
  733.     else if (*str == '-') {
  734.         ++str;
  735.         sign = -1;
  736.     }
  737.     while (*str != '\0' && isspace(Py_CHARMASK(*str)))
  738.         str++;
  739.     if (base == 0) {
  740.         if (str[0] != '0')
  741.             base = 10;
  742.         else if (str[1] == 'x' || str[1] == 'X')
  743.             base = 16;
  744.         else
  745.             base = 8;
  746.     }
  747.     if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
  748.         str += 2;
  749.     z = _PyLong_New(0);
  750.     start = str;
  751.     for ( ; z != NULL; ++str) {
  752.         int k = -1;
  753.         PyLongObject *temp;
  754.         
  755.         if (*str <= '9')
  756.             k = *str - '0';
  757.         else if (*str >= 'a')
  758.             k = *str - 'a' + 10;
  759.         else if (*str >= 'A')
  760.             k = *str - 'A' + 10;
  761.         if (k < 0 || k >= base)
  762.             break;
  763.         temp = muladd1(z, (digit)base, (digit)k);
  764.         Py_DECREF(z);
  765.         z = temp;
  766.     }
  767.     if (z == NULL)
  768.         return NULL;
  769.     if (str == start) {
  770.         PyErr_SetString(PyExc_ValueError,
  771.                 "no digits in long int constant");
  772.         Py_DECREF(z);
  773.         return NULL;
  774.     }
  775.     if (sign < 0 && z != NULL && z->ob_size != 0)
  776.         z->ob_size = -(z->ob_size);
  777.     if (pend)
  778.         *pend = str;
  779.     return (PyObject *) z;
  780. }
  781.  
  782. static PyLongObject *x_divrem
  783.     Py_PROTO((PyLongObject *, PyLongObject *, PyLongObject **));
  784. static PyObject *long_pos Py_PROTO((PyLongObject *));
  785. static int long_divrem Py_PROTO((PyLongObject *, PyLongObject *,
  786.     PyLongObject **, PyLongObject **));
  787.  
  788. /* Long division with remainder, top-level routine */
  789.  
  790. static int
  791. long_divrem(a, b, pdiv, prem)
  792.     PyLongObject *a, *b;
  793.     PyLongObject **pdiv;
  794.     PyLongObject **prem;
  795. {
  796.     int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
  797.     PyLongObject *z;
  798.     
  799.     if (size_b == 0) {
  800.         PyErr_SetString(PyExc_ZeroDivisionError,
  801.                 "long division or modulo");
  802.         return -1;
  803.     }
  804.     if (size_a < size_b ||
  805.         (size_a == size_b &&
  806.          a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
  807.         /* |a| < |b|. */
  808.         *pdiv = _PyLong_New(0);
  809.         Py_INCREF(a);
  810.         *prem = (PyLongObject *) a;
  811.         return 0;
  812.     }
  813.     if (size_b == 1) {
  814.         digit rem = 0;
  815.         z = divrem1(a, b->ob_digit[0], &rem);
  816.         if (z == NULL)
  817.             return -1;
  818.         *prem = (PyLongObject *) PyLong_FromLong((long)rem);
  819.     }
  820.     else {
  821.         z = x_divrem(a, b, prem);
  822.         if (z == NULL)
  823.             return -1;
  824.     }
  825.     /* Set the signs.
  826.        The quotient z has the sign of a*b;
  827.        the remainder r has the sign of a,
  828.        so a = b*z + r. */
  829.     if ((a->ob_size < 0) != (b->ob_size < 0))
  830.         z->ob_size = -(z->ob_size);
  831.     if (a->ob_size < 0 && (*prem)->ob_size != 0)
  832.         (*prem)->ob_size = -((*prem)->ob_size);
  833.     *pdiv = z;
  834.     return 0;
  835. }
  836.  
  837. /* Unsigned long division with remainder -- the algorithm */
  838.  
  839. static PyLongObject *
  840. x_divrem(v1, w1, prem)
  841.     PyLongObject *v1, *w1;
  842.     PyLongObject **prem;
  843. {
  844.     int size_v = ABS(v1->ob_size), size_w = ABS(w1->ob_size);
  845.     digit d = (digit) ((twodigits)BASE / (w1->ob_digit[size_w-1] + 1));
  846.     PyLongObject *v = mul1(v1, d);
  847.     PyLongObject *w = mul1(w1, d);
  848.     PyLongObject *a;
  849.     int j, k;
  850.     
  851.     if (v == NULL || w == NULL) {
  852.         Py_XDECREF(v);
  853.         Py_XDECREF(w);
  854.         return NULL;
  855.     }
  856.     
  857.     assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
  858.     assert(v->ob_refcnt == 1); /* Since v will be used as accumulator! */
  859.     assert(size_w == ABS(w->ob_size)); /* That's how d was calculated */
  860.     
  861.     size_v = ABS(v->ob_size);
  862.     a = _PyLong_New(size_v - size_w + 1);
  863.     
  864.     for (j = size_v, k = a->ob_size-1; a != NULL && k >= 0; --j, --k) {
  865.         digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
  866.         twodigits q;
  867.         stwodigits carry = 0;
  868.         int i;
  869.         
  870.         SIGCHECK({
  871.             Py_DECREF(a);
  872.             a = NULL;
  873.             break;
  874.         })
  875.         if (vj == w->ob_digit[size_w-1])
  876.             q = MASK;
  877.         else
  878.             q = (((twodigits)vj << SHIFT) + v->ob_digit[j-1]) /
  879.                 w->ob_digit[size_w-1];
  880.         
  881.         while (w->ob_digit[size_w-2]*q >
  882.                 ((
  883.                     ((twodigits)vj << SHIFT)
  884.                     + v->ob_digit[j-1]
  885.                     - q*w->ob_digit[size_w-1]
  886.                                 ) << SHIFT)
  887.                 + v->ob_digit[j-2])
  888.             --q;
  889.         
  890.         for (i = 0; i < size_w && i+k < size_v; ++i) {
  891.             twodigits z = w->ob_digit[i] * q;
  892.             digit zz = (digit) (z >> SHIFT);
  893.             carry += v->ob_digit[i+k] - z
  894.                 + ((twodigits)zz << SHIFT);
  895.             v->ob_digit[i+k] = carry & MASK;
  896.             carry = (carry >> SHIFT) - zz;
  897.         }
  898.         
  899.         if (i+k < size_v) {
  900.             carry += v->ob_digit[i+k];
  901.             v->ob_digit[i+k] = 0;
  902.         }
  903.         
  904.         if (carry == 0)
  905.             a->ob_digit[k] = (digit) q;
  906.         else {
  907.             assert(carry == -1);
  908.             a->ob_digit[k] = (digit) q-1;
  909.             carry = 0;
  910.             for (i = 0; i < size_w && i+k < size_v; ++i) {
  911.                 carry += v->ob_digit[i+k] + w->ob_digit[i];
  912.                 v->ob_digit[i+k] = carry & MASK;
  913.                 carry >>= SHIFT;
  914.             }
  915.         }
  916.     } /* for j, k */
  917.     
  918.     if (a == NULL)
  919.         *prem = NULL;
  920.     else {
  921.         a = long_normalize(a);
  922.         *prem = divrem1(v, d, &d);
  923.         /* d receives the (unused) remainder */
  924.         if (*prem == NULL) {
  925.             Py_DECREF(a);
  926.             a = NULL;
  927.         }
  928.     }
  929.     Py_DECREF(v);
  930.     Py_DECREF(w);
  931.     return a;
  932. }
  933.  
  934. /* Methods */
  935.  
  936. /* Forward */
  937. static void long_dealloc Py_PROTO((PyObject *));
  938. static PyObject *long_repr Py_PROTO((PyObject *));
  939. static int long_compare Py_PROTO((PyLongObject *, PyLongObject *));
  940. static long long_hash Py_PROTO((PyLongObject *));
  941.  
  942. static PyObject *long_add Py_PROTO((PyLongObject *, PyLongObject *));
  943. static PyObject *long_sub Py_PROTO((PyLongObject *, PyLongObject *));
  944. static PyObject *long_mul Py_PROTO((PyLongObject *, PyLongObject *));
  945. static PyObject *long_div Py_PROTO((PyLongObject *, PyLongObject *));
  946. static PyObject *long_mod Py_PROTO((PyLongObject *, PyLongObject *));
  947. static PyObject *long_divmod Py_PROTO((PyLongObject *, PyLongObject *));
  948. static PyObject *long_pow
  949.     Py_PROTO((PyLongObject *, PyLongObject *, PyLongObject *));
  950. static PyObject *long_neg Py_PROTO((PyLongObject *));
  951. static PyObject *long_pos Py_PROTO((PyLongObject *));
  952. static PyObject *long_abs Py_PROTO((PyLongObject *));
  953. static int long_nonzero Py_PROTO((PyLongObject *));
  954. static PyObject *long_invert Py_PROTO((PyLongObject *));
  955. static PyObject *long_lshift Py_PROTO((PyLongObject *, PyLongObject *));
  956. static PyObject *long_rshift Py_PROTO((PyLongObject *, PyLongObject *));
  957. static PyObject *long_and Py_PROTO((PyLongObject *, PyLongObject *));
  958. static PyObject *long_xor Py_PROTO((PyLongObject *, PyLongObject *));
  959. static PyObject *long_or Py_PROTO((PyLongObject *, PyLongObject *));
  960.  
  961. static void
  962. long_dealloc(v)
  963.     PyObject *v;
  964. {
  965.     PyMem_DEL(v);
  966. }
  967.  
  968. static PyObject *
  969. long_repr(v)
  970.     PyObject *v;
  971. {
  972.     return long_format(v, 10);
  973. }
  974.  
  975. static int
  976. long_compare(a, b)
  977.     PyLongObject *a, *b;
  978. {
  979.     int sign;
  980.     
  981.     if (a->ob_size != b->ob_size) {
  982.         if (ABS(a->ob_size) == 0 && ABS(b->ob_size) == 0)
  983.             sign = 0;
  984.         else
  985.             sign = a->ob_size - b->ob_size;
  986.     }
  987.     else {
  988.         int i = ABS(a->ob_size);
  989.         while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
  990.             ;
  991.         if (i < 0)
  992.             sign = 0;
  993.         else {
  994.             sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
  995.             if (a->ob_size < 0)
  996.                 sign = -sign;
  997.         }
  998.     }
  999.     return sign < 0 ? -1 : sign > 0 ? 1 : 0;
  1000. }
  1001.  
  1002. static long
  1003. long_hash(v)
  1004.     PyLongObject *v;
  1005. {
  1006.     long x;
  1007.     int i, sign;
  1008.  
  1009.     /* This is designed so that Python ints and longs with the
  1010.        same value hash to the same value, otherwise comparisons
  1011.        of mapping keys will turn out weird */
  1012.     i = v->ob_size;
  1013.     sign = 1;
  1014.     x = 0;
  1015.     if (i < 0) {
  1016.         sign = -1;
  1017.         i = -(i);
  1018.     }
  1019.     while (--i >= 0) {
  1020.         /* Force a 32-bit circular shift */
  1021.         x = ((x << SHIFT) & ~MASK) | ((x >> (32-SHIFT)) & MASK);
  1022.         x += v->ob_digit[i];
  1023.     }
  1024.     x = x * sign;
  1025.     if (x == -1)
  1026.         x = -2;
  1027.     return x;
  1028. }
  1029.  
  1030.  
  1031. /* Add the absolute values of two long integers. */
  1032.  
  1033. static PyLongObject *x_add Py_PROTO((PyLongObject *, PyLongObject *));
  1034. static PyLongObject *
  1035. x_add(a, b)
  1036.     PyLongObject *a, *b;
  1037. {
  1038.     int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
  1039.     PyLongObject *z;
  1040.     int i;
  1041.     digit carry = 0;
  1042.     
  1043.     /* Ensure a is the larger of the two: */
  1044.     if (size_a < size_b) {
  1045.         { PyLongObject *temp = a; a = b; b = temp; }
  1046.         { int size_temp = size_a;
  1047.           size_a = size_b;
  1048.           size_b = size_temp; }
  1049.     }
  1050.     z = _PyLong_New(size_a+1);
  1051.     if (z == NULL)
  1052.         return NULL;
  1053.     for (i = 0; i < size_b; ++i) {
  1054.         carry += a->ob_digit[i] + b->ob_digit[i];
  1055.         z->ob_digit[i] = carry & MASK;
  1056.         /* The following assumes unsigned shifts don't
  1057.            propagate the sign bit. */
  1058.         carry >>= SHIFT;
  1059.     }
  1060.     for (; i < size_a; ++i) {
  1061.         carry += a->ob_digit[i];
  1062.         z->ob_digit[i] = carry & MASK;
  1063.         carry >>= SHIFT;
  1064.     }
  1065.     z->ob_digit[i] = carry;
  1066.     return long_normalize(z);
  1067. }
  1068.  
  1069. /* Subtract the absolute values of two integers. */
  1070.  
  1071. static PyLongObject *x_sub Py_PROTO((PyLongObject *, PyLongObject *));
  1072. static PyLongObject *
  1073. x_sub(a, b)
  1074.     PyLongObject *a, *b;
  1075. {
  1076.     int size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
  1077.     PyLongObject *z;
  1078.     int i;
  1079.     int sign = 1;
  1080.     digit borrow = 0;
  1081.     
  1082.     /* Ensure a is the larger of the two: */
  1083.     if (size_a < size_b) {
  1084.         sign = -1;
  1085.         { PyLongObject *temp = a; a = b; b = temp; }
  1086.         { int size_temp = size_a;
  1087.           size_a = size_b;
  1088.           size_b = size_temp; }
  1089.     }
  1090.     else if (size_a == size_b) {
  1091.         /* Find highest digit where a and b differ: */
  1092.         i = size_a;
  1093.         while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
  1094.             ;
  1095.         if (i < 0)
  1096.             return _PyLong_New(0);
  1097.         if (a->ob_digit[i] < b->ob_digit[i]) {
  1098.             sign = -1;
  1099.             { PyLongObject *temp = a; a = b; b = temp; }
  1100.         }
  1101.         size_a = size_b = i+1;
  1102.     }
  1103.     z = _PyLong_New(size_a);
  1104.     if (z == NULL)
  1105.         return NULL;
  1106.     for (i = 0; i < size_b; ++i) {
  1107.         /* The following assumes unsigned arithmetic
  1108.            works module 2**N for some N>SHIFT. */
  1109.         borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
  1110.         z->ob_digit[i] = borrow & MASK;
  1111.         borrow >>= SHIFT;
  1112.         borrow &= 1; /* Keep only one sign bit */
  1113.     }
  1114.     for (; i < size_a; ++i) {
  1115.         borrow = a->ob_digit[i] - borrow;
  1116.         z->ob_digit[i] = borrow & MASK;
  1117.         borrow >>= SHIFT;
  1118.     }
  1119.     assert(borrow == 0);
  1120.     if (sign < 0)
  1121.         z->ob_size = -(z->ob_size);
  1122.     return long_normalize(z);
  1123. }
  1124.  
  1125. static PyObject *
  1126. long_add(a, b)
  1127.     PyLongObject *a;
  1128.     PyLongObject *b;
  1129. {
  1130.     PyLongObject *z;
  1131.     
  1132.     if (a->ob_size < 0) {
  1133.         if (b->ob_size < 0) {
  1134.             z = x_add(a, b);
  1135.             if (z != NULL && z->ob_size != 0)
  1136.                 z->ob_size = -(z->ob_size);
  1137.         }
  1138.         else
  1139.             z = x_sub(b, a);
  1140.     }
  1141.     else {
  1142.         if (b->ob_size < 0)
  1143.             z = x_sub(a, b);
  1144.         else
  1145.             z = x_add(a, b);
  1146.     }
  1147.     return (PyObject *)z;
  1148. }
  1149.  
  1150. static PyObject *
  1151. long_sub(a, b)
  1152.     PyLongObject *a;
  1153.     PyLongObject *b;
  1154. {
  1155.     PyLongObject *z;
  1156.     
  1157.     if (a->ob_size < 0) {
  1158.         if (b->ob_size < 0)
  1159.             z = x_sub(a, b);
  1160.         else
  1161.             z = x_add(a, b);
  1162.         if (z != NULL && z->ob_size != 0)
  1163.             z->ob_size = -(z->ob_size);
  1164.     }
  1165.     else {
  1166.         if (b->ob_size < 0)
  1167.             z = x_add(a, b);
  1168.         else
  1169.             z = x_sub(a, b);
  1170.     }
  1171.     return (PyObject *)z;
  1172. }
  1173.  
  1174. static PyObject *
  1175. long_mul(a, b)
  1176.     PyLongObject *a;
  1177.     PyLongObject *b;
  1178. {
  1179.     int size_a;
  1180.     int size_b;
  1181.     PyLongObject *z;
  1182.     int i;
  1183.     
  1184.     size_a = ABS(a->ob_size);
  1185.     size_b = ABS(b->ob_size);
  1186.     z = _PyLong_New(size_a + size_b);
  1187.     if (z == NULL)
  1188.         return NULL;
  1189.     for (i = 0; i < z->ob_size; ++i)
  1190.         z->ob_digit[i] = 0;
  1191.     for (i = 0; i < size_a; ++i) {
  1192.         twodigits carry = 0;
  1193.         twodigits f = a->ob_digit[i];
  1194.         int j;
  1195.         
  1196.         SIGCHECK({
  1197.             Py_DECREF(z);
  1198.             return NULL;
  1199.         })
  1200.         for (j = 0; j < size_b; ++j) {
  1201.             carry += z->ob_digit[i+j] + b->ob_digit[j] * f;
  1202.             z->ob_digit[i+j] = (digit) (carry & MASK);
  1203.             carry >>= SHIFT;
  1204.         }
  1205.         for (; carry != 0; ++j) {
  1206.             assert(i+j < z->ob_size);
  1207.             carry += z->ob_digit[i+j];
  1208.             z->ob_digit[i+j] = (digit) (carry & MASK);
  1209.             carry >>= SHIFT;
  1210.         }
  1211.     }
  1212.     if (a->ob_size < 0)
  1213.         z->ob_size = -(z->ob_size);
  1214.     if (b->ob_size < 0)
  1215.         z->ob_size = -(z->ob_size);
  1216.     return (PyObject *) long_normalize(z);
  1217. }
  1218.  
  1219. /* The / and % operators are now defined in terms of divmod().
  1220.    The expression a mod b has the value a - b*floor(a/b).
  1221.    The long_divrem function gives the remainder after division of
  1222.    |a| by |b|, with the sign of a.  This is also expressed
  1223.    as a - b*trunc(a/b), if trunc truncates towards zero.
  1224.    Some examples:
  1225.         a     b    a rem b        a mod b
  1226.         13     10     3         3
  1227.        -13     10    -3         7
  1228.         13    -10     3        -7
  1229.        -13    -10    -3        -3
  1230.    So, to get from rem to mod, we have to add b if a and b
  1231.    have different signs.  We then subtract one from the 'div'
  1232.    part of the outcome to keep the invariant intact. */
  1233.  
  1234. static int l_divmod Py_PROTO((PyLongObject *, PyLongObject *,
  1235.     PyLongObject **, PyLongObject **));
  1236. static int
  1237. l_divmod(v, w, pdiv, pmod)
  1238.     PyLongObject *v;
  1239.     PyLongObject *w;
  1240.     PyLongObject **pdiv;
  1241.     PyLongObject **pmod;
  1242. {
  1243.     PyLongObject *div, *mod;
  1244.     
  1245.     if (long_divrem(v, w, &div, &mod) < 0)
  1246.         return -1;
  1247.     if ((mod->ob_size < 0 && w->ob_size > 0) ||
  1248.         (mod->ob_size > 0 && w->ob_size < 0)) {
  1249.         PyLongObject *temp;
  1250.         PyLongObject *one;
  1251.         temp = (PyLongObject *) long_add(mod, w);
  1252.         Py_DECREF(mod);
  1253.         mod = temp;
  1254.         if (mod == NULL) {
  1255.             Py_DECREF(div);
  1256.             return -1;
  1257.         }
  1258.         one = (PyLongObject *) PyLong_FromLong(1L);
  1259.         if (one == NULL ||
  1260.             (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
  1261.             Py_DECREF(mod);
  1262.             Py_DECREF(div);
  1263.             Py_XDECREF(one);
  1264.             return -1;
  1265.         }
  1266.         Py_DECREF(one);
  1267.         Py_DECREF(div);
  1268.         div = temp;
  1269.     }
  1270.     *pdiv = div;
  1271.     *pmod = mod;
  1272.     return 0;
  1273. }
  1274.  
  1275. static PyObject *
  1276. long_div(v, w)
  1277.     PyLongObject *v;
  1278.     PyLongObject *w;
  1279. {
  1280.     PyLongObject *div, *mod;
  1281.     if (l_divmod(v, w, &div, &mod) < 0)
  1282.         return NULL;
  1283.     Py_DECREF(mod);
  1284.     return (PyObject *)div;
  1285. }
  1286.  
  1287. static PyObject *
  1288. long_mod(v, w)
  1289.     PyLongObject *v;
  1290.     PyLongObject *w;
  1291. {
  1292.     PyLongObject *div, *mod;
  1293.     if (l_divmod(v, w, &div, &mod) < 0)
  1294.         return NULL;
  1295.     Py_DECREF(div);
  1296.     return (PyObject *)mod;
  1297. }
  1298.  
  1299. static PyObject *
  1300. long_divmod(v, w)
  1301.     PyLongObject *v;
  1302.     PyLongObject *w;
  1303. {
  1304.     PyObject *z;
  1305.     PyLongObject *div, *mod;
  1306.     if (l_divmod(v, w, &div, &mod) < 0)
  1307.         return NULL;
  1308.     z = PyTuple_New(2);
  1309.     if (z != NULL) {
  1310.         PyTuple_SetItem(z, 0, (PyObject *) div);
  1311.         PyTuple_SetItem(z, 1, (PyObject *) mod);
  1312.     }
  1313.     else {
  1314.         Py_DECREF(div);
  1315.         Py_DECREF(mod);
  1316.     }
  1317.     return z;
  1318. }
  1319.  
  1320. static PyObject *
  1321. long_pow(a, b, c)
  1322.     PyLongObject *a;
  1323.     PyLongObject *b;
  1324.     PyLongObject *c;
  1325. {
  1326.     PyLongObject *z, *div, *mod;
  1327.     int size_b, i;
  1328.     
  1329.     size_b = b->ob_size;
  1330.     if (size_b < 0) {
  1331.         PyErr_SetString(PyExc_ValueError,
  1332.                 "long integer to the negative power");
  1333.         return NULL;
  1334.     }
  1335.     z = (PyLongObject *)PyLong_FromLong(1L);
  1336.     Py_INCREF(a);
  1337.     for (i = 0; i < size_b; ++i) {
  1338.         digit bi = b->ob_digit[i];
  1339.         int j;
  1340.     
  1341.         for (j = 0; j < SHIFT; ++j) {
  1342.             PyLongObject *temp;
  1343.         
  1344.             if (bi & 1) {
  1345.                 temp = (PyLongObject *)long_mul(z, a);
  1346.                 Py_DECREF(z);
  1347.                  if ((PyObject*)c!=Py_None && temp!=NULL) {
  1348.                      l_divmod(temp, c, &div, &mod);
  1349.                      Py_XDECREF(div);
  1350.                      Py_DECREF(temp);
  1351.                      temp = mod;
  1352.                 }
  1353.                  z = temp;
  1354.                 if (z == NULL)
  1355.                     break;
  1356.             }
  1357.             bi >>= 1;
  1358.             if (bi == 0 && i+1 == size_b)
  1359.                 break;
  1360.             temp = (PyLongObject *)long_mul(a, a);
  1361.             Py_DECREF(a);
  1362.              if ((PyObject*)c!=Py_None && temp!=NULL) {
  1363.                  l_divmod(temp, c, &div, &mod);
  1364.                  Py_XDECREF(div);
  1365.                  Py_DECREF(temp);
  1366.                  temp = mod;
  1367.             }
  1368.             a = temp;
  1369.             if (a == NULL) {
  1370.                 Py_DECREF(z);
  1371.                 z = NULL;
  1372.                 break;
  1373.             }
  1374.         }
  1375.         if (a == NULL || z == NULL)
  1376.             break;
  1377.     }
  1378.     Py_XDECREF(a);
  1379.     if ((PyObject*)c!=Py_None && z!=NULL) {
  1380.             l_divmod(z, c, &div, &mod);
  1381.             Py_XDECREF(div);
  1382.             Py_DECREF(z);
  1383.             z=mod;
  1384.     }
  1385.     return (PyObject *)z;
  1386. }
  1387.  
  1388. static PyObject *
  1389. long_invert(v)
  1390.     PyLongObject *v;
  1391. {
  1392.     /* Implement ~x as -(x+1) */
  1393.     PyLongObject *x;
  1394.     PyLongObject *w;
  1395.     w = (PyLongObject *)PyLong_FromLong(1L);
  1396.     if (w == NULL)
  1397.         return NULL;
  1398.     x = (PyLongObject *) long_add(v, w);
  1399.     Py_DECREF(w);
  1400.     if (x == NULL)
  1401.         return NULL;
  1402.     if (x->ob_size != 0)
  1403.         x->ob_size = -(x->ob_size);
  1404.     return (PyObject *)x;
  1405. }
  1406.  
  1407. static PyObject *
  1408. long_pos(v)
  1409.     PyLongObject *v;
  1410. {
  1411.     Py_INCREF(v);
  1412.     return (PyObject *)v;
  1413. }
  1414.  
  1415. static PyObject *
  1416. long_neg(v)
  1417.     PyLongObject *v;
  1418. {
  1419.     PyLongObject *z;
  1420.     int i, n;
  1421.     n = ABS(v->ob_size);
  1422.     if (n == 0) {
  1423.         /* -0 == 0 */
  1424.         Py_INCREF(v);
  1425.         return (PyObject *) v;
  1426.     }
  1427.     z = _PyLong_New(ABS(n));
  1428.     if (z == NULL)
  1429.         return NULL;
  1430.     for (i = 0; i < n; i++)
  1431.         z->ob_digit[i] = v->ob_digit[i];
  1432.     z->ob_size = -(v->ob_size);
  1433.     return (PyObject *)z;
  1434. }
  1435.  
  1436. static PyObject *
  1437. long_abs(v)
  1438.     PyLongObject *v;
  1439. {
  1440.     if (v->ob_size < 0)
  1441.         return long_neg(v);
  1442.     else {
  1443.         Py_INCREF(v);
  1444.         return (PyObject *)v;
  1445.     }
  1446. }
  1447.  
  1448. static int
  1449. long_nonzero(v)
  1450.     PyLongObject *v;
  1451. {
  1452.     return ABS(v->ob_size) != 0;
  1453. }
  1454.  
  1455. static PyObject *
  1456. long_rshift(a, b)
  1457.     PyLongObject *a;
  1458.     PyLongObject *b;
  1459. {
  1460.     PyLongObject *z;
  1461.     long shiftby;
  1462.     int newsize, wordshift, loshift, hishift, i, j;
  1463.     digit lomask, himask;
  1464.     
  1465.     if (a->ob_size < 0) {
  1466.         /* Right shifting negative numbers is harder */
  1467.         PyLongObject *a1, *a2, *a3;
  1468.         a1 = (PyLongObject *) long_invert(a);
  1469.         if (a1 == NULL) return NULL;
  1470.         a2 = (PyLongObject *) long_rshift(a1, b);
  1471.         Py_DECREF(a1);
  1472.         if (a2 == NULL) return NULL;
  1473.         a3 = (PyLongObject *) long_invert(a2);
  1474.         Py_DECREF(a2);
  1475.         return (PyObject *) a3;
  1476.     }
  1477.     
  1478.     shiftby = PyLong_AsLong((PyObject *)b);
  1479.     if (shiftby == -1L && PyErr_Occurred())
  1480.         return NULL;
  1481.     if (shiftby < 0) {
  1482.         PyErr_SetString(PyExc_ValueError, "negative shift count");
  1483.         return NULL;
  1484.     }
  1485.     wordshift = shiftby / SHIFT;
  1486.     newsize = ABS(a->ob_size) - wordshift;
  1487.     if (newsize <= 0) {
  1488.         z = _PyLong_New(0);
  1489.         return (PyObject *)z;
  1490.     }
  1491.     loshift = shiftby % SHIFT;
  1492.     hishift = SHIFT - loshift;
  1493.     lomask = ((digit)1 << hishift) - 1;
  1494.     himask = MASK ^ lomask;
  1495.     z = _PyLong_New(newsize);
  1496.     if (z == NULL)
  1497.         return NULL;
  1498.     if (a->ob_size < 0)
  1499.         z->ob_size = -(z->ob_size);
  1500.     for (i = 0, j = wordshift; i < newsize; i++, j++) {
  1501.         z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
  1502.         if (i+1 < newsize)
  1503.             z->ob_digit[i] |=
  1504.               (a->ob_digit[j+1] << hishift) & himask;
  1505.     }
  1506.     return (PyObject *) long_normalize(z);
  1507. }
  1508.  
  1509. static PyObject *
  1510. long_lshift(a, b)
  1511.     PyLongObject *a;
  1512.     PyLongObject *b;
  1513. {
  1514.     /* This version due to Tim Peters */
  1515.     PyLongObject *z;
  1516.     long shiftby;
  1517.     int oldsize, newsize, wordshift, remshift, i, j;
  1518.     twodigits accum;
  1519.     
  1520.     shiftby = PyLong_AsLong((PyObject *)b);
  1521.     if (shiftby == -1L && PyErr_Occurred())
  1522.         return NULL;
  1523.     if (shiftby < 0) {
  1524.         PyErr_SetString(PyExc_ValueError, "negative shift count");
  1525.         return NULL;
  1526.     }
  1527.     if ((long)(int)shiftby != shiftby) {
  1528.         PyErr_SetString(PyExc_ValueError,
  1529.                 "outrageous left shift count");
  1530.         return NULL;
  1531.     }
  1532.     /* wordshift, remshift = divmod(shiftby, SHIFT) */
  1533.     wordshift = (int)shiftby / SHIFT;
  1534.     remshift  = (int)shiftby - wordshift * SHIFT;
  1535.  
  1536.     oldsize = ABS(a->ob_size);
  1537.     newsize = oldsize + wordshift;
  1538.     if (remshift)
  1539.         ++newsize;
  1540.     z = _PyLong_New(newsize);
  1541.     if (z == NULL)
  1542.         return NULL;
  1543.     if (a->ob_size < 0)
  1544.         z->ob_size = -(z->ob_size);
  1545.     for (i = 0; i < wordshift; i++)
  1546.         z->ob_digit[i] = 0;
  1547.     accum = 0;    
  1548.     for (i = wordshift, j = 0; j < oldsize; i++, j++) {
  1549.         accum |= a->ob_digit[j] << remshift;
  1550.         z->ob_digit[i] = (digit)(accum & MASK);
  1551.         accum >>= SHIFT;
  1552.     }
  1553.     if (remshift)
  1554.         z->ob_digit[newsize-1] = (digit)accum;
  1555.     else    
  1556.         assert(!accum);
  1557.     return (PyObject *) long_normalize(z);
  1558. }
  1559.  
  1560.  
  1561. /* Bitwise and/xor/or operations */
  1562.  
  1563. #define MAX(x, y) ((x) < (y) ? (y) : (x))
  1564. #define MIN(x, y) ((x) > (y) ? (y) : (x))
  1565.  
  1566. static PyObject *long_bitwise Py_PROTO((PyLongObject *, int, PyLongObject *));
  1567. static PyObject *
  1568. long_bitwise(a, op, b)
  1569.     PyLongObject *a;
  1570.     int op; /* '&', '|', '^' */
  1571.     PyLongObject *b;
  1572. {
  1573.     digit maska, maskb; /* 0 or MASK */
  1574.     int negz;
  1575.     int size_a, size_b, size_z;
  1576.     PyLongObject *z;
  1577.     int i;
  1578.     digit diga, digb;
  1579.     PyObject *v;
  1580.     
  1581.     if (a->ob_size < 0) {
  1582.         a = (PyLongObject *) long_invert(a);
  1583.         maska = MASK;
  1584.     }
  1585.     else {
  1586.         Py_INCREF(a);
  1587.         maska = 0;
  1588.     }
  1589.     if (b->ob_size < 0) {
  1590.         b = (PyLongObject *) long_invert(b);
  1591.         maskb = MASK;
  1592.     }
  1593.     else {
  1594.         Py_INCREF(b);
  1595.         maskb = 0;
  1596.     }
  1597.     
  1598.     negz = 0;
  1599.     switch (op) {
  1600.     case '^':
  1601.         if (maska != maskb) {
  1602.             maska ^= MASK;
  1603.             negz = -1;
  1604.         }
  1605.         break;
  1606.     case '&':
  1607.         if (maska && maskb) {
  1608.             op = '|';
  1609.             maska ^= MASK;
  1610.             maskb ^= MASK;
  1611.             negz = -1;
  1612.         }
  1613.         break;
  1614.     case '|':
  1615.         if (maska || maskb) {
  1616.             op = '&';
  1617.             maska ^= MASK;
  1618.             maskb ^= MASK;
  1619.             negz = -1;
  1620.         }
  1621.         break;
  1622.     }
  1623.     
  1624.     /* JRH: The original logic here was to allocate the result value (z)
  1625.        as the longer of the two operands.  However, there are some cases
  1626.        where the result is guaranteed to be shorter than that: AND of two
  1627.        positives, OR of two negatives: use the shorter number.  AND with
  1628.        mixed signs: use the positive number.  OR with mixed signs: use the
  1629.        negative number.  After the transformations above, op will be '&'
  1630.        iff one of these cases applies, and mask will be non-0 for operands
  1631.        whose length should be ignored.
  1632.     */
  1633.  
  1634.     size_a = a->ob_size;
  1635.     size_b = b->ob_size;
  1636.     size_z = op == '&'
  1637.         ? (maska
  1638.            ? size_b
  1639.            : (maskb ? size_a : MIN(size_a, size_b)))
  1640.         : MAX(size_a, size_b);
  1641.     z = _PyLong_New(size_z);
  1642.     if (a == NULL || b == NULL || z == NULL) {
  1643.         Py_XDECREF(a);
  1644.         Py_XDECREF(b);
  1645.         Py_XDECREF(z);
  1646.         return NULL;
  1647.     }
  1648.     
  1649.     for (i = 0; i < size_z; ++i) {
  1650.         diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
  1651.         digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
  1652.         switch (op) {
  1653.         case '&': z->ob_digit[i] = diga & digb; break;
  1654.         case '|': z->ob_digit[i] = diga | digb; break;
  1655.         case '^': z->ob_digit[i] = diga ^ digb; break;
  1656.         }
  1657.     }
  1658.     
  1659.     Py_DECREF(a);
  1660.     Py_DECREF(b);
  1661.     z = long_normalize(z);
  1662.     if (negz == 0)
  1663.         return (PyObject *) z;
  1664.     v = long_invert(z);
  1665.     Py_DECREF(z);
  1666.     return v;
  1667. }
  1668.  
  1669. static PyObject *
  1670. long_and(a, b)
  1671.     PyLongObject *a;
  1672.     PyLongObject *b;
  1673. {
  1674.     return long_bitwise(a, '&', b);
  1675. }
  1676.  
  1677. static PyObject *
  1678. long_xor(a, b)
  1679.     PyLongObject *a;
  1680.     PyLongObject *b;
  1681. {
  1682.     return long_bitwise(a, '^', b);
  1683. }
  1684.  
  1685. static PyObject *
  1686. long_or(a, b)
  1687.     PyLongObject *a;
  1688.     PyLongObject *b;
  1689. {
  1690.     return long_bitwise(a, '|', b);
  1691. }
  1692.  
  1693. static int
  1694. long_coerce(pv, pw)
  1695.     PyObject **pv;
  1696.     PyObject **pw;
  1697. {
  1698.     if (PyInt_Check(*pw)) {
  1699.         *pw = PyLong_FromLong(PyInt_AsLong(*pw));
  1700.         Py_INCREF(*pv);
  1701.         return 0;
  1702.     }
  1703.     return 1; /* Can't do it */
  1704. }
  1705.  
  1706. static PyObject *
  1707. long_int(v)
  1708.     PyObject *v;
  1709. {
  1710.     long x;
  1711.     x = PyLong_AsLong(v);
  1712.     if (PyErr_Occurred())
  1713.         return NULL;
  1714.     return PyInt_FromLong(x);
  1715. }
  1716.  
  1717. static PyObject *
  1718. long_long(v)
  1719.     PyObject *v;
  1720. {
  1721.     Py_INCREF(v);
  1722.     return v;
  1723. }
  1724.  
  1725. static PyObject *
  1726. long_float(v)
  1727.     PyObject *v;
  1728. {
  1729.     double result;
  1730.     PyFPE_START_PROTECT("long_float", return 0)
  1731.     result = PyLong_AsDouble(v);
  1732.     PyFPE_END_PROTECT(result)
  1733.     return PyFloat_FromDouble(result);
  1734. }
  1735.  
  1736. static PyObject *
  1737. long_oct(v)
  1738.     PyObject *v;
  1739. {
  1740.     return long_format(v, 8);
  1741. }
  1742.  
  1743. static PyObject *
  1744. long_hex(v)
  1745.     PyObject *v;
  1746. {
  1747.     return long_format(v, 16);
  1748. }
  1749.  
  1750.  
  1751. #define UF (unaryfunc)
  1752. #define BF (binaryfunc)
  1753. #define TF (ternaryfunc)
  1754. #define IF (inquiry)
  1755.  
  1756. static PyNumberMethods long_as_number = {
  1757.     BF long_add,    /*nb_add*/
  1758.     BF long_sub,    /*nb_subtract*/
  1759.     BF long_mul,    /*nb_multiply*/
  1760.     BF long_div,    /*nb_divide*/
  1761.     BF long_mod,    /*nb_remainder*/
  1762.     BF long_divmod,    /*nb_divmod*/
  1763.     TF long_pow,    /*nb_power*/
  1764.     UF long_neg,    /*nb_negative*/
  1765.     UF long_pos,    /*tp_positive*/
  1766.     UF long_abs,    /*tp_absolute*/
  1767.     IF long_nonzero,/*tp_nonzero*/
  1768.     UF long_invert,    /*nb_invert*/
  1769.     BF long_lshift,    /*nb_lshift*/
  1770.     BF long_rshift,    /*nb_rshift*/
  1771.     BF long_and,    /*nb_and*/
  1772.     BF long_xor,    /*nb_xor*/
  1773.     BF long_or,    /*nb_or*/
  1774.     (int (*) Py_FPROTO((PyObject **, PyObject **)))
  1775.     (coercion)long_coerce, /*nb_coerce*/
  1776.     UF long_int,    /*nb_int*/
  1777.     UF long_long,    /*nb_long*/
  1778.     UF long_float,    /*nb_float*/
  1779.     UF long_oct,    /*nb_oct*/
  1780.     UF long_hex,    /*nb_hex*/
  1781. };
  1782.  
  1783. PyTypeObject PyLong_Type = {
  1784.     PyObject_HEAD_INIT(&PyType_Type)
  1785.     0,
  1786.     "long int",
  1787.     sizeof(PyLongObject) - sizeof(digit),
  1788.     sizeof(digit),
  1789.     (destructor)long_dealloc, /*tp_dealloc*/
  1790.     0,        /*tp_print*/
  1791.     0,        /*tp_getattr*/
  1792.     0,        /*tp_setattr*/
  1793.     (int (*) Py_FPROTO((PyObject *, PyObject *)))
  1794.     (cmpfunc)long_compare, /*tp_compare*/
  1795.     (reprfunc)long_repr, /*tp_repr*/
  1796.     &long_as_number,/*tp_as_number*/
  1797.     0,        /*tp_as_sequence*/
  1798.     0,        /*tp_as_mapping*/
  1799.     (long (*) Py_FPROTO((PyObject *)))
  1800.     (hashfunc)long_hash, /*tp_hash*/
  1801. };
  1802.