Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Objects/intobject.c

    r2 r388  
    44#include "Python.h"
    55#include <ctype.h>
     6#include <float.h>
    67
    78static PyObject *int_int(PyIntObject *v);
     
    1011PyInt_GetMax(void)
    1112{
    12         return LONG_MAX;        /* To initialize sys.maxint */
     13    return LONG_MAX;            /* To initialize sys.maxint */
    1314}
    1415
     
    3031*/
    3132
    32 #define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
    33 #define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
    34 #define N_INTOBJECTS    ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
     33#define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
     34#define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
     35#define N_INTOBJECTS    ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
    3536
    3637struct _intblock {
    37         struct _intblock *next;
    38         PyIntObject objects[N_INTOBJECTS];
     38    struct _intblock *next;
     39    PyIntObject objects[N_INTOBJECTS];
    3940};
    4041
     
    4748fill_free_list(void)
    4849{
    49         PyIntObject *p, *q;
    50         /* Python's object allocator isn't appropriate for large blocks. */
    51         p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
    52         if (p == NULL)
    53                 return (PyIntObject *) PyErr_NoMemory();
    54         ((PyIntBlock *)p)->next = block_list;
    55         block_list = (PyIntBlock *)p;
    56         /* Link the int objects together, from rear to front, then return
    57            the address of the last int object in the block. */
    58         p = &((PyIntBlock *)p)->objects[0];
    59         q = p + N_INTOBJECTS;
    60         while (--q > p)
    61                 Py_TYPE(q) = (struct _typeobject *)(q-1);
    62         Py_TYPE(q) = NULL;
    63         return p + N_INTOBJECTS - 1;
     50    PyIntObject *p, *q;
     51    /* Python's object allocator isn't appropriate for large blocks. */
     52    p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
     53    if (p == NULL)
     54        return (PyIntObject *) PyErr_NoMemory();
     55    ((PyIntBlock *)p)->next = block_list;
     56    block_list = (PyIntBlock *)p;
     57    /* Link the int objects together, from rear to front, then return
     58       the address of the last int object in the block. */
     59    p = &((PyIntBlock *)p)->objects[0];
     60    q = p + N_INTOBJECTS;
     61    while (--q > p)
     62        Py_TYPE(q) = (struct _typeobject *)(q-1);
     63    Py_TYPE(q) = NULL;
     64    return p + N_INTOBJECTS - 1;
    6465}
    6566
    6667#ifndef NSMALLPOSINTS
    67 #define NSMALLPOSINTS           257
     68#define NSMALLPOSINTS           257
    6869#endif
    6970#ifndef NSMALLNEGINTS
    70 #define NSMALLNEGINTS           5
     71#define NSMALLNEGINTS           5
    7172#endif
    7273#if NSMALLNEGINTS + NSMALLPOSINTS > 0
     
    7980#endif
    8081#ifdef COUNT_ALLOCS
    81 int quick_int_allocs, quick_neg_int_allocs;
     82Py_ssize_t quick_int_allocs;
     83Py_ssize_t quick_neg_int_allocs;
    8284#endif
    8385
     
    8587PyInt_FromLong(long ival)
    8688{
    87         register PyIntObject *v;
     89    register PyIntObject *v;
    8890#if NSMALLNEGINTS + NSMALLPOSINTS > 0
    89         if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
    90                 v = small_ints[ival + NSMALLNEGINTS];
    91                 Py_INCREF(v);
     91    if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
     92        v = small_ints[ival + NSMALLNEGINTS];
     93        Py_INCREF(v);
    9294#ifdef COUNT_ALLOCS
    93                 if (ival >= 0)
    94                         quick_int_allocs++;
    95                 else
    96                         quick_neg_int_allocs++;
    97 #endif
    98                 return (PyObject *) v;
    99         }
    100 #endif
    101         if (free_list == NULL) {
    102                 if ((free_list = fill_free_list()) == NULL)
    103                         return NULL;
    104         }
    105         /* Inline PyObject_New */
    106         v = free_list;
    107         free_list = (PyIntObject *)Py_TYPE(v);
    108         PyObject_INIT(v, &PyInt_Type);
    109         v->ob_ival = ival;
    110         return (PyObject *) v;
     95        if (ival >= 0)
     96            quick_int_allocs++;
     97        else
     98            quick_neg_int_allocs++;
     99#endif
     100        return (PyObject *) v;
     101    }
     102#endif
     103    if (free_list == NULL) {
     104        if ((free_list = fill_free_list()) == NULL)
     105            return NULL;
     106    }
     107    /* Inline PyObject_New */
     108    v = free_list;
     109    free_list = (PyIntObject *)Py_TYPE(v);
     110    PyObject_INIT(v, &PyInt_Type);
     111    v->ob_ival = ival;
     112    return (PyObject *) v;
    111113}
    112114
     
    114116PyInt_FromSize_t(size_t ival)
    115117{
    116         if (ival <= LONG_MAX)
    117                 return PyInt_FromLong((long)ival);
    118         return _PyLong_FromSize_t(ival);
     118    if (ival <= LONG_MAX)
     119        return PyInt_FromLong((long)ival);
     120    return _PyLong_FromSize_t(ival);
    119121}
    120122
     
    122124PyInt_FromSsize_t(Py_ssize_t ival)
    123125{
    124         if (ival >= LONG_MIN && ival <= LONG_MAX)
    125                 return PyInt_FromLong((long)ival);
    126         return _PyLong_FromSsize_t(ival);
     126    if (ival >= LONG_MIN && ival <= LONG_MAX)
     127        return PyInt_FromLong((long)ival);
     128    return _PyLong_FromSsize_t(ival);
    127129}
    128130
     
    130132int_dealloc(PyIntObject *v)
    131133{
    132         if (PyInt_CheckExact(v)) {
    133                 Py_TYPE(v) = (struct _typeobject *)free_list;
    134                 free_list = v;
    135         }
    136         else
    137                 Py_TYPE(v)->tp_free((PyObject *)v);
     134    if (PyInt_CheckExact(v)) {
     135        Py_TYPE(v) = (struct _typeobject *)free_list;
     136        free_list = v;
     137    }
     138    else
     139        Py_TYPE(v)->tp_free((PyObject *)v);
    138140}
    139141
     
    141143int_free(PyIntObject *v)
    142144{
    143         Py_TYPE(v) = (struct _typeobject *)free_list;
    144         free_list = v;
     145    Py_TYPE(v) = (struct _typeobject *)free_list;
     146    free_list = v;
    145147}
    146148
     
    148150PyInt_AsLong(register PyObject *op)
    149151{
    150         PyNumberMethods *nb;
    151         PyIntObject *io;
    152         long val;
    153 
    154         if (op && PyInt_Check(op))
    155                 return PyInt_AS_LONG((PyIntObject*) op);
    156 
    157         if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
    158             nb->nb_int == NULL) {
    159                 PyErr_SetString(PyExc_TypeError, "an integer is required");
    160                 return -1;
    161         }
    162 
    163         io = (PyIntObject*) (*nb->nb_int) (op);
    164         if (io == NULL)
    165                 return -1;
    166         if (!PyInt_Check(io)) {
    167                 if (PyLong_Check(io)) {
    168                         /* got a long? => retry int conversion */
    169                         val = PyLong_AsLong((PyObject *)io);
    170                         Py_DECREF(io);
    171                         if ((val == -1) && PyErr_Occurred())
    172                                 return -1;
    173                         return val;
    174                 }
    175                 else
    176                 {
    177                         Py_DECREF(io);
    178                         PyErr_SetString(PyExc_TypeError,
    179                                         "nb_int should return int object");
    180                         return -1;
    181                 }
    182         }
    183 
    184         val = PyInt_AS_LONG(io);
    185         Py_DECREF(io);
    186 
    187         return val;
     152    PyNumberMethods *nb;
     153    PyIntObject *io;
     154    long val;
     155
     156    if (op && PyInt_Check(op))
     157        return PyInt_AS_LONG((PyIntObject*) op);
     158
     159    if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
     160        nb->nb_int == NULL) {
     161        PyErr_SetString(PyExc_TypeError, "an integer is required");
     162        return -1;
     163    }
     164
     165    io = (PyIntObject*) (*nb->nb_int) (op);
     166    if (io == NULL)
     167        return -1;
     168    if (!PyInt_Check(io)) {
     169        if (PyLong_Check(io)) {
     170            /* got a long? => retry int conversion */
     171            val = PyLong_AsLong((PyObject *)io);
     172            Py_DECREF(io);
     173            if ((val == -1) && PyErr_Occurred())
     174                return -1;
     175            return val;
     176        }
     177        else
     178        {
     179            Py_DECREF(io);
     180            PyErr_SetString(PyExc_TypeError,
     181                        "__int__ method should return an integer");
     182            return -1;
     183        }
     184    }
     185
     186    val = PyInt_AS_LONG(io);
     187    Py_DECREF(io);
     188
     189    return val;
     190}
     191
     192int
     193_PyInt_AsInt(PyObject *obj)
     194{
     195    long result = PyInt_AsLong(obj);
     196    if (result == -1 && PyErr_Occurred())
     197        return -1;
     198    if (result > INT_MAX || result < INT_MIN) {
     199        PyErr_SetString(PyExc_OverflowError,
     200                        "Python int too large to convert to C int");
     201        return -1;
     202    }
     203    return (int)result;
    188204}
    189205
     
    192208{
    193209#if SIZEOF_SIZE_T != SIZEOF_LONG
    194         PyNumberMethods *nb;
    195         PyIntObject *io;
    196         Py_ssize_t val;
    197 #endif
    198 
    199         if (op == NULL) {
    200                 PyErr_SetString(PyExc_TypeError, "an integer is required");
    201                 return -1;
    202         }
    203 
    204         if (PyInt_Check(op))
    205                 return PyInt_AS_LONG((PyIntObject*) op);
    206         if (PyLong_Check(op))
    207                 return _PyLong_AsSsize_t(op);
     210    PyNumberMethods *nb;
     211    PyIntObject *io;
     212    Py_ssize_t val;
     213#endif
     214
     215    if (op == NULL) {
     216        PyErr_SetString(PyExc_TypeError, "an integer is required");
     217        return -1;
     218    }
     219
     220    if (PyInt_Check(op))
     221        return PyInt_AS_LONG((PyIntObject*) op);
     222    if (PyLong_Check(op))
     223        return _PyLong_AsSsize_t(op);
    208224#if SIZEOF_SIZE_T == SIZEOF_LONG
    209         return PyInt_AsLong(op);
     225    return PyInt_AsLong(op);
    210226#else
    211227
    212         if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
    213             (nb->nb_int == NULL && nb->nb_long == 0)) {
    214                 PyErr_SetString(PyExc_TypeError, "an integer is required");
    215                 return -1;
    216         }
    217 
    218         if (nb->nb_long != 0)
    219                 io = (PyIntObject*) (*nb->nb_long) (op);
    220         else
    221                 io = (PyIntObject*) (*nb->nb_int) (op);
    222         if (io == NULL)
    223                 return -1;
    224         if (!PyInt_Check(io)) {
    225                 if (PyLong_Check(io)) {
    226                         /* got a long? => retry int conversion */
    227                         val = _PyLong_AsSsize_t((PyObject *)io);
    228                         Py_DECREF(io);
    229                         if ((val == -1) && PyErr_Occurred())
    230                                 return -1;
    231                         return val;
    232                 }
    233                 else
    234                 {
    235                         Py_DECREF(io);
    236                         PyErr_SetString(PyExc_TypeError,
    237                                         "nb_int should return int object");
    238                         return -1;
    239                 }
    240         }
    241 
    242         val = PyInt_AS_LONG(io);
    243         Py_DECREF(io);
    244 
    245         return val;
     228    if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
     229        (nb->nb_int == NULL && nb->nb_long == 0)) {
     230        PyErr_SetString(PyExc_TypeError, "an integer is required");
     231        return -1;
     232    }
     233
     234    if (nb->nb_long != 0)
     235        io = (PyIntObject*) (*nb->nb_long) (op);
     236    else
     237        io = (PyIntObject*) (*nb->nb_int) (op);
     238    if (io == NULL)
     239        return -1;
     240    if (!PyInt_Check(io)) {
     241        if (PyLong_Check(io)) {
     242            /* got a long? => retry int conversion */
     243            val = _PyLong_AsSsize_t((PyObject *)io);
     244            Py_DECREF(io);
     245            if ((val == -1) && PyErr_Occurred())
     246                return -1;
     247            return val;
     248        }
     249        else
     250        {
     251            Py_DECREF(io);
     252            PyErr_SetString(PyExc_TypeError,
     253                        "__int__ method should return an integer");
     254            return -1;
     255        }
     256    }
     257
     258    val = PyInt_AS_LONG(io);
     259    Py_DECREF(io);
     260
     261    return val;
    246262#endif
    247263}
     
    250266PyInt_AsUnsignedLongMask(register PyObject *op)
    251267{
    252         PyNumberMethods *nb;
    253         PyIntObject *io;
    254         unsigned long val;
    255 
    256         if (op && PyInt_Check(op))
    257                 return PyInt_AS_LONG((PyIntObject*) op);
    258         if (op && PyLong_Check(op))
    259                 return PyLong_AsUnsignedLongMask(op);
    260 
    261         if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
    262             nb->nb_int == NULL) {
    263                 PyErr_SetString(PyExc_TypeError, "an integer is required");
    264                 return (unsigned long)-1;
    265         }
    266 
    267         io = (PyIntObject*) (*nb->nb_int) (op);
    268         if (io == NULL)
    269                 return (unsigned long)-1;
    270         if (!PyInt_Check(io)) {
    271                 if (PyLong_Check(io)) {
    272                         val = PyLong_AsUnsignedLongMask((PyObject *)io);
    273                         Py_DECREF(io);
    274                         if (PyErr_Occurred())
    275                                 return (unsigned long)-1;
    276                         return val;
    277                 }
    278                 else
    279                 {
    280                         Py_DECREF(io);
    281                         PyErr_SetString(PyExc_TypeError,
    282                                         "nb_int should return int object");
    283                         return (unsigned long)-1;
    284                 }
    285         }
    286 
    287         val = PyInt_AS_LONG(io);
    288         Py_DECREF(io);
    289 
    290         return val;
     268    PyNumberMethods *nb;
     269    PyIntObject *io;
     270    unsigned long val;
     271
     272    if (op && PyInt_Check(op))
     273        return PyInt_AS_LONG((PyIntObject*) op);
     274    if (op && PyLong_Check(op))
     275        return PyLong_AsUnsignedLongMask(op);
     276
     277    if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
     278        nb->nb_int == NULL) {
     279        PyErr_SetString(PyExc_TypeError, "an integer is required");
     280        return (unsigned long)-1;
     281    }
     282
     283    io = (PyIntObject*) (*nb->nb_int) (op);
     284    if (io == NULL)
     285        return (unsigned long)-1;
     286    if (!PyInt_Check(io)) {
     287        if (PyLong_Check(io)) {
     288            val = PyLong_AsUnsignedLongMask((PyObject *)io);
     289            Py_DECREF(io);
     290            if (PyErr_Occurred())
     291                return (unsigned long)-1;
     292            return val;
     293        }
     294        else
     295        {
     296            Py_DECREF(io);
     297            PyErr_SetString(PyExc_TypeError,
     298                        "__int__ method should return an integer");
     299            return (unsigned long)-1;
     300        }
     301    }
     302
     303    val = PyInt_AS_LONG(io);
     304    Py_DECREF(io);
     305
     306    return val;
    291307}
    292308
     
    295311PyInt_AsUnsignedLongLongMask(register PyObject *op)
    296312{
    297         PyNumberMethods *nb;
    298         PyIntObject *io;
    299         unsigned PY_LONG_LONG val;
    300 
    301         if (op && PyInt_Check(op))
    302                 return PyInt_AS_LONG((PyIntObject*) op);
    303         if (op && PyLong_Check(op))
    304                 return PyLong_AsUnsignedLongLongMask(op);
    305 
    306         if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
    307             nb->nb_int == NULL) {
    308                 PyErr_SetString(PyExc_TypeError, "an integer is required");
    309                 return (unsigned PY_LONG_LONG)-1;
    310         }
    311 
    312         io = (PyIntObject*) (*nb->nb_int) (op);
    313         if (io == NULL)
    314                 return (unsigned PY_LONG_LONG)-1;
    315         if (!PyInt_Check(io)) {
    316                 if (PyLong_Check(io)) {
    317                         val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
    318                         Py_DECREF(io);
    319                         if (PyErr_Occurred())
    320                                 return (unsigned PY_LONG_LONG)-1;
    321                         return val;
    322                 }
    323                 else
    324                 {
    325                         Py_DECREF(io);
    326                         PyErr_SetString(PyExc_TypeError,
    327                                         "nb_int should return int object");
    328                         return (unsigned PY_LONG_LONG)-1;
    329                 }
    330         }
    331 
    332         val = PyInt_AS_LONG(io);
    333         Py_DECREF(io);
    334 
    335         return val;
     313    PyNumberMethods *nb;
     314    PyIntObject *io;
     315    unsigned PY_LONG_LONG val;
     316
     317    if (op && PyInt_Check(op))
     318        return PyInt_AS_LONG((PyIntObject*) op);
     319    if (op && PyLong_Check(op))
     320        return PyLong_AsUnsignedLongLongMask(op);
     321
     322    if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
     323        nb->nb_int == NULL) {
     324        PyErr_SetString(PyExc_TypeError, "an integer is required");
     325        return (unsigned PY_LONG_LONG)-1;
     326    }
     327
     328    io = (PyIntObject*) (*nb->nb_int) (op);
     329    if (io == NULL)
     330        return (unsigned PY_LONG_LONG)-1;
     331    if (!PyInt_Check(io)) {
     332        if (PyLong_Check(io)) {
     333            val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
     334            Py_DECREF(io);
     335            if (PyErr_Occurred())
     336                return (unsigned PY_LONG_LONG)-1;
     337            return val;
     338        }
     339        else
     340        {
     341            Py_DECREF(io);
     342            PyErr_SetString(PyExc_TypeError,
     343                        "__int__ method should return an integer");
     344            return (unsigned PY_LONG_LONG)-1;
     345        }
     346    }
     347
     348    val = PyInt_AS_LONG(io);
     349    Py_DECREF(io);
     350
     351    return val;
    336352}
    337353#endif
     
    340356PyInt_FromString(char *s, char **pend, int base)
    341357{
    342         char *end;
    343         long x;
    344         Py_ssize_t slen;
    345         PyObject *sobj, *srepr;
    346 
    347         if ((base != 0 && base < 2) || base > 36) {
    348                 PyErr_SetString(PyExc_ValueError,
    349                                 "int() base must be >= 2 and <= 36");
    350                 return NULL;
    351         }
    352 
    353         while (*s && isspace(Py_CHARMASK(*s)))
    354                 s++;
    355         errno = 0;
    356         if (base == 0 && s[0] == '0') {
    357                 x = (long) PyOS_strtoul(s, &end, base);
    358                 if (x < 0)
    359                         return PyLong_FromString(s, pend, base);
    360         }
    361         else
    362                 x = PyOS_strtol(s, &end, base);
    363         if (end == s || !isalnum(Py_CHARMASK(end[-1])))
    364                 goto bad;
    365         while (*end && isspace(Py_CHARMASK(*end)))
    366                 end++;
    367         if (*end != '\0') {
     358    char *end;
     359    long x;
     360    Py_ssize_t slen;
     361    PyObject *sobj, *srepr;
     362
     363    if ((base != 0 && base < 2) || base > 36) {
     364        PyErr_SetString(PyExc_ValueError,
     365                        "int() base must be >= 2 and <= 36");
     366        return NULL;
     367    }
     368
     369    while (*s && isspace(Py_CHARMASK(*s)))
     370        s++;
     371    errno = 0;
     372    if (base == 0 && s[0] == '0') {
     373        x = (long) PyOS_strtoul(s, &end, base);
     374        if (x < 0)
     375            return PyLong_FromString(s, pend, base);
     376    }
     377    else
     378        x = PyOS_strtol(s, &end, base);
     379    if (end == s || !isalnum(Py_CHARMASK(end[-1])))
     380        goto bad;
     381    while (*end && isspace(Py_CHARMASK(*end)))
     382        end++;
     383    if (*end != '\0') {
    368384  bad:
    369                 slen = strlen(s) < 200 ? strlen(s) : 200;
    370                 sobj = PyString_FromStringAndSize(s, slen);
    371                 if (sobj == NULL)
    372                         return NULL;
    373                 srepr = PyObject_Repr(sobj);
    374                 Py_DECREF(sobj);
    375                 if (srepr == NULL)
    376                         return NULL;
    377                 PyErr_Format(PyExc_ValueError,
    378                              "invalid literal for int() with base %d: %s",
    379                              base, PyString_AS_STRING(srepr));
    380                 Py_DECREF(srepr);
    381                 return NULL;
    382         }
    383         else if (errno != 0)
    384                 return PyLong_FromString(s, pend, base);
    385         if (pend)
    386                 *pend = end;
    387         return PyInt_FromLong(x);
     385        slen = strlen(s) < 200 ? strlen(s) : 200;
     386        sobj = PyString_FromStringAndSize(s, slen);
     387        if (sobj == NULL)
     388            return NULL;
     389        srepr = PyObject_Repr(sobj);
     390        Py_DECREF(sobj);
     391        if (srepr == NULL)
     392            return NULL;
     393        PyErr_Format(PyExc_ValueError,
     394                     "invalid literal for int() with base %d: %s",
     395                     base, PyString_AS_STRING(srepr));
     396        Py_DECREF(srepr);
     397        return NULL;
     398    }
     399    else if (errno != 0)
     400        return PyLong_FromString(s, pend, base);
     401    if (pend)
     402        *pend = end;
     403    return PyInt_FromLong(x);
    388404}
    389405
     
    392408PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
    393409{
    394         PyObject *result;
    395         char *buffer = (char *)PyMem_MALLOC(length+1);
    396 
    397         if (buffer == NULL)
    398                 return PyErr_NoMemory();
    399 
    400         if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
    401                 PyMem_FREE(buffer);
    402                 return NULL;
    403         }
    404         result = PyInt_FromString(buffer, NULL, base);
    405         PyMem_FREE(buffer);
    406         return result;
     410    PyObject *result;
     411    char *buffer = (char *)PyMem_MALLOC(length+1);
     412
     413    if (buffer == NULL)
     414        return PyErr_NoMemory();
     415
     416    if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
     417        PyMem_FREE(buffer);
     418        return NULL;
     419    }
     420    result = PyInt_FromString(buffer, NULL, base);
     421    PyMem_FREE(buffer);
     422    return result;
    407423}
    408424#endif
     
    414430   integers. */
    415431
    416 #define CONVERT_TO_LONG(obj, lng)               \
    417         if (PyInt_Check(obj)) {                 \
    418                 lng = PyInt_AS_LONG(obj);       \
    419         }                                       \
    420         else {                                  \
    421                 Py_INCREF(Py_NotImplemented);   \
    422                 return Py_NotImplemented;       \
    423         }
     432#define CONVERT_TO_LONG(obj, lng)               \
     433    if (PyInt_Check(obj)) {                     \
     434        lng = PyInt_AS_LONG(obj);               \
     435    }                                           \
     436    else {                                      \
     437        Py_INCREF(Py_NotImplemented);           \
     438        return Py_NotImplemented;               \
     439    }
    424440
    425441/* ARGSUSED */
     
    428444     /* flags -- not used but required by interface */
    429445{
    430         long int_val = v->ob_ival;
    431         Py_BEGIN_ALLOW_THREADS
    432         fprintf(fp, "%ld", int_val);
    433         Py_END_ALLOW_THREADS
    434         return 0;
    435 }
    436 
    437 static PyObject *
    438 int_repr(PyIntObject *v)
    439 {
    440         return _PyInt_Format(v, 10, 0);
     446    long int_val = v->ob_ival;
     447    Py_BEGIN_ALLOW_THREADS
     448    fprintf(fp, "%ld", int_val);
     449    Py_END_ALLOW_THREADS
     450    return 0;
    441451}
    442452
     
    444454int_compare(PyIntObject *v, PyIntObject *w)
    445455{
    446         register long i = v->ob_ival;
    447         register long j = w->ob_ival;
    448         return (i < j) ? -1 : (i > j) ? 1 : 0;
     456    register long i = v->ob_ival;
     457    register long j = w->ob_ival;
     458    return (i < j) ? -1 : (i > j) ? 1 : 0;
    449459}
    450460
     
    452462int_hash(PyIntObject *v)
    453463{
    454         /* XXX If this is changed, you also need to change the way
    455            Python's long, float and complex types are hashed. */
    456         long x = v -> ob_ival;
    457         if (x == -1)
    458                 x = -2;
    459         return x;
     464    /* XXX If this is changed, you also need to change the way
     465       Python's long, float and complex types are hashed. */
     466    long x = v -> ob_ival;
     467    if (x == -1)
     468        x = -2;
     469    return x;
    460470}
    461471
     
    463473int_add(PyIntObject *v, PyIntObject *w)
    464474{
    465         register long a, b, x;
    466         CONVERT_TO_LONG(v, a);
    467         CONVERT_TO_LONG(w, b);
    468         /* casts in the line below avoid undefined behaviour on overflow */
    469         x = (long)((unsigned long)a + b);
    470         if ((x^a) >= 0 || (x^b) >= 0)
    471                 return PyInt_FromLong(x);
    472         return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
     475    register long a, b, x;
     476    CONVERT_TO_LONG(v, a);
     477    CONVERT_TO_LONG(w, b);
     478    /* casts in the line below avoid undefined behaviour on overflow */
     479    x = (long)((unsigned long)a + b);
     480    if ((x^a) >= 0 || (x^b) >= 0)
     481        return PyInt_FromLong(x);
     482    return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
    473483}
    474484
     
    476486int_sub(PyIntObject *v, PyIntObject *w)
    477487{
    478         register long a, b, x;
    479         CONVERT_TO_LONG(v, a);
    480         CONVERT_TO_LONG(w, b);
    481         /* casts in the line below avoid undefined behaviour on overflow */
    482         x = (long)((unsigned long)a - b);
    483         if ((x^a) >= 0 || (x^~b) >= 0)
    484                 return PyInt_FromLong(x);
    485         return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
    486                                                      (PyObject *)w);
     488    register long a, b, x;
     489    CONVERT_TO_LONG(v, a);
     490    CONVERT_TO_LONG(w, b);
     491    /* casts in the line below avoid undefined behaviour on overflow */
     492    x = (long)((unsigned long)a - b);
     493    if ((x^a) >= 0 || (x^~b) >= 0)
     494        return PyInt_FromLong(x);
     495    return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
     496                                                 (PyObject *)w);
    487497}
    488498
     
    516526int_mul(PyObject *v, PyObject *w)
    517527{
    518         long a, b;
    519         long longprod;                  /* a*b in native long arithmetic */
    520         double doubled_longprod;        /* (double)longprod */
    521         double doubleprod;              /* (double)a * (double)b */
    522 
    523         CONVERT_TO_LONG(v, a);
    524         CONVERT_TO_LONG(w, b);
    525         /* casts in the next line avoid undefined behaviour on overflow */
    526         longprod = (long)((unsigned long)a * b);
    527         doubleprod = (double)a * (double)b;
    528         doubled_longprod = (double)longprod;
    529 
    530         /* Fast path for normal case:  small multiplicands, and no info
    531            is lost in either method. */
    532         if (doubled_longprod == doubleprod)
    533                 return PyInt_FromLong(longprod);
    534 
    535         /* Somebody somewhere lost info.  Close enough, or way off?  Note
    536            that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
    537            The difference either is or isn't significant compared to the
    538            true value (of which doubleprod is a good approximation).
    539         */
    540         {
    541                 const double diff = doubled_longprod - doubleprod;
    542                 const double absdiff = diff >= 0.0 ? diff : -diff;
    543                 const double absprod = doubleprod >= 0.0 ? doubleprod :
    544                                                           -doubleprod;
    545                 /* absdiff/absprod <= 1/32 iff
    546                    32 * absdiff <= absprod -- 5 good bits is "close enough" */
    547                 if (32.0 * absdiff <= absprod)
    548                         return PyInt_FromLong(longprod);
    549                 else
    550                         return PyLong_Type.tp_as_number->nb_multiply(v, w);
    551         }
     528    long a, b;
     529    long longprod;                      /* a*b in native long arithmetic */
     530    double doubled_longprod;            /* (double)longprod */
     531    double doubleprod;                  /* (double)a * (double)b */
     532
     533    CONVERT_TO_LONG(v, a);
     534    CONVERT_TO_LONG(w, b);
     535    /* casts in the next line avoid undefined behaviour on overflow */
     536    longprod = (long)((unsigned long)a * b);
     537    doubleprod = (double)a * (double)b;
     538    doubled_longprod = (double)longprod;
     539
     540    /* Fast path for normal case:  small multiplicands, and no info
     541       is lost in either method. */
     542    if (doubled_longprod == doubleprod)
     543        return PyInt_FromLong(longprod);
     544
     545    /* Somebody somewhere lost info.  Close enough, or way off?  Note
     546       that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
     547       The difference either is or isn't significant compared to the
     548       true value (of which doubleprod is a good approximation).
     549    */
     550    {
     551        const double diff = doubled_longprod - doubleprod;
     552        const double absdiff = diff >= 0.0 ? diff : -diff;
     553        const double absprod = doubleprod >= 0.0 ? doubleprod :
     554                              -doubleprod;
     555        /* absdiff/absprod <= 1/32 iff
     556           32 * absdiff <= absprod -- 5 good bits is "close enough" */
     557        if (32.0 * absdiff <= absprod)
     558            return PyInt_FromLong(longprod);
     559        else
     560            return PyLong_Type.tp_as_number->nb_multiply(v, w);
     561    }
    552562}
    553563
     
    560570 * weird "0-".
    561571 */
    562 #define UNARY_NEG_WOULD_OVERFLOW(x)     \
    563         ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
     572#define UNARY_NEG_WOULD_OVERFLOW(x)     \
     573    ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
    564574
    565575/* Return type of i_divmod */
    566576enum divmod_result {
    567         DIVMOD_OK,              /* Correct result */
    568         DIVMOD_OVERFLOW,        /* Overflow, try again using longs */
    569         DIVMOD_ERROR            /* Exception raised */
     577    DIVMOD_OK,                  /* Correct result */
     578    DIVMOD_OVERFLOW,            /* Overflow, try again using longs */
     579    DIVMOD_ERROR                /* Exception raised */
    570580};
    571581
     
    574584         long *p_xdivy, long *p_xmody)
    575585{
    576         long xdivy, xmody;
    577 
    578         if (y == 0) {
    579                 PyErr_SetString(PyExc_ZeroDivisionError,
    580                                 "integer division or modulo by zero");
    581                 return DIVMOD_ERROR;
    582         }
    583         /* (-sys.maxint-1)/-1 is the only overflow case. */
    584         if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
    585                 return DIVMOD_OVERFLOW;
    586         xdivy = x / y;
    587         /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
    588         * for x and y with differing signs. (This is unusual
    589         * behaviour, and C99 prohibits it, but it's allowed by C89;
    590         * for an example of overflow, take x = LONG_MIN, y = 5 or x =
    591         * LONG_MAX, y = -5.)  However, x - xdivy*y is always
    592         * representable as a long, since it lies strictly between
    593         * -abs(y) and abs(y).  We add casts to avoid intermediate
    594         * overflow.
    595         */
    596         xmody = (long)(x - (unsigned long)xdivy * y);
    597         /* If the signs of x and y differ, and the remainder is non-0,
    598         * C89 doesn't define whether xdivy is now the floor or the
    599         * ceiling of the infinitely precise quotient.  We want the floor,
    600         * and we have it iff the remainder's sign matches y's.
    601         */
    602         if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
    603                 xmody += y;
    604                 --xdivy;
    605                 assert(xmody && ((y ^ xmody) >= 0));
    606         }
    607         *p_xdivy = xdivy;
    608         *p_xmody = xmody;
    609         return DIVMOD_OK;
     586    long xdivy, xmody;
     587
     588    if (y == 0) {
     589        PyErr_SetString(PyExc_ZeroDivisionError,
     590                        "integer division or modulo by zero");
     591        return DIVMOD_ERROR;
     592    }
     593    /* (-sys.maxint-1)/-1 is the only overflow case. */
     594    if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
     595        return DIVMOD_OVERFLOW;
     596    xdivy = x / y;
     597    /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
     598    * for x and y with differing signs. (This is unusual
     599    * behaviour, and C99 prohibits it, but it's allowed by C89;
     600    * for an example of overflow, take x = LONG_MIN, y = 5 or x =
     601    * LONG_MAX, y = -5.)  However, x - xdivy*y is always
     602    * representable as a long, since it lies strictly between
     603    * -abs(y) and abs(y).  We add casts to avoid intermediate
     604    * overflow.
     605    */
     606    xmody = (long)(x - (unsigned long)xdivy * y);
     607    /* If the signs of x and y differ, and the remainder is non-0,
     608    * C89 doesn't define whether xdivy is now the floor or the
     609    * ceiling of the infinitely precise quotient.  We want the floor,
     610    * and we have it iff the remainder's sign matches y's.
     611    */
     612    if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
     613        xmody += y;
     614        --xdivy;
     615        assert(xmody && ((y ^ xmody) >= 0));
     616    }
     617    *p_xdivy = xdivy;
     618    *p_xmody = xmody;
     619    return DIVMOD_OK;
    610620}
    611621
     
    613623int_div(PyIntObject *x, PyIntObject *y)
    614624{
    615         long xi, yi;
    616         long d, m;
    617         CONVERT_TO_LONG(x, xi);
    618         CONVERT_TO_LONG(y, yi);
    619         switch (i_divmod(xi, yi, &d, &m)) {
    620         case DIVMOD_OK:
    621                 return PyInt_FromLong(d);
    622         case DIVMOD_OVERFLOW:
    623                 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
    624                                                            (PyObject *)y);
    625         default:
    626                 return NULL;
    627         }
     625    long xi, yi;
     626    long d, m;
     627    CONVERT_TO_LONG(x, xi);
     628    CONVERT_TO_LONG(y, yi);
     629    switch (i_divmod(xi, yi, &d, &m)) {
     630    case DIVMOD_OK:
     631        return PyInt_FromLong(d);
     632    case DIVMOD_OVERFLOW:
     633        return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
     634                                                   (PyObject *)y);
     635    default:
     636        return NULL;
     637    }
    628638}
    629639
     
    631641int_classic_div(PyIntObject *x, PyIntObject *y)
    632642{
    633         long xi, yi;
    634         long d, m;
    635         CONVERT_TO_LONG(x, xi);
    636         CONVERT_TO_LONG(y, yi);
    637         if (Py_DivisionWarningFlag &&
    638             PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
    639                 return NULL;
    640         switch (i_divmod(xi, yi, &d, &m)) {
    641         case DIVMOD_OK:
    642                 return PyInt_FromLong(d);
    643         case DIVMOD_OVERFLOW:
    644                 return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
    645                                                            (PyObject *)y);
    646         default:
    647                 return NULL;
    648         }
    649 }
    650 
    651 static PyObject *
    652 int_true_divide(PyObject *v, PyObject *w)
    653 {
    654         /* If they aren't both ints, give someone else a chance.  In
    655            particular, this lets int/long get handled by longs, which
    656            underflows to 0 gracefully if the long is too big to convert
    657            to float. */
    658         if (PyInt_Check(v) && PyInt_Check(w))
    659                 return PyFloat_Type.tp_as_number->nb_true_divide(v, w);
    660         Py_INCREF(Py_NotImplemented);
    661         return Py_NotImplemented;
     643    long xi, yi;
     644    long d, m;
     645    CONVERT_TO_LONG(x, xi);
     646    CONVERT_TO_LONG(y, yi);
     647    if (Py_DivisionWarningFlag &&
     648        PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
     649        return NULL;
     650    switch (i_divmod(xi, yi, &d, &m)) {
     651    case DIVMOD_OK:
     652        return PyInt_FromLong(d);
     653    case DIVMOD_OVERFLOW:
     654        return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
     655                                                   (PyObject *)y);
     656    default:
     657        return NULL;
     658    }
     659}
     660
     661static PyObject *
     662int_true_divide(PyIntObject *x, PyIntObject *y)
     663{
     664    long xi, yi;
     665    /* If they aren't both ints, give someone else a chance.  In
     666       particular, this lets int/long get handled by longs, which
     667       underflows to 0 gracefully if the long is too big to convert
     668       to float. */
     669    CONVERT_TO_LONG(x, xi);
     670    CONVERT_TO_LONG(y, yi);
     671    if (yi == 0) {
     672        PyErr_SetString(PyExc_ZeroDivisionError,
     673                        "division by zero");
     674        return NULL;
     675    }
     676    if (xi == 0)
     677        return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
     678
     679#define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG)
     680#if DBL_MANT_DIG < WIDTH_OF_ULONG
     681    if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
     682        (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
     683        /* Large x or y.  Use long integer arithmetic. */
     684        return PyLong_Type.tp_as_number->nb_true_divide(
     685            (PyObject *)x, (PyObject *)y);
     686    else
     687#endif
     688        /* Both ints can be exactly represented as doubles.  Do a
     689           floating-point division. */
     690        return PyFloat_FromDouble((double)xi / (double)yi);
    662691}
    663692
     
    665694int_mod(PyIntObject *x, PyIntObject *y)
    666695{
    667         long xi, yi;
    668         long d, m;
    669         CONVERT_TO_LONG(x, xi);
    670         CONVERT_TO_LONG(y, yi);
    671         switch (i_divmod(xi, yi, &d, &m)) {
    672         case DIVMOD_OK:
    673                 return PyInt_FromLong(m);
    674         case DIVMOD_OVERFLOW:
    675                 return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
    676                                                               (PyObject *)y);
    677         default:
    678                 return NULL;
    679         }
     696    long xi, yi;
     697    long d, m;
     698    CONVERT_TO_LONG(x, xi);
     699    CONVERT_TO_LONG(y, yi);
     700    switch (i_divmod(xi, yi, &d, &m)) {
     701    case DIVMOD_OK:
     702        return PyInt_FromLong(m);
     703    case DIVMOD_OVERFLOW:
     704        return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
     705                                                      (PyObject *)y);
     706    default:
     707        return NULL;
     708    }
    680709}
    681710
     
    683712int_divmod(PyIntObject *x, PyIntObject *y)
    684713{
    685         long xi, yi;
    686         long d, m;
    687         CONVERT_TO_LONG(x, xi);
    688         CONVERT_TO_LONG(y, yi);
    689         switch (i_divmod(xi, yi, &d, &m)) {
    690         case DIVMOD_OK:
    691                 return Py_BuildValue("(ll)", d, m);
    692         case DIVMOD_OVERFLOW:
    693                 return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
    694                                                            (PyObject *)y);
    695         default:
    696                 return NULL;
    697         }
     714    long xi, yi;
     715    long d, m;
     716    CONVERT_TO_LONG(x, xi);
     717    CONVERT_TO_LONG(y, yi);
     718    switch (i_divmod(xi, yi, &d, &m)) {
     719    case DIVMOD_OK:
     720        return Py_BuildValue("(ll)", d, m);
     721    case DIVMOD_OVERFLOW:
     722        return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
     723                                                   (PyObject *)y);
     724    default:
     725        return NULL;
     726    }
    698727}
    699728
     
    701730int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
    702731{
    703         register long iv, iw, iz=0, ix, temp, prev;
    704         CONVERT_TO_LONG(v, iv);
    705         CONVERT_TO_LONG(w, iw);
    706         if (iw < 0) {
    707                 if ((PyObject *)z != Py_None) {
    708                         PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
    709                              "cannot be negative when 3rd argument specified");
    710                         return NULL;
    711                 }
    712                 /* Return a float.  This works because we know that
    713                    this calls float_pow() which converts its
    714                    arguments to double. */
    715                 return PyFloat_Type.tp_as_number->nb_power(
    716                         (PyObject *)v, (PyObject *)w, (PyObject *)z);
    717         }
    718         if ((PyObject *)z != Py_None) {
    719                 CONVERT_TO_LONG(z, iz);
    720                 if (iz == 0) {
    721                         PyErr_SetString(PyExc_ValueError,
    722                                         "pow() 3rd argument cannot be 0");
    723                         return NULL;
    724                 }
    725         }
    726         /*
    727          * XXX: The original exponentiation code stopped looping
    728          * when temp hit zero; this code will continue onwards
    729          * unnecessarily, but at least it won't cause any errors.
    730          * Hopefully the speed improvement from the fast exponentiation
    731          * will compensate for the slight inefficiency.
    732          * XXX: Better handling of overflows is desperately needed.
    733          */
    734         temp = iv;
    735         ix = 1;
    736         while (iw > 0) {
    737                 prev = ix;      /* Save value for overflow check */
    738                 if (iw & 1) {
    739                         ix = ix*temp;
    740                         if (temp == 0)
    741                                 break; /* Avoid ix / 0 */
    742                         if (ix / temp != prev) {
    743                                 return PyLong_Type.tp_as_number->nb_power(
    744                                         (PyObject *)v,
    745                                         (PyObject *)w,
    746                                         (PyObject *)z);
    747                         }
    748                 }
    749                 iw >>= 1;       /* Shift exponent down by 1 bit */
    750                 if (iw==0) break;
    751                 prev = temp;
    752                 temp *= temp;   /* Square the value of temp */
    753                 if (prev != 0 && temp / prev != prev) {
    754                         return PyLong_Type.tp_as_number->nb_power(
    755                                 (PyObject *)v, (PyObject *)w, (PyObject *)z);
    756                 }
    757                 if (iz) {
    758                         /* If we did a multiplication, perform a modulo */
    759                         ix = ix % iz;
    760                         temp = temp % iz;
    761                 }
    762         }
    763         if (iz) {
    764                 long div, mod;
    765                 switch (i_divmod(ix, iz, &div, &mod)) {
    766                 case DIVMOD_OK:
    767                         ix = mod;
    768                         break;
    769                 case DIVMOD_OVERFLOW:
    770                         return PyLong_Type.tp_as_number->nb_power(
    771                                 (PyObject *)v, (PyObject *)w, (PyObject *)z);
    772                 default:
    773                         return NULL;
    774                 }
    775         }
    776         return PyInt_FromLong(ix);
     732    register long iv, iw, iz=0, ix, temp, prev;
     733    CONVERT_TO_LONG(v, iv);
     734    CONVERT_TO_LONG(w, iw);
     735    if (iw < 0) {
     736        if ((PyObject *)z != Py_None) {
     737            PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
     738                 "cannot be negative when 3rd argument specified");
     739            return NULL;
     740        }
     741        /* Return a float.  This works because we know that
     742           this calls float_pow() which converts its
     743           arguments to double. */
     744        return PyFloat_Type.tp_as_number->nb_power(
     745            (PyObject *)v, (PyObject *)w, (PyObject *)z);
     746    }
     747    if ((PyObject *)z != Py_None) {
     748        CONVERT_TO_LONG(z, iz);
     749        if (iz == 0) {
     750            PyErr_SetString(PyExc_ValueError,
     751                            "pow() 3rd argument cannot be 0");
     752            return NULL;
     753        }
     754    }
     755    /*
     756     * XXX: The original exponentiation code stopped looping
     757     * when temp hit zero; this code will continue onwards
     758     * unnecessarily, but at least it won't cause any errors.
     759     * Hopefully the speed improvement from the fast exponentiation
     760     * will compensate for the slight inefficiency.
     761     * XXX: Better handling of overflows is desperately needed.
     762     */
     763    temp = iv;
     764    ix = 1;
     765    while (iw > 0) {
     766        prev = ix;              /* Save value for overflow check */
     767        if (iw & 1) {
     768            /*
     769             * The (unsigned long) cast below ensures that the multiplication
     770             * is interpreted as an unsigned operation rather than a signed one
     771             * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour
     772             * from signed arithmetic overflow (C99 6.5p5).  See issue #12973.
     773             */
     774            ix = (unsigned long)ix * temp;
     775            if (temp == 0)
     776                break; /* Avoid ix / 0 */
     777            if (ix / temp != prev) {
     778                return PyLong_Type.tp_as_number->nb_power(
     779                    (PyObject *)v,
     780                    (PyObject *)w,
     781                    (PyObject *)z);
     782            }
     783        }
     784        iw >>= 1;               /* Shift exponent down by 1 bit */
     785        if (iw==0) break;
     786        prev = temp;
     787        temp = (unsigned long)temp * temp;  /* Square the value of temp */
     788        if (prev != 0 && temp / prev != prev) {
     789            return PyLong_Type.tp_as_number->nb_power(
     790                (PyObject *)v, (PyObject *)w, (PyObject *)z);
     791        }
     792        if (iz) {
     793            /* If we did a multiplication, perform a modulo */
     794            ix = ix % iz;
     795            temp = temp % iz;
     796        }
     797    }
     798    if (iz) {
     799        long div, mod;
     800        switch (i_divmod(ix, iz, &div, &mod)) {
     801        case DIVMOD_OK:
     802            ix = mod;
     803            break;
     804        case DIVMOD_OVERFLOW:
     805            return PyLong_Type.tp_as_number->nb_power(
     806                (PyObject *)v, (PyObject *)w, (PyObject *)z);
     807        default:
     808            return NULL;
     809        }
     810    }
     811    return PyInt_FromLong(ix);
    777812}
    778813
     
    780815int_neg(PyIntObject *v)
    781816{
    782         register long a;
    783         a = v->ob_ival;
    784         /* check for overflow */
    785         if (UNARY_NEG_WOULD_OVERFLOW(a)) {
    786                 PyObject *o = PyLong_FromLong(a);
    787                 if (o != NULL) {
    788                         PyObject *result = PyNumber_Negative(o);
    789                         Py_DECREF(o);
    790                         return result;
    791                 }
    792                 return NULL;
    793         }
    794         return PyInt_FromLong(-a);
     817    register long a;
     818    a = v->ob_ival;
     819    /* check for overflow */
     820    if (UNARY_NEG_WOULD_OVERFLOW(a)) {
     821        PyObject *o = PyLong_FromLong(a);
     822        if (o != NULL) {
     823            PyObject *result = PyNumber_Negative(o);
     824            Py_DECREF(o);
     825            return result;
     826        }
     827        return NULL;
     828    }
     829    return PyInt_FromLong(-a);
    795830}
    796831
     
    798833int_abs(PyIntObject *v)
    799834{
    800         if (v->ob_ival >= 0)
    801                 return int_int(v);
    802         else
    803                 return int_neg(v);
     835    if (v->ob_ival >= 0)
     836        return int_int(v);
     837    else
     838        return int_neg(v);
    804839}
    805840
     
    807842int_nonzero(PyIntObject *v)
    808843{
    809         return v->ob_ival != 0;
     844    return v->ob_ival != 0;
    810845}
    811846
     
    813848int_invert(PyIntObject *v)
    814849{
    815         return PyInt_FromLong(~v->ob_ival);
     850    return PyInt_FromLong(~v->ob_ival);
    816851}
    817852
     
    819854int_lshift(PyIntObject *v, PyIntObject *w)
    820855{
    821         long a, b, c;
    822         PyObject *vv, *ww, *result;
    823 
    824         CONVERT_TO_LONG(v, a);
    825         CONVERT_TO_LONG(w, b);
    826         if (b < 0) {
    827                 PyErr_SetString(PyExc_ValueError, "negative shift count");
    828                 return NULL;
    829         }
    830         if (a == 0 || b == 0)
    831                 return int_int(v);
    832         if (b >= LONG_BIT) {
    833                 vv = PyLong_FromLong(PyInt_AS_LONG(v));
    834                 if (vv == NULL)
    835                         return NULL;
    836                 ww = PyLong_FromLong(PyInt_AS_LONG(w));
    837                 if (ww == NULL) {
    838                         Py_DECREF(vv);
    839                         return NULL;
    840                 }
    841                 result = PyNumber_Lshift(vv, ww);
    842                 Py_DECREF(vv);
    843                 Py_DECREF(ww);
    844                 return result;
    845         }
    846         c = a << b;
    847         if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
    848                 vv = PyLong_FromLong(PyInt_AS_LONG(v));
    849                 if (vv == NULL)
    850                         return NULL;
    851                 ww = PyLong_FromLong(PyInt_AS_LONG(w));
    852                 if (ww == NULL) {
    853                         Py_DECREF(vv);
    854                         return NULL;
    855                 }
    856                 result = PyNumber_Lshift(vv, ww);
    857                 Py_DECREF(vv);
    858                 Py_DECREF(ww);
    859                 return result;
    860         }
    861         return PyInt_FromLong(c);
     856    long a, b, c;
     857    PyObject *vv, *ww, *result;
     858
     859    CONVERT_TO_LONG(v, a);
     860    CONVERT_TO_LONG(w, b);
     861    if (b < 0) {
     862        PyErr_SetString(PyExc_ValueError, "negative shift count");
     863        return NULL;
     864    }
     865    if (a == 0 || b == 0)
     866        return int_int(v);
     867    if (b >= LONG_BIT) {
     868        vv = PyLong_FromLong(PyInt_AS_LONG(v));
     869        if (vv == NULL)
     870            return NULL;
     871        ww = PyLong_FromLong(PyInt_AS_LONG(w));
     872        if (ww == NULL) {
     873            Py_DECREF(vv);
     874            return NULL;
     875        }
     876        result = PyNumber_Lshift(vv, ww);
     877        Py_DECREF(vv);
     878        Py_DECREF(ww);
     879        return result;
     880    }
     881    c = a << b;
     882    if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
     883        vv = PyLong_FromLong(PyInt_AS_LONG(v));
     884        if (vv == NULL)
     885            return NULL;
     886        ww = PyLong_FromLong(PyInt_AS_LONG(w));
     887        if (ww == NULL) {
     888            Py_DECREF(vv);
     889            return NULL;
     890        }
     891        result = PyNumber_Lshift(vv, ww);
     892        Py_DECREF(vv);
     893        Py_DECREF(ww);
     894        return result;
     895    }
     896    return PyInt_FromLong(c);
    862897}
    863898
     
    865900int_rshift(PyIntObject *v, PyIntObject *w)
    866901{
    867         register long a, b;
    868         CONVERT_TO_LONG(v, a);
    869         CONVERT_TO_LONG(w, b);
    870         if (b < 0) {
    871                 PyErr_SetString(PyExc_ValueError, "negative shift count");
    872                 return NULL;
    873         }
    874         if (a == 0 || b == 0)
    875                 return int_int(v);
    876         if (b >= LONG_BIT) {
    877                 if (a < 0)
    878                         a = -1;
    879                 else
    880                         a = 0;
    881         }
    882         else {
    883                 a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
    884         }
    885         return PyInt_FromLong(a);
     902    register long a, b;
     903    CONVERT_TO_LONG(v, a);
     904    CONVERT_TO_LONG(w, b);
     905    if (b < 0) {
     906        PyErr_SetString(PyExc_ValueError, "negative shift count");
     907        return NULL;
     908    }
     909    if (a == 0 || b == 0)
     910        return int_int(v);
     911    if (b >= LONG_BIT) {
     912        if (a < 0)
     913            a = -1;
     914        else
     915            a = 0;
     916    }
     917    else {
     918        a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
     919    }
     920    return PyInt_FromLong(a);
    886921}
    887922
     
    889924int_and(PyIntObject *v, PyIntObject *w)
    890925{
    891         register long a, b;
    892         CONVERT_TO_LONG(v, a);
    893         CONVERT_TO_LONG(w, b);
    894         return PyInt_FromLong(a & b);
     926    register long a, b;
     927    CONVERT_TO_LONG(v, a);
     928    CONVERT_TO_LONG(w, b);
     929    return PyInt_FromLong(a & b);
    895930}
    896931
     
    898933int_xor(PyIntObject *v, PyIntObject *w)
    899934{
    900         register long a, b;
    901         CONVERT_TO_LONG(v, a);
    902         CONVERT_TO_LONG(w, b);
    903         return PyInt_FromLong(a ^ b);
     935    register long a, b;
     936    CONVERT_TO_LONG(v, a);
     937    CONVERT_TO_LONG(w, b);
     938    return PyInt_FromLong(a ^ b);
    904939}
    905940
     
    907942int_or(PyIntObject *v, PyIntObject *w)
    908943{
    909         register long a, b;
    910         CONVERT_TO_LONG(v, a);
    911         CONVERT_TO_LONG(w, b);
    912         return PyInt_FromLong(a | b);
     944    register long a, b;
     945    CONVERT_TO_LONG(v, a);
     946    CONVERT_TO_LONG(w, b);
     947    return PyInt_FromLong(a | b);
    913948}
    914949
     
    916951int_coerce(PyObject **pv, PyObject **pw)
    917952{
    918         if (PyInt_Check(*pw)) {
    919                 Py_INCREF(*pv);
    920                 Py_INCREF(*pw);
    921                 return 0;
    922         }
    923         return 1; /* Can't do it */
     953    if (PyInt_Check(*pw)) {
     954        Py_INCREF(*pv);
     955        Py_INCREF(*pw);
     956        return 0;
     957    }
     958    return 1; /* Can't do it */
    924959}
    925960
     
    927962int_int(PyIntObject *v)
    928963{
    929         if (PyInt_CheckExact(v))
    930                 Py_INCREF(v);
    931         else
    932                 v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
    933         return (PyObject *)v;
     964    if (PyInt_CheckExact(v))
     965        Py_INCREF(v);
     966    else
     967        v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
     968    return (PyObject *)v;
    934969}
    935970
     
    937972int_long(PyIntObject *v)
    938973{
    939         return PyLong_FromLong((v -> ob_ival));
    940 }
     974    return PyLong_FromLong((v -> ob_ival));
     975}
     976
     977static const unsigned char BitLengthTable[32] = {
     978    0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
     979    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
     980};
     981
     982static int
     983bits_in_ulong(unsigned long d)
     984{
     985    int d_bits = 0;
     986    while (d >= 32) {
     987        d_bits += 6;
     988        d >>= 6;
     989    }
     990    d_bits += (int)BitLengthTable[d];
     991    return d_bits;
     992}
     993
     994#if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG
     995/* Every Python int can be exactly represented as a float. */
    941996
    942997static PyObject *
    943998int_float(PyIntObject *v)
    944999{
    945         return PyFloat_FromDouble((double)(v -> ob_ival));
    946 }
     1000    return PyFloat_FromDouble((double)(v -> ob_ival));
     1001}
     1002
     1003#else
     1004/* Here not all Python ints are exactly representable as floats, so we may
     1005   have to round.  We do this manually, since the C standards don't specify
     1006   whether converting an integer to a float rounds up or down */
     1007
     1008static PyObject *
     1009int_float(PyIntObject *v)
     1010{
     1011    unsigned long abs_ival, lsb;
     1012    int round_up;
     1013
     1014    if (v->ob_ival < 0)
     1015        abs_ival = 0U-(unsigned long)v->ob_ival;
     1016    else
     1017        abs_ival = (unsigned long)v->ob_ival;
     1018    if (abs_ival < (1L << DBL_MANT_DIG))
     1019        /* small integer;  no need to round */
     1020        return PyFloat_FromDouble((double)v->ob_ival);
     1021
     1022    /* Round abs_ival to MANT_DIG significant bits, using the
     1023       round-half-to-even rule.  abs_ival & lsb picks out the 'rounding'
     1024       bit: the first bit after the most significant MANT_DIG bits of
     1025       abs_ival.  We round up if this bit is set, provided that either:
     1026
     1027         (1) abs_ival isn't exactly halfway between two floats, in which
     1028         case at least one of the bits following the rounding bit must be
     1029         set; i.e., abs_ival & lsb-1 != 0, or:
     1030
     1031         (2) the resulting rounded value has least significant bit 0; or
     1032         in other words the bit above the rounding bit is set (this is the
     1033         'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
     1034
     1035       The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
     1036
     1037    lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
     1038    round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
     1039    abs_ival &= -2*lsb;
     1040    if (round_up)
     1041        abs_ival += 2*lsb;
     1042    return PyFloat_FromDouble(v->ob_ival < 0 ?
     1043                              -(double)abs_ival :
     1044                  (double)abs_ival);
     1045}
     1046
     1047#endif
    9471048
    9481049static PyObject *
    9491050int_oct(PyIntObject *v)
    9501051{
    951         return _PyInt_Format(v, 8, 0);
     1052    return _PyInt_Format(v, 8, 0);
    9521053}
    9531054
     
    9551056int_hex(PyIntObject *v)
    9561057{
    957         return _PyInt_Format(v, 16, 0);
     1058    return _PyInt_Format(v, 16, 0);
    9581059}
    9591060
     
    9641065int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    9651066{
    966         PyObject *x = NULL;
    967         int base = -909;
    968         static char *kwlist[] = {"x", "base", 0};
    969 
    970         if (type != &PyInt_Type)
    971                 return int_subtype_new(type, args, kwds); /* Wimp out */
    972         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
    973                                          &x, &base))
    974                 return NULL;
    975         if (x == NULL)
    976                 return PyInt_FromLong(0L);
    977         if (base == -909)
    978                 return PyNumber_Int(x);
    979         if (PyString_Check(x)) {
    980                 /* Since PyInt_FromString doesn't have a length parameter,
    981                  * check here for possible NULs in the string. */
    982                 char *string = PyString_AS_STRING(x);
    983                 if (strlen(string) != PyString_Size(x)) {
    984                         /* create a repr() of the input string,
    985                          * just like PyInt_FromString does */
    986                         PyObject *srepr;
    987                         srepr = PyObject_Repr(x);
    988                         if (srepr == NULL)
    989                                 return NULL;
    990                         PyErr_Format(PyExc_ValueError,
    991                              "invalid literal for int() with base %d: %s",
    992                              base, PyString_AS_STRING(srepr));
    993                         Py_DECREF(srepr);
    994                         return NULL;
    995                 }
    996                 return PyInt_FromString(string, NULL, base);
    997         }
     1067    PyObject *x = NULL;
     1068    int base = -909;
     1069    static char *kwlist[] = {"x", "base", 0};
     1070
     1071    if (type != &PyInt_Type)
     1072        return int_subtype_new(type, args, kwds); /* Wimp out */
     1073    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
     1074                                     &x, &base))
     1075        return NULL;
     1076    if (x == NULL) {
     1077        if (base != -909) {
     1078            PyErr_SetString(PyExc_TypeError,
     1079                            "int() missing string argument");
     1080            return NULL;
     1081        }
     1082        return PyInt_FromLong(0L);
     1083    }
     1084    if (base == -909)
     1085        return PyNumber_Int(x);
     1086    if (PyString_Check(x)) {
     1087        /* Since PyInt_FromString doesn't have a length parameter,
     1088         * check here for possible NULs in the string. */
     1089        char *string = PyString_AS_STRING(x);
     1090        if (strlen(string) != PyString_Size(x)) {
     1091            /* create a repr() of the input string,
     1092             * just like PyInt_FromString does */
     1093            PyObject *srepr;
     1094            srepr = PyObject_Repr(x);
     1095            if (srepr == NULL)
     1096                return NULL;
     1097            PyErr_Format(PyExc_ValueError,
     1098                 "invalid literal for int() with base %d: %s",
     1099                 base, PyString_AS_STRING(srepr));
     1100            Py_DECREF(srepr);
     1101            return NULL;
     1102        }
     1103        return PyInt_FromString(string, NULL, base);
     1104    }
    9981105#ifdef Py_USING_UNICODE
    999         if (PyUnicode_Check(x))
    1000                 return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
    1001                                         PyUnicode_GET_SIZE(x),
    1002                                         base);
    1003 #endif
    1004         PyErr_SetString(PyExc_TypeError,
    1005                         "int() can't convert non-string with explicit base");
    1006         return NULL;
     1106    if (PyUnicode_Check(x))
     1107        return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
     1108                                PyUnicode_GET_SIZE(x),
     1109                                base);
     1110#endif
     1111    PyErr_SetString(PyExc_TypeError,
     1112                    "int() can't convert non-string with explicit base");
     1113    return NULL;
    10071114}
    10081115
     
    10151122int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    10161123{
    1017         PyObject *tmp, *newobj;
    1018         long ival;
    1019 
    1020         assert(PyType_IsSubtype(type, &PyInt_Type));
    1021         tmp = int_new(&PyInt_Type, args, kwds);
    1022         if (tmp == NULL)
    1023                 return NULL;
    1024         if (!PyInt_Check(tmp)) {
    1025                 ival = PyLong_AsLong(tmp);
    1026                 if (ival == -1 && PyErr_Occurred()) {
    1027                         Py_DECREF(tmp);
    1028                         return NULL;
    1029                 }
    1030         } else {
    1031                 ival = ((PyIntObject *)tmp)->ob_ival;
    1032         }
    1033 
    1034         newobj = type->tp_alloc(type, 0);
    1035         if (newobj == NULL) {
    1036                 Py_DECREF(tmp);
    1037                 return NULL;
    1038         }
    1039         ((PyIntObject *)newobj)->ob_ival = ival;
    1040         Py_DECREF(tmp);
    1041         return newobj;
     1124    PyObject *tmp, *newobj;
     1125    long ival;
     1126
     1127    assert(PyType_IsSubtype(type, &PyInt_Type));
     1128    tmp = int_new(&PyInt_Type, args, kwds);
     1129    if (tmp == NULL)
     1130        return NULL;
     1131    if (!PyInt_Check(tmp)) {
     1132        ival = PyLong_AsLong(tmp);
     1133        if (ival == -1 && PyErr_Occurred()) {
     1134            Py_DECREF(tmp);
     1135            return NULL;
     1136        }
     1137    } else {
     1138        ival = ((PyIntObject *)tmp)->ob_ival;
     1139    }
     1140
     1141    newobj = type->tp_alloc(type, 0);
     1142    if (newobj == NULL) {
     1143        Py_DECREF(tmp);
     1144        return NULL;
     1145    }
     1146    ((PyIntObject *)newobj)->ob_ival = ival;
     1147    Py_DECREF(tmp);
     1148    return newobj;
    10421149}
    10431150
     
    10451152int_getnewargs(PyIntObject *v)
    10461153{
    1047         return Py_BuildValue("(l)", v->ob_ival);
    1048 }
    1049 
    1050 static PyObject *
    1051 int_getN(PyIntObject *v, void *context) {
    1052         return PyInt_FromLong((Py_intptr_t)context);
     1154    return Py_BuildValue("(l)", v->ob_ival);
     1155}
     1156
     1157static PyObject *
     1158int_get0(PyIntObject *v, void *context) {
     1159    return PyInt_FromLong(0L);
     1160}
     1161
     1162static PyObject *
     1163int_get1(PyIntObject *v, void *context) {
     1164    return PyInt_FromLong(1L);
     1165}
     1166
     1167/* Convert an integer to a decimal string.  On many platforms, this
     1168   will be significantly faster than the general arbitrary-base
     1169   conversion machinery in _PyInt_Format, thanks to optimization
     1170   opportunities offered by division by a compile-time constant. */
     1171static PyObject *
     1172int_to_decimal_string(PyIntObject *v) {
     1173    char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
     1174    long n = v->ob_ival;
     1175    unsigned long absn;
     1176    p = bufend = buf + sizeof(buf);
     1177    absn = n < 0 ? 0UL - n : n;
     1178    do {
     1179        *--p = '0' + (char)(absn % 10);
     1180        absn /= 10;
     1181    } while (absn);
     1182    if (n < 0)
     1183        *--p = '-';
     1184    return PyString_FromStringAndSize(p, bufend - p);
    10531185}
    10541186
     
    10601192_PyInt_Format(PyIntObject *v, int base, int newstyle)
    10611193{
    1062         /* There are no doubt many, many ways to optimize this, using code
    1063            similar to _PyLong_Format */
    1064         long n = v->ob_ival;
    1065         int  negative = n < 0;
    1066         int is_zero = n == 0;
    1067 
    1068         /* For the reasoning behind this size, see
    1069            http://c-faq.com/misc/hexio.html. Then, add a few bytes for
    1070            the possible sign and prefix "0[box]" */
    1071         char buf[sizeof(n)*CHAR_BIT+6];
    1072 
    1073         /* Start by pointing to the end of the buffer.  We fill in from
    1074            the back forward. */
    1075         char* p = &buf[sizeof(buf)];
    1076 
    1077         assert(base >= 2 && base <= 36);
    1078 
    1079         do {
    1080                 /* I'd use i_divmod, except it doesn't produce the results
    1081                    I want when n is negative.  So just duplicate the salient
    1082                    part here. */
    1083                 long div = n / base;
    1084                 long mod = n - div * base;
    1085 
    1086                 /* convert abs(mod) to the right character in [0-9, a-z] */
    1087                 char cdigit = (char)(mod < 0 ? -mod : mod);
    1088                 cdigit += (cdigit < 10) ? '0' : 'a'-10;
    1089                 *--p = cdigit;
    1090 
    1091                 n = div;
    1092         } while(n);
    1093 
    1094         if (base == 2) {
    1095                 *--p = 'b';
    1096                 *--p = '0';
    1097         }
    1098         else if (base == 8) {
    1099                 if (newstyle) {
    1100                         *--p = 'o';
    1101                         *--p = '0';
    1102                 }
    1103                 else
    1104                         if (!is_zero)
    1105                                 *--p = '0';
    1106         }
    1107         else if (base == 16) {
    1108                 *--p = 'x';
    1109                 *--p = '0';
    1110         }
    1111         else if (base != 10) {
    1112                 *--p = '#';
    1113                 *--p = '0' + base%10;
    1114                 if (base > 10)
    1115                         *--p = '0' + base/10;
    1116         }
    1117         if (negative)
    1118                 *--p = '-';
    1119 
    1120         return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
     1194    /* There are no doubt many, many ways to optimize this, using code
     1195       similar to _PyLong_Format */
     1196    long n = v->ob_ival;
     1197    int  negative = n < 0;
     1198    int is_zero = n == 0;
     1199
     1200    /* For the reasoning behind this size, see
     1201       http://c-faq.com/misc/hexio.html. Then, add a few bytes for
     1202       the possible sign and prefix "0[box]" */
     1203    char buf[sizeof(n)*CHAR_BIT+6];
     1204
     1205    /* Start by pointing to the end of the buffer.  We fill in from
     1206       the back forward. */
     1207    char* p = &buf[sizeof(buf)];
     1208
     1209    assert(base >= 2 && base <= 36);
     1210
     1211    /* Special case base 10, for speed */
     1212    if (base == 10)
     1213        return int_to_decimal_string(v);
     1214
     1215    do {
     1216        /* I'd use i_divmod, except it doesn't produce the results
     1217           I want when n is negative.  So just duplicate the salient
     1218           part here. */
     1219        long div = n / base;
     1220        long mod = n - div * base;
     1221
     1222        /* convert abs(mod) to the right character in [0-9, a-z] */
     1223        char cdigit = (char)(mod < 0 ? -mod : mod);
     1224        cdigit += (cdigit < 10) ? '0' : 'a'-10;
     1225        *--p = cdigit;
     1226
     1227        n = div;
     1228    } while(n);
     1229
     1230    if (base == 2) {
     1231        *--p = 'b';
     1232        *--p = '0';
     1233    }
     1234    else if (base == 8) {
     1235        if (newstyle) {
     1236            *--p = 'o';
     1237            *--p = '0';
     1238        }
     1239        else
     1240            if (!is_zero)
     1241                *--p = '0';
     1242    }
     1243    else if (base == 16) {
     1244        *--p = 'x';
     1245        *--p = '0';
     1246    }
     1247    else {
     1248        *--p = '#';
     1249        *--p = '0' + base%10;
     1250        if (base > 10)
     1251            *--p = '0' + base/10;
     1252    }
     1253    if (negative)
     1254        *--p = '-';
     1255
     1256    return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
    11211257}
    11221258
     
    11241260int__format__(PyObject *self, PyObject *args)
    11251261{
    1126         PyObject *format_spec;
    1127 
    1128         if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
    1129                 return NULL;
    1130         if (PyBytes_Check(format_spec))
    1131                 return _PyInt_FormatAdvanced(self,
    1132                                              PyBytes_AS_STRING(format_spec),
    1133                                              PyBytes_GET_SIZE(format_spec));
    1134         if (PyUnicode_Check(format_spec)) {
    1135                 /* Convert format_spec to a str */
    1136                 PyObject *result;
    1137                 PyObject *str_spec = PyObject_Str(format_spec);
    1138 
    1139                 if (str_spec == NULL)
    1140                         return NULL;
    1141 
    1142                 result = _PyInt_FormatAdvanced(self,
    1143                                                PyBytes_AS_STRING(str_spec),
    1144                                                PyBytes_GET_SIZE(str_spec));
    1145 
    1146                 Py_DECREF(str_spec);
    1147                 return result;
    1148         }
    1149         PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
    1150         return NULL;
    1151 }
     1262    PyObject *format_spec;
     1263
     1264    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
     1265        return NULL;
     1266    if (PyBytes_Check(format_spec))
     1267        return _PyInt_FormatAdvanced(self,
     1268                                     PyBytes_AS_STRING(format_spec),
     1269                                     PyBytes_GET_SIZE(format_spec));
     1270    if (PyUnicode_Check(format_spec)) {
     1271        /* Convert format_spec to a str */
     1272        PyObject *result;
     1273        PyObject *str_spec = PyObject_Str(format_spec);
     1274
     1275        if (str_spec == NULL)
     1276            return NULL;
     1277
     1278        result = _PyInt_FormatAdvanced(self,
     1279                                       PyBytes_AS_STRING(str_spec),
     1280                                       PyBytes_GET_SIZE(str_spec));
     1281
     1282        Py_DECREF(str_spec);
     1283        return result;
     1284    }
     1285    PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
     1286    return NULL;
     1287}
     1288
     1289static PyObject *
     1290int_bit_length(PyIntObject *v)
     1291{
     1292    unsigned long n;
     1293
     1294    if (v->ob_ival < 0)
     1295        /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
     1296        n = 0U-(unsigned long)v->ob_ival;
     1297    else
     1298        n = (unsigned long)v->ob_ival;
     1299
     1300    return PyInt_FromLong(bits_in_ulong(n));
     1301}
     1302
     1303PyDoc_STRVAR(int_bit_length_doc,
     1304"int.bit_length() -> int\n\
     1305\n\
     1306Number of bits necessary to represent self in binary.\n\
     1307>>> bin(37)\n\
     1308'0b100101'\n\
     1309>>> (37).bit_length()\n\
     13106");
    11521311
    11531312#if 0
     
    11551314int_is_finite(PyObject *v)
    11561315{
    1157         Py_RETURN_TRUE;
     1316    Py_RETURN_TRUE;
    11581317}
    11591318#endif
    11601319
    11611320static PyMethodDef int_methods[] = {
    1162         {"conjugate",   (PyCFunction)int_int,   METH_NOARGS,
    1163          "Returns self, the complex conjugate of any int."},
     1321    {"conjugate",       (PyCFunction)int_int,   METH_NOARGS,
     1322     "Returns self, the complex conjugate of any int."},
     1323    {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
     1324     int_bit_length_doc},
    11641325#if 0
    1165         {"is_finite",   (PyCFunction)int_is_finite,     METH_NOARGS,
    1166         "Returns always True."},
    1167 #endif
    1168         {"__trunc__",   (PyCFunction)int_int,   METH_NOARGS,
    1169          "Truncating an Integral returns itself."},
    1170         {"__getnewargs__",      (PyCFunction)int_getnewargs,    METH_NOARGS},
    1171         {"__format__", (PyCFunction)int__format__, METH_VARARGS},
    1172         {NULL,          NULL}           /* sentinel */
     1326    {"is_finite",       (PyCFunction)int_is_finite,     METH_NOARGS,
     1327    "Returns always True."},
     1328#endif
     1329    {"__trunc__",       (PyCFunction)int_int,   METH_NOARGS,
     1330     "Truncating an Integral returns itself."},
     1331    {"__getnewargs__",          (PyCFunction)int_getnewargs,    METH_NOARGS},
     1332    {"__format__", (PyCFunction)int__format__, METH_VARARGS},
     1333    {NULL,              NULL}           /* sentinel */
    11731334};
    11741335
    11751336static PyGetSetDef int_getset[] = {
    1176         {"real",
    1177         (getter)int_int, (setter)NULL,
    1178         "the real part of a complex number",
    1179         NULL},
    1180         {"imag",
    1181          (getter)int_getN, (setter)NULL,
    1182         "the imaginary part of a complex number",
    1183          (void*)0},
    1184         {"numerator",
    1185         (getter)int_int, (setter)NULL,
    1186         "the numerator of a rational number in lowest terms",
    1187         NULL},
    1188         {"denominator",
    1189          (getter)int_getN, (setter)NULL,
    1190         "the denominator of a rational number in lowest terms",
    1191          (void*)1},
    1192         {NULL}  /* Sentinel */
     1337    {"real",
     1338    (getter)int_int, (setter)NULL,
     1339    "the real part of a complex number",
     1340    NULL},
     1341    {"imag",
     1342     (getter)int_get0, (setter)NULL,
     1343    "the imaginary part of a complex number",
     1344     NULL},
     1345    {"numerator",
     1346    (getter)int_int, (setter)NULL,
     1347    "the numerator of a rational number in lowest terms",
     1348    NULL},
     1349    {"denominator",
     1350     (getter)int_get1, (setter)NULL,
     1351    "the denominator of a rational number in lowest terms",
     1352     NULL},
     1353    {NULL}  /* Sentinel */
    11931354};
    11941355
    11951356PyDoc_STRVAR(int_doc,
    1196 "int(x[, base]) -> integer\n\
     1357"int(x=0) -> int or long\n\
     1358int(x, base=10) -> int or long\n\
    11971359\n\
    1198 Convert a string or number to an integer, if possible.  A floating point\n\
    1199 argument will be truncated towards zero (this does not include a string\n\
    1200 representation of a floating point number!)  When converting a string, use\n\
    1201 the optional base.  It is an error to supply a base when converting a\n\
    1202 non-string.  If base is zero, the proper base is guessed based on the\n\
    1203 string content.  If the argument is outside the integer range a\n\
    1204 long object will be returned instead.");
     1360Convert a number or string to an integer, or return 0 if no arguments\n\
     1361are given.  If x is floating point, the conversion truncates towards zero.\n\
     1362If x is outside the integer range, the function returns a long instead.\n\
     1363\n\
     1364If x is not a number or if base is given, then x must be a string or\n\
     1365Unicode object representing an integer literal in the given base.  The\n\
     1366literal can be preceded by '+' or '-' and be surrounded by whitespace.\n\
     1367The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to\n\
     1368interpret the base from the string as an integer literal.\n\
     1369>>> int('0b100', base=0)\n\
     13704");
    12051371
    12061372static PyNumberMethods int_as_number = {
    1207         (binaryfunc)int_add,    /*nb_add*/
    1208         (binaryfunc)int_sub,    /*nb_subtract*/
    1209         (binaryfunc)int_mul,    /*nb_multiply*/
    1210         (binaryfunc)int_classic_div, /*nb_divide*/
    1211         (binaryfunc)int_mod,    /*nb_remainder*/
    1212         (binaryfunc)int_divmod, /*nb_divmod*/
    1213         (ternaryfunc)int_pow,   /*nb_power*/
    1214         (unaryfunc)int_neg,     /*nb_negative*/
    1215         (unaryfunc)int_int,     /*nb_positive*/
    1216         (unaryfunc)int_abs,     /*nb_absolute*/
    1217         (inquiry)int_nonzero,   /*nb_nonzero*/
    1218         (unaryfunc)int_invert,  /*nb_invert*/
    1219         (binaryfunc)int_lshift, /*nb_lshift*/
    1220         (binaryfunc)int_rshift, /*nb_rshift*/
    1221         (binaryfunc)int_and,    /*nb_and*/
    1222         (binaryfunc)int_xor,    /*nb_xor*/
    1223         (binaryfunc)int_or,     /*nb_or*/
    1224         int_coerce,             /*nb_coerce*/
    1225         (unaryfunc)int_int,     /*nb_int*/
    1226         (unaryfunc)int_long,    /*nb_long*/
    1227         (unaryfunc)int_float,   /*nb_float*/
    1228         (unaryfunc)int_oct,     /*nb_oct*/
    1229         (unaryfunc)int_hex,     /*nb_hex*/
    1230         0,                      /*nb_inplace_add*/
    1231         0,                      /*nb_inplace_subtract*/
    1232         0,                      /*nb_inplace_multiply*/
    1233         0,                      /*nb_inplace_divide*/
    1234         0,                      /*nb_inplace_remainder*/
    1235         0,                      /*nb_inplace_power*/
    1236         0,                      /*nb_inplace_lshift*/
    1237         0,                      /*nb_inplace_rshift*/
    1238         0,                      /*nb_inplace_and*/
    1239         0,                      /*nb_inplace_xor*/
    1240         0,                      /*nb_inplace_or*/
    1241         (binaryfunc)int_div,    /* nb_floor_divide */
    1242         int_true_divide,        /* nb_true_divide */
    1243         0,                      /* nb_inplace_floor_divide */
    1244         0,                      /* nb_inplace_true_divide */
    1245         (unaryfunc)int_int,     /* nb_index */
     1373    (binaryfunc)int_add,        /*nb_add*/
     1374    (binaryfunc)int_sub,        /*nb_subtract*/
     1375    (binaryfunc)int_mul,        /*nb_multiply*/
     1376    (binaryfunc)int_classic_div, /*nb_divide*/
     1377    (binaryfunc)int_mod,        /*nb_remainder*/
     1378    (binaryfunc)int_divmod,     /*nb_divmod*/
     1379    (ternaryfunc)int_pow,       /*nb_power*/
     1380    (unaryfunc)int_neg,         /*nb_negative*/
     1381    (unaryfunc)int_int,         /*nb_positive*/
     1382    (unaryfunc)int_abs,         /*nb_absolute*/
     1383    (inquiry)int_nonzero,       /*nb_nonzero*/
     1384    (unaryfunc)int_invert,      /*nb_invert*/
     1385    (binaryfunc)int_lshift,     /*nb_lshift*/
     1386    (binaryfunc)int_rshift,     /*nb_rshift*/
     1387    (binaryfunc)int_and,        /*nb_and*/
     1388    (binaryfunc)int_xor,        /*nb_xor*/
     1389    (binaryfunc)int_or,         /*nb_or*/
     1390    int_coerce,                 /*nb_coerce*/
     1391    (unaryfunc)int_int,         /*nb_int*/
     1392    (unaryfunc)int_long,        /*nb_long*/
     1393    (unaryfunc)int_float,       /*nb_float*/
     1394    (unaryfunc)int_oct,         /*nb_oct*/
     1395    (unaryfunc)int_hex,         /*nb_hex*/
     1396    0,                          /*nb_inplace_add*/
     1397    0,                          /*nb_inplace_subtract*/
     1398    0,                          /*nb_inplace_multiply*/
     1399    0,                          /*nb_inplace_divide*/
     1400    0,                          /*nb_inplace_remainder*/
     1401    0,                          /*nb_inplace_power*/
     1402    0,                          /*nb_inplace_lshift*/
     1403    0,                          /*nb_inplace_rshift*/
     1404    0,                          /*nb_inplace_and*/
     1405    0,                          /*nb_inplace_xor*/
     1406    0,                          /*nb_inplace_or*/
     1407    (binaryfunc)int_div,        /* nb_floor_divide */
     1408    (binaryfunc)int_true_divide, /* nb_true_divide */
     1409    0,                          /* nb_inplace_floor_divide */
     1410    0,                          /* nb_inplace_true_divide */
     1411    (unaryfunc)int_int,         /* nb_index */
    12461412};
    12471413
    12481414PyTypeObject PyInt_Type = {
    1249         PyVarObject_HEAD_INIT(&PyType_Type, 0)
    1250         "int",
    1251         sizeof(PyIntObject),
    1252         0,
    1253         (destructor)int_dealloc,                /* tp_dealloc */
    1254         (printfunc)int_print,                   /* tp_print */
    1255         0,                                      /* tp_getattr */
    1256         0,                                      /* tp_setattr */
    1257         (cmpfunc)int_compare,                   /* tp_compare */
    1258         (reprfunc)int_repr,                     /* tp_repr */
    1259         &int_as_number,                         /* tp_as_number */
    1260         0,                                      /* tp_as_sequence */
    1261         0,                                      /* tp_as_mapping */
    1262         (hashfunc)int_hash,                     /* tp_hash */
    1263         0,                                      /* tp_call */
    1264         (reprfunc)int_repr,                     /* tp_str */
    1265         PyObject_GenericGetAttr,                /* tp_getattro */
    1266         0,                                      /* tp_setattro */
    1267         0,                                      /* tp_as_buffer */
    1268         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
    1269                 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS,  /* tp_flags */
    1270         int_doc,                                /* tp_doc */
    1271         0,                                      /* tp_traverse */
    1272         0,                                      /* tp_clear */
    1273         0,                                      /* tp_richcompare */
    1274         0,                                      /* tp_weaklistoffset */
    1275         0,                                      /* tp_iter */
    1276         0,                                      /* tp_iternext */
    1277         int_methods,                            /* tp_methods */
    1278         0,                                      /* tp_members */
    1279         int_getset,                             /* tp_getset */
    1280         0,                                      /* tp_base */
    1281         0,                                      /* tp_dict */
    1282         0,                                      /* tp_descr_get */
    1283         0,                                      /* tp_descr_set */
    1284         0,                                      /* tp_dictoffset */
    1285         0,                                      /* tp_init */
    1286         0,                                      /* tp_alloc */
    1287         int_new,                                /* tp_new */
    1288         (freefunc)int_free,                     /* tp_free */
     1415    PyVarObject_HEAD_INIT(&PyType_Type, 0)
     1416    "int",
     1417    sizeof(PyIntObject),
     1418    0,
     1419    (destructor)int_dealloc,                    /* tp_dealloc */
     1420    (printfunc)int_print,                       /* tp_print */
     1421    0,                                          /* tp_getattr */
     1422    0,                                          /* tp_setattr */
     1423    (cmpfunc)int_compare,                       /* tp_compare */
     1424    (reprfunc)int_to_decimal_string,            /* tp_repr */
     1425    &int_as_number,                             /* tp_as_number */
     1426    0,                                          /* tp_as_sequence */
     1427    0,                                          /* tp_as_mapping */
     1428    (hashfunc)int_hash,                         /* tp_hash */
     1429    0,                                          /* tp_call */
     1430    (reprfunc)int_to_decimal_string,            /* tp_str */
     1431    PyObject_GenericGetAttr,                    /* tp_getattro */
     1432    0,                                          /* tp_setattro */
     1433    0,                                          /* tp_as_buffer */
     1434    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
     1435        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS,          /* tp_flags */
     1436    int_doc,                                    /* tp_doc */
     1437    0,                                          /* tp_traverse */
     1438    0,                                          /* tp_clear */
     1439    0,                                          /* tp_richcompare */
     1440    0,                                          /* tp_weaklistoffset */
     1441    0,                                          /* tp_iter */
     1442    0,                                          /* tp_iternext */
     1443    int_methods,                                /* tp_methods */
     1444    0,                                          /* tp_members */
     1445    int_getset,                                 /* tp_getset */
     1446    0,                                          /* tp_base */
     1447    0,                                          /* tp_dict */
     1448    0,                                          /* tp_descr_get */
     1449    0,                                          /* tp_descr_set */
     1450    0,                                          /* tp_dictoffset */
     1451    0,                                          /* tp_init */
     1452    0,                                          /* tp_alloc */
     1453    int_new,                                    /* tp_new */
     1454    (freefunc)int_free,                         /* tp_free */
    12891455};
    12901456
     
    12921458_PyInt_Init(void)
    12931459{
    1294         PyIntObject *v;
    1295         int ival;
     1460    PyIntObject *v;
     1461    int ival;
    12961462#if NSMALLNEGINTS + NSMALLPOSINTS > 0
    1297         for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
    1298               if (!free_list && (free_list = fill_free_list()) == NULL)
    1299                         return 0;
    1300                 /* PyObject_New is inlined */
    1301                 v = free_list;
    1302                 free_list = (PyIntObject *)Py_TYPE(v);
    1303                 PyObject_INIT(v, &PyInt_Type);
    1304                 v->ob_ival = ival;
    1305                 small_ints[ival + NSMALLNEGINTS] = v;
    1306         }
    1307 #endif
    1308         return 1;
     1463    for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
     1464          if (!free_list && (free_list = fill_free_list()) == NULL)
     1465                    return 0;
     1466        /* PyObject_New is inlined */
     1467        v = free_list;
     1468        free_list = (PyIntObject *)Py_TYPE(v);
     1469        PyObject_INIT(v, &PyInt_Type);
     1470        v->ob_ival = ival;
     1471        small_ints[ival + NSMALLNEGINTS] = v;
     1472    }
     1473#endif
     1474    return 1;
    13091475}
    13101476
     
    13121478PyInt_ClearFreeList(void)
    13131479{
    1314         PyIntObject *p;
    1315         PyIntBlock *list, *next;
    1316         int i;
    1317         int u;                  /* remaining unfreed ints per block */
    1318         int freelist_size = 0;
    1319 
    1320         list = block_list;
    1321         block_list = NULL;
    1322         free_list = NULL;
    1323         while (list != NULL) {
    1324                 u = 0;
    1325                 for (i = 0, p = &list->objects[0];
    1326                      i < N_INTOBJECTS;
    1327                      i++, p++) {
    1328                         if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
    1329                                 u++;
    1330                 }
    1331                 next = list->next;
    1332                 if (u) {
    1333                         list->next = block_list;
    1334                         block_list = list;
    1335                         for (i = 0, p = &list->objects[0];
    1336                              i < N_INTOBJECTS;
    1337                              i++, p++) {
    1338                                 if (!PyInt_CheckExact(p) ||
    1339                                     p->ob_refcnt == 0) {
    1340                                         Py_TYPE(p) = (struct _typeobject *)
    1341                                                 free_list;
    1342                                         free_list = p;
    1343                                 }
     1480    PyIntObject *p;
     1481    PyIntBlock *list, *next;
     1482    int i;
     1483    int u;                      /* remaining unfreed ints per block */
     1484    int freelist_size = 0;
     1485
     1486    list = block_list;
     1487    block_list = NULL;
     1488    free_list = NULL;
     1489    while (list != NULL) {
     1490        u = 0;
     1491        for (i = 0, p = &list->objects[0];
     1492             i < N_INTOBJECTS;
     1493             i++, p++) {
     1494            if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
     1495                u++;
     1496        }
     1497        next = list->next;
     1498        if (u) {
     1499            list->next = block_list;
     1500            block_list = list;
     1501            for (i = 0, p = &list->objects[0];
     1502                 i < N_INTOBJECTS;
     1503                 i++, p++) {
     1504                if (!PyInt_CheckExact(p) ||
     1505                    p->ob_refcnt == 0) {
     1506                    Py_TYPE(p) = (struct _typeobject *)
     1507                        free_list;
     1508                    free_list = p;
     1509                }
    13441510#if NSMALLNEGINTS + NSMALLPOSINTS > 0
    1345                                 else if (-NSMALLNEGINTS <= p->ob_ival &&
    1346                                         p->ob_ival < NSMALLPOSINTS &&
    1347                                         small_ints[p->ob_ival +
    1348                                                     NSMALLNEGINTS] == NULL) {
    1349                                         Py_INCREF(p);
    1350                                         small_ints[p->ob_ival +
    1351                                                    NSMALLNEGINTS] = p;
    1352                                 }
    1353 #endif
    1354                         }
    1355                 }
    1356                 else {
    1357                         PyMem_FREE(list);
    1358                 }
    1359                 freelist_size += u;
    1360                 list = next;
    1361         }
    1362 
    1363         return freelist_size;
     1511                else if (-NSMALLNEGINTS <= p->ob_ival &&
     1512                        p->ob_ival < NSMALLPOSINTS &&
     1513                        small_ints[p->ob_ival +
     1514                                    NSMALLNEGINTS] == NULL) {
     1515                    Py_INCREF(p);
     1516                    small_ints[p->ob_ival +
     1517                               NSMALLNEGINTS] = p;
     1518                }
     1519#endif
     1520            }
     1521        }
     1522        else {
     1523            PyMem_FREE(list);
     1524        }
     1525        freelist_size += u;
     1526        list = next;
     1527    }
     1528
     1529    return freelist_size;
    13641530}
    13651531
     
    13671533PyInt_Fini(void)
    13681534{
    1369         PyIntObject *p;
    1370         PyIntBlock *list;
    1371         int i;
    1372         int u;                  /* total unfreed ints per block */
     1535    PyIntObject *p;
     1536    PyIntBlock *list;
     1537    int i;
     1538    int u;                      /* total unfreed ints per block */
    13731539
    13741540#if NSMALLNEGINTS + NSMALLPOSINTS > 0
    1375         PyIntObject **q;
    1376 
    1377         i = NSMALLNEGINTS + NSMALLPOSINTS;
    1378         q = small_ints;
    1379         while (--i >= 0) {
    1380                 Py_XDECREF(*q);
    1381                 *q++ = NULL;
    1382         }
    1383 #endif
    1384         u = PyInt_ClearFreeList();
    1385         if (!Py_VerboseFlag)
    1386                 return;
    1387         fprintf(stderr, "# cleanup ints");
    1388         if (!u) {
    1389                 fprintf(stderr, "\n");
    1390         }
    1391         else {
    1392                 fprintf(stderr,
    1393                         ": %d unfreed int%s\n",
    1394                         u, u == 1 ? "" : "s");
    1395         }
    1396         if (Py_VerboseFlag > 1) {
    1397                 list = block_list;
    1398                 while (list != NULL) {
    1399                         for (i = 0, p = &list->objects[0];
    1400                              i < N_INTOBJECTS;
    1401                              i++, p++) {
    1402                                 if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
    1403                                         /* XXX(twouters) cast refcount to
    1404                                            long until %zd is universally
    1405                                            available
    1406                                         */
    1407                                         fprintf(stderr,
    1408                                 "#   <int at %p, refcnt=%ld, val=%ld>\n",
    1409                                                 p, (long)p->ob_refcnt,
    1410                                                 p->ob_ival);
    1411                         }
    1412                         list = list->next;
    1413                 }
    1414         }
    1415 }
     1541    PyIntObject **q;
     1542
     1543    i = NSMALLNEGINTS + NSMALLPOSINTS;
     1544    q = small_ints;
     1545    while (--i >= 0) {
     1546        Py_XDECREF(*q);
     1547        *q++ = NULL;
     1548    }
     1549#endif
     1550    u = PyInt_ClearFreeList();
     1551    if (!Py_VerboseFlag)
     1552        return;
     1553    fprintf(stderr, "# cleanup ints");
     1554    if (!u) {
     1555        fprintf(stderr, "\n");
     1556    }
     1557    else {
     1558        fprintf(stderr,
     1559            ": %d unfreed int%s\n",
     1560            u, u == 1 ? "" : "s");
     1561    }
     1562    if (Py_VerboseFlag > 1) {
     1563        list = block_list;
     1564        while (list != NULL) {
     1565            for (i = 0, p = &list->objects[0];
     1566                 i < N_INTOBJECTS;
     1567                 i++, p++) {
     1568                if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
     1569                    /* XXX(twouters) cast refcount to
     1570                       long until %zd is universally
     1571                       available
     1572                    */
     1573                    fprintf(stderr,
     1574                "#   <int at %p, refcnt=%ld, val=%ld>\n",
     1575                                p, (long)p->ob_refcnt,
     1576                                p->ob_ival);
     1577            }
     1578            list = list->next;
     1579        }
     1580    }
     1581}
Note: See TracChangeset for help on using the changeset viewer.