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/floatobject.c

    r2 r388  
    1616#define MIN(x, y) ((x) < (y) ? (x) : (y))
    1717
    18 #ifdef HAVE_IEEEFP_H
    19 #include <ieeefp.h>
    20 #endif
    21 
    2218#ifdef _OSF_SOURCE
    2319/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
     
    2622
    2723/* Special free list -- see comments for same code in intobject.c. */
    28 #define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
    29 #define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
    30 #define N_FLOATOBJECTS  ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
     24#define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
     25#define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
     26#define N_FLOATOBJECTS  ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
    3127
    3228struct _floatblock {
    33         struct _floatblock *next;
    34         PyFloatObject objects[N_FLOATOBJECTS];
     29    struct _floatblock *next;
     30    PyFloatObject objects[N_FLOATOBJECTS];
    3531};
    3632
     
    4339fill_free_list(void)
    4440{
    45         PyFloatObject *p, *q;
    46         /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
    47         p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
    48         if (p == NULL)
    49                 return (PyFloatObject *) PyErr_NoMemory();
    50         ((PyFloatBlock *)p)->next = block_list;
    51         block_list = (PyFloatBlock *)p;
    52         p = &((PyFloatBlock *)p)->objects[0];
    53         q = p + N_FLOATOBJECTS;
    54         while (--q > p)
    55                 Py_TYPE(q) = (struct _typeobject *)(q-1);
    56         Py_TYPE(q) = NULL;
    57         return p + N_FLOATOBJECTS - 1;
     41    PyFloatObject *p, *q;
     42    /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
     43    p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
     44    if (p == NULL)
     45        return (PyFloatObject *) PyErr_NoMemory();
     46    ((PyFloatBlock *)p)->next = block_list;
     47    block_list = (PyFloatBlock *)p;
     48    p = &((PyFloatBlock *)p)->objects[0];
     49    q = p + N_FLOATOBJECTS;
     50    while (--q > p)
     51        Py_TYPE(q) = (struct _typeobject *)(q-1);
     52    Py_TYPE(q) = NULL;
     53    return p + N_FLOATOBJECTS - 1;
    5854}
    5955
     
    6157PyFloat_GetMax(void)
    6258{
    63         return DBL_MAX;
     59    return DBL_MAX;
    6460}
    6561
     
    6763PyFloat_GetMin(void)
    6864{
    69         return DBL_MIN;
     65    return DBL_MIN;
    7066}
    7167
     
    7369
    7470PyDoc_STRVAR(floatinfo__doc__,
    75 "sys.floatinfo\n\
     71"sys.float_info\n\
    7672\n\
    7773A structseq holding information about the float type. It contains low level\n\
     
    8076
    8177static PyStructSequence_Field floatinfo_fields[] = {
    82         {"max",         "DBL_MAX -- maximum representable finite float"},
    83         {"max_exp",     "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
    84                         "is representable"},
    85         {"max_10_exp",  "DBL_MAX_10_EXP -- maximum int e such that 10**e "
    86                         "is representable"},
    87         {"min",         "DBL_MIN -- Minimum positive normalizer float"},
    88         {"min_exp",     "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
    89                         "is a normalized float"},
    90         {"min_10_exp",  "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
    91                         "a normalized"},
    92         {"dig",         "DBL_DIG -- digits"},
    93         {"mant_dig",    "DBL_MANT_DIG -- mantissa digits"},
    94         {"epsilon",     "DBL_EPSILON -- Difference between 1 and the next "
    95                         "representable float"},
    96         {"radix",       "FLT_RADIX -- radix of exponent"},
    97         {"rounds",      "FLT_ROUNDS -- addition rounds"},
    98         {0}
     78    {"max",             "DBL_MAX -- maximum representable finite float"},
     79    {"max_exp",         "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
     80                    "is representable"},
     81    {"max_10_exp",      "DBL_MAX_10_EXP -- maximum int e such that 10**e "
     82                    "is representable"},
     83    {"min",             "DBL_MIN -- Minimum positive normalizer float"},
     84    {"min_exp",         "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
     85                    "is a normalized float"},
     86    {"min_10_exp",      "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
     87                    "a normalized"},
     88    {"dig",             "DBL_DIG -- digits"},
     89    {"mant_dig",        "DBL_MANT_DIG -- mantissa digits"},
     90    {"epsilon",         "DBL_EPSILON -- Difference between 1 and the next "
     91                    "representable float"},
     92    {"radix",           "FLT_RADIX -- radix of exponent"},
     93    {"rounds",          "FLT_ROUNDS -- addition rounds"},
     94    {0}
    9995};
    10096
    10197static PyStructSequence_Desc floatinfo_desc = {
    102         "sys.floatinfo",        /* name */
    103         floatinfo__doc__,       /* doc */
    104         floatinfo_fields,       /* fields */
    105         11
     98    "sys.float_info",           /* name */
     99    floatinfo__doc__,           /* doc */
     100    floatinfo_fields,           /* fields */
     101    11
    106102};
    107103
     
    109105PyFloat_GetInfo(void)
    110106{
    111         PyObject* floatinfo;
    112         int pos = 0;
    113 
    114         floatinfo = PyStructSequence_New(&FloatInfoType);
    115         if (floatinfo == NULL) {
    116                 return NULL;
    117         }
     107    PyObject* floatinfo;
     108    int pos = 0;
     109
     110    floatinfo = PyStructSequence_New(&FloatInfoType);
     111    if (floatinfo == NULL) {
     112        return NULL;
     113    }
    118114
    119115#define SetIntFlag(flag) \
    120         PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
     116    PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
    121117#define SetDblFlag(flag) \
    122         PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
    123 
    124         SetDblFlag(DBL_MAX);
    125         SetIntFlag(DBL_MAX_EXP);
    126         SetIntFlag(DBL_MAX_10_EXP);
    127         SetDblFlag(DBL_MIN);
    128         SetIntFlag(DBL_MIN_EXP);
    129         SetIntFlag(DBL_MIN_10_EXP);
    130         SetIntFlag(DBL_DIG);
    131         SetIntFlag(DBL_MANT_DIG);
    132         SetDblFlag(DBL_EPSILON);
    133         SetIntFlag(FLT_RADIX);
    134         SetIntFlag(FLT_ROUNDS);
     118    PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
     119
     120    SetDblFlag(DBL_MAX);
     121    SetIntFlag(DBL_MAX_EXP);
     122    SetIntFlag(DBL_MAX_10_EXP);
     123    SetDblFlag(DBL_MIN);
     124    SetIntFlag(DBL_MIN_EXP);
     125    SetIntFlag(DBL_MIN_10_EXP);
     126    SetIntFlag(DBL_DIG);
     127    SetIntFlag(DBL_MANT_DIG);
     128    SetDblFlag(DBL_EPSILON);
     129    SetIntFlag(FLT_RADIX);
     130    SetIntFlag(FLT_ROUNDS);
    135131#undef SetIntFlag
    136132#undef SetDblFlag
    137        
    138         if (PyErr_Occurred()) {
    139                 Py_CLEAR(floatinfo);
    140                 return NULL;
    141         }
    142         return floatinfo;
     133
     134    if (PyErr_Occurred()) {
     135        Py_CLEAR(floatinfo);
     136        return NULL;
     137    }
     138    return floatinfo;
    143139}
    144140
     
    146142PyFloat_FromDouble(double fval)
    147143{
    148         register PyFloatObject *op;
    149         if (free_list == NULL) {
    150                 if ((free_list = fill_free_list()) == NULL)
    151                         return NULL;
    152         }
    153         /* Inline PyObject_New */
    154         op = free_list;
    155         free_list = (PyFloatObject *)Py_TYPE(op);
    156         PyObject_INIT(op, &PyFloat_Type);
    157         op->ob_fval = fval;
    158         return (PyObject *) op;
     144    register PyFloatObject *op;
     145    if (free_list == NULL) {
     146        if ((free_list = fill_free_list()) == NULL)
     147            return NULL;
     148    }
     149    /* Inline PyObject_New */
     150    op = free_list;
     151    free_list = (PyFloatObject *)Py_TYPE(op);
     152    PyObject_INIT(op, &PyFloat_Type);
     153    op->ob_fval = fval;
     154    return (PyObject *) op;
    159155}
    160156
     
    178174PyFloat_FromString(PyObject *v, char **pend)
    179175{
    180         const char *s, *last, *end, *sp;
    181         double x;
    182         char buffer[256]; /* for errors */
     176    const char *s, *last, *end;
     177    double x;
     178    char buffer[256]; /* for errors */
    183179#ifdef Py_USING_UNICODE
    184         char s_buffer[256]; /* for objects convertible to a char buffer */
     180    char *s_buffer = NULL;
    185181#endif
    186         Py_ssize_t len;
    187 
    188         if (pend)
    189                 *pend = NULL;
    190         if (PyString_Check(v)) {
    191                 s = PyString_AS_STRING(v);
    192                 len = PyString_GET_SIZE(v);
    193         }
     182    Py_ssize_t len;
     183    PyObject *result = NULL;
     184
     185    if (pend)
     186        *pend = NULL;
     187    if (PyString_Check(v)) {
     188        s = PyString_AS_STRING(v);
     189        len = PyString_GET_SIZE(v);
     190    }
    194191#ifdef Py_USING_UNICODE
    195         else if (PyUnicode_Check(v)) {
    196                 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
    197                         PyErr_SetString(PyExc_ValueError,
    198                                 "Unicode float() literal too long to convert");
    199                         return NULL;
    200                 }
    201                 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
    202                                             PyUnicode_GET_SIZE(v),
    203                                             s_buffer,
    204                                             NULL))
    205                         return NULL;
    206                 s = s_buffer;
    207                 len = strlen(s);
    208         }
     192    else if (PyUnicode_Check(v)) {
     193        s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
     194        if (s_buffer == NULL)
     195            return PyErr_NoMemory();
     196        if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
     197                                    PyUnicode_GET_SIZE(v),
     198                                    s_buffer,
     199                                    NULL))
     200            goto error;
     201        s = s_buffer;
     202        len = strlen(s);
     203    }
    209204#endif
    210         else if (PyObject_AsCharBuffer(v, &s, &len)) {
    211                 PyErr_SetString(PyExc_TypeError,
    212                                 "float() argument must be a string or a number");
    213                 return NULL;
    214         }
    215 
    216         last = s + len;
    217         while (*s && isspace(Py_CHARMASK(*s)))
    218                 s++;
    219         if (*s == '\0') {
    220                 PyErr_SetString(PyExc_ValueError, "empty string for float()");
    221                 return NULL;
    222         }
    223         sp = s;
    224         /* We don't care about overflow or underflow.  If the platform supports
    225          * them, infinities and signed zeroes (on underflow) are fine.
    226          * However, strtod can return 0 for denormalized numbers, where atof
    227          * does not.  So (alas!) we special-case a zero result.  Note that
    228          * whether strtod sets errno on underflow is not defined, so we can't
    229          * key off errno.
    230          */
    231         PyFPE_START_PROTECT("strtod", return NULL)
    232         x = PyOS_ascii_strtod(s, (char **)&end);
    233         PyFPE_END_PROTECT(x)
    234         errno = 0;
    235         /* Believe it or not, Solaris 2.6 can move end *beyond* the null
    236            byte at the end of the string, when the input is inf(inity). */
    237         if (end > last)
    238                 end = last;
    239         /* Check for inf and nan. This is done late because it rarely happens. */
    240         if (end == s) {
    241                 char *p = (char*)sp;
    242                 int sign = 1;
    243 
    244                 if (*p == '-') {
    245                         sign = -1;
    246                         p++;
    247                 }
    248                 if (*p == '+') {
    249                         p++;
    250                 }
    251                 if (PyOS_strnicmp(p, "inf", 4) == 0) {
    252                         Py_RETURN_INF(sign);
    253                 }
    254                 if (PyOS_strnicmp(p, "infinity", 9) == 0) {
    255                         Py_RETURN_INF(sign);
    256                 }
    257 #ifdef Py_NAN
    258                 if(PyOS_strnicmp(p, "nan", 4) == 0) {
    259                         Py_RETURN_NAN;
    260                 }
     205    else if (PyObject_AsCharBuffer(v, &s, &len)) {
     206        PyErr_SetString(PyExc_TypeError,
     207            "float() argument must be a string or a number");
     208        return NULL;
     209    }
     210    last = s + len;
     211
     212    while (Py_ISSPACE(*s))
     213        s++;
     214    /* We don't care about overflow or underflow.  If the platform
     215     * supports them, infinities and signed zeroes (on underflow) are
     216     * fine. */
     217    x = PyOS_string_to_double(s, (char **)&end, NULL);
     218    if (x == -1.0 && PyErr_Occurred())
     219        goto error;
     220    while (Py_ISSPACE(*end))
     221        end++;
     222    if (end == last)
     223        result = PyFloat_FromDouble(x);
     224    else {
     225        PyOS_snprintf(buffer, sizeof(buffer),
     226                      "invalid literal for float(): %.200s", s);
     227        PyErr_SetString(PyExc_ValueError, buffer);
     228        result = NULL;
     229    }
     230
     231  error:
     232#ifdef Py_USING_UNICODE
     233    if (s_buffer)
     234        PyMem_FREE(s_buffer);
    261235#endif
    262                 PyOS_snprintf(buffer, sizeof(buffer),
    263                               "invalid literal for float(): %.200s", s);
    264                 PyErr_SetString(PyExc_ValueError, buffer);
    265                 return NULL;
    266         }
    267         /* Since end != s, the platform made *some* kind of sense out
    268            of the input.  Trust it. */
    269         while (*end && isspace(Py_CHARMASK(*end)))
    270                 end++;
    271         if (*end != '\0') {
    272                 PyOS_snprintf(buffer, sizeof(buffer),
    273                               "invalid literal for float(): %.200s", s);
    274                 PyErr_SetString(PyExc_ValueError, buffer);
    275                 return NULL;
    276         }
    277         else if (end != last) {
    278                 PyErr_SetString(PyExc_ValueError,
    279                                 "null byte in argument for float()");
    280                 return NULL;
    281         }
    282         if (x == 0.0) {
    283                 /* See above -- may have been strtod being anal
    284                    about denorms. */
    285                 PyFPE_START_PROTECT("atof", return NULL)
    286                 x = PyOS_ascii_atof(s);
    287                 PyFPE_END_PROTECT(x)
    288                 errno = 0;    /* whether atof ever set errno is undefined */
    289         }
    290         return PyFloat_FromDouble(x);
     236    return result;
    291237}
    292238
     
    294240float_dealloc(PyFloatObject *op)
    295241{
    296         if (PyFloat_CheckExact(op)) {
    297                 Py_TYPE(op) = (struct _typeobject *)free_list;
    298                 free_list = op;
    299         }
    300         else
    301                 Py_TYPE(op)->tp_free((PyObject *)op);
     242    if (PyFloat_CheckExact(op)) {
     243        Py_TYPE(op) = (struct _typeobject *)free_list;
     244        free_list = op;
     245    }
     246    else
     247        Py_TYPE(op)->tp_free((PyObject *)op);
    302248}
    303249
     
    305251PyFloat_AsDouble(PyObject *op)
    306252{
    307         PyNumberMethods *nb;
    308         PyFloatObject *fo;
    309         double val;
    310 
    311         if (op && PyFloat_Check(op))
    312                 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
    313 
    314         if (op == NULL) {
    315                 PyErr_BadArgument();
    316                 return -1;
    317         }
    318 
    319         if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
    320                 PyErr_SetString(PyExc_TypeError, "a float is required");
    321                 return -1;
    322         }
    323 
    324         fo = (PyFloatObject*) (*nb->nb_float) (op);
    325         if (fo == NULL)
    326                 return -1;
    327         if (!PyFloat_Check(fo)) {
    328                 PyErr_SetString(PyExc_TypeError,
    329                                 "nb_float should return float object");
    330                 return -1;
    331         }
    332 
    333         val = PyFloat_AS_DOUBLE(fo);
    334         Py_DECREF(fo);
    335 
    336         return val;
     253    PyNumberMethods *nb;
     254    PyFloatObject *fo;
     255    double val;
     256
     257    if (op && PyFloat_Check(op))
     258        return PyFloat_AS_DOUBLE((PyFloatObject*) op);
     259
     260    if (op == NULL) {
     261        PyErr_BadArgument();
     262        return -1;
     263    }
     264
     265    if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
     266        PyErr_SetString(PyExc_TypeError, "a float is required");
     267        return -1;
     268    }
     269
     270    fo = (PyFloatObject*) (*nb->nb_float) (op);
     271    if (fo == NULL)
     272        return -1;
     273    if (!PyFloat_Check(fo)) {
     274        PyErr_SetString(PyExc_TypeError,
     275                        "nb_float should return float object");
     276        return -1;
     277    }
     278
     279    val = PyFloat_AS_DOUBLE(fo);
     280    Py_DECREF(fo);
     281
     282    return val;
    337283}
    338284
    339285/* Methods */
    340 
    341 static void
    342 format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
    343 {
    344         register char *cp;
    345         char format[32];
    346         int i;
    347 
    348         /* Subroutine for float_repr and float_print.
    349            We want float numbers to be recognizable as such,
    350            i.e., they should contain a decimal point or an exponent.
    351            However, %g may print the number as an integer;
    352            in such cases, we append ".0" to the string. */
    353 
    354         assert(PyFloat_Check(v));
    355         PyOS_snprintf(format, 32, "%%.%ig", precision);
    356         PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
    357         cp = buf;
    358         if (*cp == '-')
    359                 cp++;
    360         for (; *cp != '\0'; cp++) {
    361                 /* Any non-digit means it's not an integer;
    362                    this takes care of NAN and INF as well. */
    363                 if (!isdigit(Py_CHARMASK(*cp)))
    364                         break;
    365         }
    366         if (*cp == '\0') {
    367                 *cp++ = '.';
    368                 *cp++ = '0';
    369                 *cp++ = '\0';
    370                 return;
    371         }
    372         /* Checking the next three chars should be more than enough to
    373          * detect inf or nan, even on Windows. We check for inf or nan
    374          * at last because they are rare cases.
    375          */
    376         for (i=0; *cp != '\0' && i<3; cp++, i++) {
    377                 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
    378                         continue;
    379                 /* found something that is neither a digit nor point
    380                  * it might be a NaN or INF
    381                  */
    382 #ifdef Py_NAN
    383                 if (Py_IS_NAN(v->ob_fval)) {
    384                         strcpy(buf, "nan");
    385                 }
    386                 else
    387 #endif
    388                 if (Py_IS_INFINITY(v->ob_fval)) {
    389                         cp = buf;
    390                         if (*cp == '-')
    391                                 cp++;
    392                         strcpy(cp, "inf");
    393                 }
    394                 break;
    395         }
    396 
    397 }
    398 
    399 /* XXX PyFloat_AsStringEx should not be a public API function (for one
    400    XXX thing, its signature passes a buffer without a length; for another,
    401    XXX it isn't useful outside this file).
    402 */
    403 void
    404 PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
    405 {
    406         format_float(buf, 100, v, precision);
    407 }
    408286
    409287/* Macro and helper that convert PyObject obj to a C double and store
     
    414292   stored in obj, and returned from the function invoking this macro.
    415293*/
    416 #define CONVERT_TO_DOUBLE(obj, dbl)                     \
    417         if (PyFloat_Check(obj))                         \
    418                 dbl = PyFloat_AS_DOUBLE(obj);           \
    419         else if (convert_to_double(&(obj), &(dbl)) < 0) \
    420                 return obj;
     294#define CONVERT_TO_DOUBLE(obj, dbl)                     \
     295    if (PyFloat_Check(obj))                             \
     296        dbl = PyFloat_AS_DOUBLE(obj);                   \
     297    else if (convert_to_double(&(obj), &(dbl)) < 0)     \
     298        return obj;
    421299
    422300static int
    423301convert_to_double(PyObject **v, double *dbl)
    424302{
    425         register PyObject *obj = *v;
    426 
    427         if (PyInt_Check(obj)) {
    428                 *dbl = (double)PyInt_AS_LONG(obj);
    429         }
    430         else if (PyLong_Check(obj)) {
    431                 *dbl = PyLong_AsDouble(obj);
    432                 if (*dbl == -1.0 && PyErr_Occurred()) {
    433                         *v = NULL;
    434                         return -1;
    435                 }
    436         }
    437         else {
    438                 Py_INCREF(Py_NotImplemented);
    439                 *v = Py_NotImplemented;
    440                 return -1;
    441         }
    442         return 0;
    443 }
    444 
    445 /* Precisions used by repr() and str(), respectively.
    446 
    447    The repr() precision (17 significant decimal digits) is the minimal number
    448    that is guaranteed to have enough precision so that if the number is read
    449    back in the exact same binary value is recreated.  This is true for IEEE
    450    floating point by design, and also happens to work for all other modern
    451    hardware.
    452 
    453    The str() precision is chosen so that in most cases, the rounding noise
    454    created by various operations is suppressed, while giving plenty of
    455    precision for practical use.
    456 
    457 */
    458 
    459 #define PREC_REPR       17
    460 #define PREC_STR        12
    461 
    462 /* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
     303    register PyObject *obj = *v;
     304
     305    if (PyInt_Check(obj)) {
     306        *dbl = (double)PyInt_AS_LONG(obj);
     307    }
     308    else if (PyLong_Check(obj)) {
     309        *dbl = PyLong_AsDouble(obj);
     310        if (*dbl == -1.0 && PyErr_Occurred()) {
     311            *v = NULL;
     312            return -1;
     313        }
     314    }
     315    else {
     316        Py_INCREF(Py_NotImplemented);
     317        *v = Py_NotImplemented;
     318        return -1;
     319    }
     320    return 0;
     321}
     322
     323/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
    463324   XXX they pass a char buffer without passing a length.
    464325*/
     
    466327PyFloat_AsString(char *buf, PyFloatObject *v)
    467328{
    468         format_float(buf, 100, v, PREC_STR);
     329    char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
     330                    PyFloat_STR_PRECISION,
     331                    Py_DTSF_ADD_DOT_0, NULL);
     332    strcpy(buf, tmp);
     333    PyMem_Free(tmp);
    469334}
    470335
     
    472337PyFloat_AsReprString(char *buf, PyFloatObject *v)
    473338{
    474         format_float(buf, 100, v, PREC_REPR);
     339    char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
     340                    Py_DTSF_ADD_DOT_0, NULL);
     341    strcpy(buf, tmp);
     342    PyMem_Free(tmp);
    475343}
    476344
     
    479347float_print(PyFloatObject *v, FILE *fp, int flags)
    480348{
    481         char buf[100];
    482         format_float(buf, sizeof(buf), v,
    483                      (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
    484         Py_BEGIN_ALLOW_THREADS
    485         fputs(buf, fp);
    486         Py_END_ALLOW_THREADS
    487         return 0;
     349    char *buf;
     350    if (flags & Py_PRINT_RAW)
     351        buf = PyOS_double_to_string(v->ob_fval,
     352                                    'g', PyFloat_STR_PRECISION,
     353                                    Py_DTSF_ADD_DOT_0, NULL);
     354    else
     355        buf = PyOS_double_to_string(v->ob_fval,
     356                            'r', 0, Py_DTSF_ADD_DOT_0, NULL);
     357    Py_BEGIN_ALLOW_THREADS
     358    fputs(buf, fp);
     359    Py_END_ALLOW_THREADS
     360    PyMem_Free(buf);
     361    return 0;
     362}
     363
     364static PyObject *
     365float_str_or_repr(PyFloatObject *v, int precision, char format_code)
     366{
     367    PyObject *result;
     368    char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
     369                                  format_code, precision,
     370                                  Py_DTSF_ADD_DOT_0,
     371                                  NULL);
     372    if (!buf)
     373        return PyErr_NoMemory();
     374    result = PyString_FromString(buf);
     375    PyMem_Free(buf);
     376    return result;
    488377}
    489378
     
    491380float_repr(PyFloatObject *v)
    492381{
    493         char buf[100];
    494         format_float(buf, sizeof(buf), v, PREC_REPR);
    495 
    496         return PyString_FromString(buf);
     382    return float_str_or_repr(v, 0, 'r');
    497383}
    498384
     
    500386float_str(PyFloatObject *v)
    501387{
    502         char buf[100];
    503         format_float(buf, sizeof(buf), v, PREC_STR);
    504         return PyString_FromString(buf);
     388    return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
    505389}
    506390
     
    523407float_richcompare(PyObject *v, PyObject *w, int op)
    524408{
    525         double i, j;
    526         int r = 0;
    527 
    528         assert(PyFloat_Check(v));
    529         i = PyFloat_AS_DOUBLE(v);
    530 
    531         /* Switch on the type of w.  Set i and j to doubles to be compared,
    532         * and op to the richcomp to use.
    533         */
    534         if (PyFloat_Check(w))
    535                 j = PyFloat_AS_DOUBLE(w);
    536 
    537         else if (!Py_IS_FINITE(i)) {
    538                 if (PyInt_Check(w) || PyLong_Check(w))
    539                         /* If i is an infinity, its magnitude exceeds any
    540                         * finite integer, so it doesn't matter which int we
    541                         * compare i with.  If i is a NaN, similarly.
    542                         */
    543                         j = 0.0;
    544                 else
    545                         goto Unimplemented;
    546         }
    547 
    548         else if (PyInt_Check(w)) {
    549                 long jj = PyInt_AS_LONG(w);
    550                 /* In the worst realistic case I can imagine, C double is a
    551                 * Cray single with 48 bits of precision, and long has 64
    552                 * bits.
    553                 */
     409    double i, j;
     410    int r = 0;
     411
     412    assert(PyFloat_Check(v));
     413    i = PyFloat_AS_DOUBLE(v);
     414
     415    /* Switch on the type of w.  Set i and j to doubles to be compared,
     416    * and op to the richcomp to use.
     417    */
     418    if (PyFloat_Check(w))
     419        j = PyFloat_AS_DOUBLE(w);
     420
     421    else if (!Py_IS_FINITE(i)) {
     422        if (PyInt_Check(w) || PyLong_Check(w))
     423            /* If i is an infinity, its magnitude exceeds any
     424            * finite integer, so it doesn't matter which int we
     425            * compare i with.  If i is a NaN, similarly.
     426            */
     427            j = 0.0;
     428        else
     429            goto Unimplemented;
     430    }
     431
     432    else if (PyInt_Check(w)) {
     433        long jj = PyInt_AS_LONG(w);
     434        /* In the worst realistic case I can imagine, C double is a
     435        * Cray single with 48 bits of precision, and long has 64
     436        * bits.
     437        */
    554438#if SIZEOF_LONG > 6
    555                 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
    556                 if (abs >> 48) {
    557                         /* Needs more than 48 bits.  Make it take the
    558                         * PyLong path.
    559                         */
    560                         PyObject *result;
    561                         PyObject *ww = PyLong_FromLong(jj);
    562 
    563                         if (ww == NULL)
    564                                 return NULL;
    565                         result = float_richcompare(v, ww, op);
    566                         Py_DECREF(ww);
    567                         return result;
    568                 }
     439        unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
     440        if (abs >> 48) {
     441            /* Needs more than 48 bits.  Make it take the
     442            * PyLong path.
     443            */
     444            PyObject *result;
     445            PyObject *ww = PyLong_FromLong(jj);
     446
     447            if (ww == NULL)
     448                return NULL;
     449            result = float_richcompare(v, ww, op);
     450            Py_DECREF(ww);
     451            return result;
     452        }
    569453#endif
    570                 j = (double)jj;
    571                 assert((long)j == jj);
    572         }
    573 
    574         else if (PyLong_Check(w)) {
    575                 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
    576                 int wsign = _PyLong_Sign(w);
    577                 size_t nbits;
    578                 int exponent;
    579 
    580                 if (vsign != wsign) {
    581                         /* Magnitudes are irrelevant -- the signs alone
    582                         * determine the outcome.
    583                         */
    584                         i = (double)vsign;
    585                         j = (double)wsign;
    586                         goto Compare;
    587                 }
    588                 /* The signs are the same. */
    589                 /* Convert w to a double if it fits.  In particular, 0 fits. */
    590                 nbits = _PyLong_NumBits(w);
    591                 if (nbits == (size_t)-1 && PyErr_Occurred()) {
    592                         /* This long is so large that size_t isn't big enough
    593                         * to hold the # of bits.  Replace with little doubles
    594                         * that give the same outcome -- w is so large that
    595                         * its magnitude must exceed the magnitude of any
    596                         * finite float.
    597                         */
    598                         PyErr_Clear();
    599                         i = (double)vsign;
    600                         assert(wsign != 0);
    601                         j = wsign * 2.0;
    602                         goto Compare;
    603                 }
    604                 if (nbits <= 48) {
    605                         j = PyLong_AsDouble(w);
    606                         /* It's impossible that <= 48 bits overflowed. */
    607                         assert(j != -1.0 || ! PyErr_Occurred());
    608                         goto Compare;
    609                 }
    610                 assert(wsign != 0); /* else nbits was 0 */
    611                 assert(vsign != 0); /* if vsign were 0, then since wsign is
    612                                      * not 0, we would have taken the
    613                                      * vsign != wsign branch at the start */
    614                 /* We want to work with non-negative numbers. */
    615                 if (vsign < 0) {
    616                         /* "Multiply both sides" by -1; this also swaps the
    617                         * comparator.
    618                         */
    619                         i = -i;
    620                         op = _Py_SwappedOp[op];
    621                 }
    622                 assert(i > 0.0);
    623                 (void) frexp(i, &exponent);
    624                 /* exponent is the # of bits in v before the radix point;
    625                 * we know that nbits (the # of bits in w) > 48 at this point
    626                 */
    627                 if (exponent < 0 || (size_t)exponent < nbits) {
    628                         i = 1.0;
    629                         j = 2.0;
    630                         goto Compare;
    631                 }
    632                 if ((size_t)exponent > nbits) {
    633                         i = 2.0;
    634                         j = 1.0;
    635                         goto Compare;
    636                 }
    637                 /* v and w have the same number of bits before the radix
    638                 * point.  Construct two longs that have the same comparison
    639                 * outcome.
    640                 */
    641                 {
    642                         double fracpart;
    643                         double intpart;
    644                         PyObject *result = NULL;
    645                         PyObject *one = NULL;
    646                         PyObject *vv = NULL;
    647                         PyObject *ww = w;
    648 
    649                         if (wsign < 0) {
    650                                 ww = PyNumber_Negative(w);
    651                                 if (ww == NULL)
    652                                         goto Error;
    653                         }
    654                         else
    655                                 Py_INCREF(ww);
    656 
    657                         fracpart = modf(i, &intpart);
    658                         vv = PyLong_FromDouble(intpart);
    659                         if (vv == NULL)
    660                                 goto Error;
    661 
    662                         if (fracpart != 0.0) {
    663                                 /* Shift left, and or a 1 bit into vv
    664                                 * to represent the lost fraction.
    665                                 */
    666                                 PyObject *temp;
    667 
    668                                 one = PyInt_FromLong(1);
    669                                 if (one == NULL)
    670                                         goto Error;
    671 
    672                                 temp = PyNumber_Lshift(ww, one);
    673                                 if (temp == NULL)
    674                                         goto Error;
    675                                 Py_DECREF(ww);
    676                                 ww = temp;
    677 
    678                                 temp = PyNumber_Lshift(vv, one);
    679                                 if (temp == NULL)
    680                                         goto Error;
    681                                 Py_DECREF(vv);
    682                                 vv = temp;
    683 
    684                                 temp = PyNumber_Or(vv, one);
    685                                 if (temp == NULL)
    686                                         goto Error;
    687                                 Py_DECREF(vv);
    688                                 vv = temp;
    689                         }
    690 
    691                         r = PyObject_RichCompareBool(vv, ww, op);
    692                         if (r < 0)
    693                                 goto Error;
    694                         result = PyBool_FromLong(r);
    695                  Error:
    696                         Py_XDECREF(vv);
    697                         Py_XDECREF(ww);
    698                         Py_XDECREF(one);
    699                         return result;
    700                 }
    701         } /* else if (PyLong_Check(w)) */
    702 
    703         else    /* w isn't float, int, or long */
    704                 goto Unimplemented;
     454        j = (double)jj;
     455        assert((long)j == jj);
     456    }
     457
     458    else if (PyLong_Check(w)) {
     459        int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
     460        int wsign = _PyLong_Sign(w);
     461        size_t nbits;
     462        int exponent;
     463
     464        if (vsign != wsign) {
     465            /* Magnitudes are irrelevant -- the signs alone
     466            * determine the outcome.
     467            */
     468            i = (double)vsign;
     469            j = (double)wsign;
     470            goto Compare;
     471        }
     472        /* The signs are the same. */
     473        /* Convert w to a double if it fits.  In particular, 0 fits. */
     474        nbits = _PyLong_NumBits(w);
     475        if (nbits == (size_t)-1 && PyErr_Occurred()) {
     476            /* This long is so large that size_t isn't big enough
     477            * to hold the # of bits.  Replace with little doubles
     478            * that give the same outcome -- w is so large that
     479            * its magnitude must exceed the magnitude of any
     480            * finite float.
     481            */
     482            PyErr_Clear();
     483            i = (double)vsign;
     484            assert(wsign != 0);
     485            j = wsign * 2.0;
     486            goto Compare;
     487        }
     488        if (nbits <= 48) {
     489            j = PyLong_AsDouble(w);
     490            /* It's impossible that <= 48 bits overflowed. */
     491            assert(j != -1.0 || ! PyErr_Occurred());
     492            goto Compare;
     493        }
     494        assert(wsign != 0); /* else nbits was 0 */
     495        assert(vsign != 0); /* if vsign were 0, then since wsign is
     496                             * not 0, we would have taken the
     497                             * vsign != wsign branch at the start */
     498        /* We want to work with non-negative numbers. */
     499        if (vsign < 0) {
     500            /* "Multiply both sides" by -1; this also swaps the
     501            * comparator.
     502            */
     503            i = -i;
     504            op = _Py_SwappedOp[op];
     505        }
     506        assert(i > 0.0);
     507        (void) frexp(i, &exponent);
     508        /* exponent is the # of bits in v before the radix point;
     509        * we know that nbits (the # of bits in w) > 48 at this point
     510        */
     511        if (exponent < 0 || (size_t)exponent < nbits) {
     512            i = 1.0;
     513            j = 2.0;
     514            goto Compare;
     515        }
     516        if ((size_t)exponent > nbits) {
     517            i = 2.0;
     518            j = 1.0;
     519            goto Compare;
     520        }
     521        /* v and w have the same number of bits before the radix
     522        * point.  Construct two longs that have the same comparison
     523        * outcome.
     524        */
     525        {
     526            double fracpart;
     527            double intpart;
     528            PyObject *result = NULL;
     529            PyObject *one = NULL;
     530            PyObject *vv = NULL;
     531            PyObject *ww = w;
     532
     533            if (wsign < 0) {
     534                ww = PyNumber_Negative(w);
     535                if (ww == NULL)
     536                    goto Error;
     537            }
     538            else
     539                Py_INCREF(ww);
     540
     541            fracpart = modf(i, &intpart);
     542            vv = PyLong_FromDouble(intpart);
     543            if (vv == NULL)
     544                goto Error;
     545
     546            if (fracpart != 0.0) {
     547                /* Shift left, and or a 1 bit into vv
     548                * to represent the lost fraction.
     549                */
     550                PyObject *temp;
     551
     552                one = PyInt_FromLong(1);
     553                if (one == NULL)
     554                    goto Error;
     555
     556                temp = PyNumber_Lshift(ww, one);
     557                if (temp == NULL)
     558                    goto Error;
     559                Py_DECREF(ww);
     560                ww = temp;
     561
     562                temp = PyNumber_Lshift(vv, one);
     563                if (temp == NULL)
     564                    goto Error;
     565                Py_DECREF(vv);
     566                vv = temp;
     567
     568                temp = PyNumber_Or(vv, one);
     569                if (temp == NULL)
     570                    goto Error;
     571                Py_DECREF(vv);
     572                vv = temp;
     573            }
     574
     575            r = PyObject_RichCompareBool(vv, ww, op);
     576            if (r < 0)
     577                goto Error;
     578            result = PyBool_FromLong(r);
     579         Error:
     580            Py_XDECREF(vv);
     581            Py_XDECREF(ww);
     582            Py_XDECREF(one);
     583            return result;
     584        }
     585    } /* else if (PyLong_Check(w)) */
     586
     587    else        /* w isn't float, int, or long */
     588        goto Unimplemented;
    705589
    706590 Compare:
    707         PyFPE_START_PROTECT("richcompare", return NULL)
    708         switch (op) {
    709         case Py_EQ:
    710                 r = i == j;
    711                 break;
    712         case Py_NE:
    713                 r = i != j;
    714                 break;
    715         case Py_LE:
    716                 r = i <= j;
    717                 break;
    718         case Py_GE:
    719                 r = i >= j;
    720                 break;
    721         case Py_LT:
    722                 r = i < j;
    723                 break;
    724         case Py_GT:
    725                 r = i > j;
    726                 break;
    727         }
    728         PyFPE_END_PROTECT(r)
    729         return PyBool_FromLong(r);
     591    PyFPE_START_PROTECT("richcompare", return NULL)
     592    switch (op) {
     593    case Py_EQ:
     594        r = i == j;
     595        break;
     596    case Py_NE:
     597        r = i != j;
     598        break;
     599    case Py_LE:
     600        r = i <= j;
     601        break;
     602    case Py_GE:
     603        r = i >= j;
     604        break;
     605    case Py_LT:
     606        r = i < j;
     607        break;
     608    case Py_GT:
     609        r = i > j;
     610        break;
     611    }
     612    PyFPE_END_PROTECT(r)
     613    return PyBool_FromLong(r);
    730614
    731615 Unimplemented:
    732         Py_INCREF(Py_NotImplemented);
    733         return Py_NotImplemented;
     616    Py_INCREF(Py_NotImplemented);
     617    return Py_NotImplemented;
    734618}
    735619
     
    737621float_hash(PyFloatObject *v)
    738622{
    739         return _Py_HashDouble(v->ob_fval);
     623    return _Py_HashDouble(v->ob_fval);
    740624}
    741625
     
    743627float_add(PyObject *v, PyObject *w)
    744628{
    745         double a,b;
    746         CONVERT_TO_DOUBLE(v, a);
    747         CONVERT_TO_DOUBLE(w, b);
    748         PyFPE_START_PROTECT("add", return 0)
    749         a = a + b;
    750         PyFPE_END_PROTECT(a)
    751         return PyFloat_FromDouble(a);
     629    double a,b;
     630    CONVERT_TO_DOUBLE(v, a);
     631    CONVERT_TO_DOUBLE(w, b);
     632    PyFPE_START_PROTECT("add", return 0)
     633    a = a + b;
     634    PyFPE_END_PROTECT(a)
     635    return PyFloat_FromDouble(a);
    752636}
    753637
     
    755639float_sub(PyObject *v, PyObject *w)
    756640{
    757         double a,b;
    758         CONVERT_TO_DOUBLE(v, a);
    759         CONVERT_TO_DOUBLE(w, b);
    760         PyFPE_START_PROTECT("subtract", return 0)
    761         a = a - b;
    762         PyFPE_END_PROTECT(a)
    763         return PyFloat_FromDouble(a);
     641    double a,b;
     642    CONVERT_TO_DOUBLE(v, a);
     643    CONVERT_TO_DOUBLE(w, b);
     644    PyFPE_START_PROTECT("subtract", return 0)
     645    a = a - b;
     646    PyFPE_END_PROTECT(a)
     647    return PyFloat_FromDouble(a);
    764648}
    765649
     
    767651float_mul(PyObject *v, PyObject *w)
    768652{
    769         double a,b;
    770         CONVERT_TO_DOUBLE(v, a);
    771         CONVERT_TO_DOUBLE(w, b);
    772         PyFPE_START_PROTECT("multiply", return 0)
    773         a = a * b;
    774         PyFPE_END_PROTECT(a)
    775         return PyFloat_FromDouble(a);
     653    double a,b;
     654    CONVERT_TO_DOUBLE(v, a);
     655    CONVERT_TO_DOUBLE(w, b);
     656    PyFPE_START_PROTECT("multiply", return 0)
     657    a = a * b;
     658    PyFPE_END_PROTECT(a)
     659    return PyFloat_FromDouble(a);
    776660}
    777661
     
    779663float_div(PyObject *v, PyObject *w)
    780664{
    781         double a,b;
    782         CONVERT_TO_DOUBLE(v, a);
    783         CONVERT_TO_DOUBLE(w, b);
     665    double a,b;
     666    CONVERT_TO_DOUBLE(v, a);
     667    CONVERT_TO_DOUBLE(w, b);
    784668#ifdef Py_NAN
    785         if (b == 0.0) {
    786                 PyErr_SetString(PyExc_ZeroDivisionError,
    787                                 "float division");
    788                 return NULL;
    789         }
     669    if (b == 0.0) {
     670        PyErr_SetString(PyExc_ZeroDivisionError,
     671                        "float division by zero");
     672        return NULL;
     673    }
    790674#endif
    791         PyFPE_START_PROTECT("divide", return 0)
    792         a = a / b;
    793         PyFPE_END_PROTECT(a)
    794         return PyFloat_FromDouble(a);
     675    PyFPE_START_PROTECT("divide", return 0)
     676    a = a / b;
     677    PyFPE_END_PROTECT(a)
     678    return PyFloat_FromDouble(a);
    795679}
    796680
     
    798682float_classic_div(PyObject *v, PyObject *w)
    799683{
    800         double a,b;
    801         CONVERT_TO_DOUBLE(v, a);
    802         CONVERT_TO_DOUBLE(w, b);
    803         if (Py_DivisionWarningFlag >= 2 &&
    804             PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
    805                 return NULL;
     684    double a,b;
     685    CONVERT_TO_DOUBLE(v, a);
     686    CONVERT_TO_DOUBLE(w, b);
     687    if (Py_DivisionWarningFlag >= 2 &&
     688        PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
     689        return NULL;
    806690#ifdef Py_NAN
    807         if (b == 0.0) {
    808                 PyErr_SetString(PyExc_ZeroDivisionError,
    809                                 "float division");
    810                 return NULL;
    811         }
     691    if (b == 0.0) {
     692        PyErr_SetString(PyExc_ZeroDivisionError,
     693                        "float division by zero");
     694        return NULL;
     695    }
    812696#endif
    813         PyFPE_START_PROTECT("divide", return 0)
    814         a = a / b;
    815         PyFPE_END_PROTECT(a)
    816         return PyFloat_FromDouble(a);
     697    PyFPE_START_PROTECT("divide", return 0)
     698    a = a / b;
     699    PyFPE_END_PROTECT(a)
     700    return PyFloat_FromDouble(a);
    817701}
    818702
     
    820704float_rem(PyObject *v, PyObject *w)
    821705{
    822         double vx, wx;
    823         double mod;
    824         CONVERT_TO_DOUBLE(v, vx);
    825         CONVERT_TO_DOUBLE(w, wx);
     706    double vx, wx;
     707    double mod;
     708    CONVERT_TO_DOUBLE(v, vx);
     709    CONVERT_TO_DOUBLE(w, wx);
    826710#ifdef Py_NAN
    827         if (wx == 0.0) {
    828                 PyErr_SetString(PyExc_ZeroDivisionError,
    829                                 "float modulo");
    830                 return NULL;
    831         }
     711    if (wx == 0.0) {
     712        PyErr_SetString(PyExc_ZeroDivisionError,
     713                        "float modulo");
     714        return NULL;
     715    }
    832716#endif
    833         PyFPE_START_PROTECT("modulo", return 0)
    834         mod = fmod(vx, wx);
    835         /* note: checking mod*wx < 0 is incorrect -- underflows to
    836            0 if wx < sqrt(smallest nonzero double) */
    837         if (mod && ((wx < 0) != (mod < 0))) {
    838                 mod += wx;
    839         }
    840         PyFPE_END_PROTECT(mod)
    841         return PyFloat_FromDouble(mod);
     717    PyFPE_START_PROTECT("modulo", return 0)
     718    mod = fmod(vx, wx);
     719    if (mod) {
     720        /* ensure the remainder has the same sign as the denominator */
     721        if ((wx < 0) != (mod < 0)) {
     722            mod += wx;
     723        }
     724    }
     725    else {
     726        /* the remainder is zero, and in the presence of signed zeroes
     727           fmod returns different results across platforms; ensure
     728           it has the same sign as the denominator; we'd like to do
     729           "mod = wx * 0.0", but that may get optimized away */
     730        mod *= mod;  /* hide "mod = +0" from optimizer */
     731        if (wx < 0.0)
     732            mod = -mod;
     733    }
     734    PyFPE_END_PROTECT(mod)
     735    return PyFloat_FromDouble(mod);
    842736}
    843737
     
    845739float_divmod(PyObject *v, PyObject *w)
    846740{
    847         double vx, wx;
    848         double div, mod, floordiv;
    849         CONVERT_TO_DOUBLE(v, vx);
    850         CONVERT_TO_DOUBLE(w, wx);
    851         if (wx == 0.0) {
    852                 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
    853                 return NULL;
    854         }
    855         PyFPE_START_PROTECT("divmod", return 0)
    856         mod = fmod(vx, wx);
    857         /* fmod is typically exact, so vx-mod is *mathematically* an
    858            exact multiple of wx.  But this is fp arithmetic, and fp
    859            vx - mod is an approximation; the result is that div may
    860            not be an exact integral value after the division, although
    861            it will always be very close to one.
    862         */
    863         div = (vx - mod) / wx;
    864         if (mod) {
    865                 /* ensure the remainder has the same sign as the denominator */
    866                 if ((wx < 0) != (mod < 0)) {
    867                         mod += wx;
    868                         div -= 1.0;
    869                 }
    870         }
    871         else {
    872                 /* the remainder is zero, and in the presence of signed zeroes
    873                    fmod returns different results across platforms; ensure
    874                    it has the same sign as the denominator; we'd like to do
    875                    "mod = wx * 0.0", but that may get optimized away */
    876                 mod *= mod;  /* hide "mod = +0" from optimizer */
    877                 if (wx < 0.0)
    878                         mod = -mod;
    879         }
    880         /* snap quotient to nearest integral value */
    881         if (div) {
    882                 floordiv = floor(div);
    883                 if (div - floordiv > 0.5)
    884                         floordiv += 1.0;
    885         }
    886         else {
    887                 /* div is zero - get the same sign as the true quotient */
    888                 div *= div;     /* hide "div = +0" from optimizers */
    889                 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
    890         }
    891         PyFPE_END_PROTECT(floordiv)
    892         return Py_BuildValue("(dd)", floordiv, mod);
     741    double vx, wx;
     742    double div, mod, floordiv;
     743    CONVERT_TO_DOUBLE(v, vx);
     744    CONVERT_TO_DOUBLE(w, wx);
     745    if (wx == 0.0) {
     746        PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
     747        return NULL;
     748    }
     749    PyFPE_START_PROTECT("divmod", return 0)
     750    mod = fmod(vx, wx);
     751    /* fmod is typically exact, so vx-mod is *mathematically* an
     752       exact multiple of wx.  But this is fp arithmetic, and fp
     753       vx - mod is an approximation; the result is that div may
     754       not be an exact integral value after the division, although
     755       it will always be very close to one.
     756    */
     757    div = (vx - mod) / wx;
     758    if (mod) {
     759        /* ensure the remainder has the same sign as the denominator */
     760        if ((wx < 0) != (mod < 0)) {
     761            mod += wx;
     762            div -= 1.0;
     763        }
     764    }
     765    else {
     766        /* the remainder is zero, and in the presence of signed zeroes
     767           fmod returns different results across platforms; ensure
     768           it has the same sign as the denominator; we'd like to do
     769           "mod = wx * 0.0", but that may get optimized away */
     770        mod *= mod;  /* hide "mod = +0" from optimizer */
     771        if (wx < 0.0)
     772            mod = -mod;
     773    }
     774    /* snap quotient to nearest integral value */
     775    if (div) {
     776        floordiv = floor(div);
     777        if (div - floordiv > 0.5)
     778            floordiv += 1.0;
     779    }
     780    else {
     781        /* div is zero - get the same sign as the true quotient */
     782        div *= div;             /* hide "div = +0" from optimizers */
     783        floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
     784    }
     785    PyFPE_END_PROTECT(floordiv)
     786    return Py_BuildValue("(dd)", floordiv, mod);
    893787}
    894788
     
    896790float_floor_div(PyObject *v, PyObject *w)
    897791{
    898         PyObject *t, *r;
    899 
    900         t = float_divmod(v, w);
    901         if (t == NULL || t == Py_NotImplemented)
    902                 return t;
    903         assert(PyTuple_CheckExact(t));
    904         r = PyTuple_GET_ITEM(t, 0);
    905         Py_INCREF(r);
    906         Py_DECREF(t);
    907         return r;
    908 }
     792    PyObject *t, *r;
     793
     794    t = float_divmod(v, w);
     795    if (t == NULL || t == Py_NotImplemented)
     796        return t;
     797    assert(PyTuple_CheckExact(t));
     798    r = PyTuple_GET_ITEM(t, 0);
     799    Py_INCREF(r);
     800    Py_DECREF(t);
     801    return r;
     802}
     803
     804/* determine whether x is an odd integer or not;  assumes that
     805   x is not an infinity or nan. */
     806#define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)
    909807
    910808static PyObject *
    911809float_pow(PyObject *v, PyObject *w, PyObject *z)
    912810{
    913         double iv, iw, ix;
    914 
    915         if ((PyObject *)z != Py_None) {
    916                 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
    917                         "allowed unless all arguments are integers");
    918                 return NULL;
    919         }
    920 
    921         CONVERT_TO_DOUBLE(v, iv);
    922         CONVERT_TO_DOUBLE(w, iw);
    923 
    924         /* Sort out special cases here instead of relying on pow() */
    925         if (iw == 0) {          /* v**0 is 1, even 0**0 */
    926                 return PyFloat_FromDouble(1.0);
    927         }
    928         if (iv == 0.0) {  /* 0**w is error if w<0, else 1 */
    929                 if (iw < 0.0) {
    930                         PyErr_SetString(PyExc_ZeroDivisionError,
    931                                         "0.0 cannot be raised to a negative power");
    932                         return NULL;
    933                 }
    934                 return PyFloat_FromDouble(0.0);
    935         }
    936         if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
    937                 return PyFloat_FromDouble(1.0);
    938         }
    939         if (iv < 0.0) {
    940                 /* Whether this is an error is a mess, and bumps into libm
    941                  * bugs so we have to figure it out ourselves.
    942                  */
    943                 if (iw != floor(iw)) {
    944                         PyErr_SetString(PyExc_ValueError, "negative number "
    945                                 "cannot be raised to a fractional power");
    946                         return NULL;
    947                 }
    948                 /* iw is an exact integer, albeit perhaps a very large one.
    949                  * -1 raised to an exact integer should never be exceptional.
    950                  * Alas, some libms (chiefly glibc as of early 2003) return
    951                  * NaN and set EDOM on pow(-1, large_int) if the int doesn't
    952                  * happen to be representable in a *C* integer.  That's a
    953                  * bug; we let that slide in math.pow() (which currently
    954                  * reflects all platform accidents), but not for Python's **.
    955                  */
    956                  if (iv == -1.0 && Py_IS_FINITE(iw)) {
    957                         /* Return 1 if iw is even, -1 if iw is odd; there's
    958                          * no guarantee that any C integral type is big
    959                          * enough to hold iw, so we have to check this
    960                          * indirectly.
    961                          */
    962                         ix = floor(iw * 0.5) * 2.0;
    963                         return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
    964                 }
    965                 /* Else iv != -1.0, and overflow or underflow are possible.
    966                  * Unless we're to write pow() ourselves, we have to trust
    967                  * the platform to do this correctly.
    968                  */
    969         }
    970         errno = 0;
    971         PyFPE_START_PROTECT("pow", return NULL)
    972         ix = pow(iv, iw);
    973         PyFPE_END_PROTECT(ix)
    974         Py_ADJUST_ERANGE1(ix);
    975         if (errno != 0) {
    976                 /* We don't expect any errno value other than ERANGE, but
    977                  * the range of libm bugs appears unbounded.
    978                  */
    979                 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
    980                                                      PyExc_ValueError);
    981                 return NULL;
    982         }
    983         return PyFloat_FromDouble(ix);
    984 }
     811    double iv, iw, ix;
     812    int negate_result = 0;
     813
     814    if ((PyObject *)z != Py_None) {
     815        PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
     816            "allowed unless all arguments are integers");
     817        return NULL;
     818    }
     819
     820    CONVERT_TO_DOUBLE(v, iv);
     821    CONVERT_TO_DOUBLE(w, iw);
     822
     823    /* Sort out special cases here instead of relying on pow() */
     824    if (iw == 0) {              /* v**0 is 1, even 0**0 */
     825        return PyFloat_FromDouble(1.0);
     826    }
     827    if (Py_IS_NAN(iv)) {        /* nan**w = nan, unless w == 0 */
     828        return PyFloat_FromDouble(iv);
     829    }
     830    if (Py_IS_NAN(iw)) {        /* v**nan = nan, unless v == 1; 1**nan = 1 */
     831        return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
     832    }
     833    if (Py_IS_INFINITY(iw)) {
     834        /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
     835         *     abs(v) > 1 (including case where v infinite)
     836         *
     837         * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
     838         *     abs(v) > 1 (including case where v infinite)
     839         */
     840        iv = fabs(iv);
     841        if (iv == 1.0)
     842            return PyFloat_FromDouble(1.0);
     843        else if ((iw > 0.0) == (iv > 1.0))
     844            return PyFloat_FromDouble(fabs(iw)); /* return inf */
     845        else
     846            return PyFloat_FromDouble(0.0);
     847    }
     848    if (Py_IS_INFINITY(iv)) {
     849        /* (+-inf)**w is: inf for w positive, 0 for w negative; in
     850         *     both cases, we need to add the appropriate sign if w is
     851         *     an odd integer.
     852         */
     853        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
     854        if (iw > 0.0)
     855            return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
     856        else
     857            return PyFloat_FromDouble(iw_is_odd ?
     858                                      copysign(0.0, iv) : 0.0);
     859    }
     860    if (iv == 0.0) {  /* 0**w is: 0 for w positive, 1 for w zero
     861                         (already dealt with above), and an error
     862                         if w is negative. */
     863        int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
     864        if (iw < 0.0) {
     865            PyErr_SetString(PyExc_ZeroDivisionError,
     866                            "0.0 cannot be raised to a "
     867                            "negative power");
     868            return NULL;
     869        }
     870        /* use correct sign if iw is odd */
     871        return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
     872    }
     873
     874    if (iv < 0.0) {
     875        /* Whether this is an error is a mess, and bumps into libm
     876         * bugs so we have to figure it out ourselves.
     877         */
     878        if (iw != floor(iw)) {
     879            PyErr_SetString(PyExc_ValueError, "negative number "
     880                "cannot be raised to a fractional power");
     881            return NULL;
     882        }
     883        /* iw is an exact integer, albeit perhaps a very large
     884         * one.  Replace iv by its absolute value and remember
     885         * to negate the pow result if iw is odd.
     886         */
     887        iv = -iv;
     888        negate_result = DOUBLE_IS_ODD_INTEGER(iw);
     889    }
     890
     891    if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
     892        /* (-1) ** large_integer also ends up here.  Here's an
     893         * extract from the comments for the previous
     894         * implementation explaining why this special case is
     895         * necessary:
     896         *
     897         * -1 raised to an exact integer should never be exceptional.
     898         * Alas, some libms (chiefly glibc as of early 2003) return
     899         * NaN and set EDOM on pow(-1, large_int) if the int doesn't
     900         * happen to be representable in a *C* integer.  That's a
     901         * bug.
     902         */
     903        return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
     904    }
     905
     906    /* Now iv and iw are finite, iw is nonzero, and iv is
     907     * positive and not equal to 1.0.  We finally allow
     908     * the platform pow to step in and do the rest.
     909     */
     910    errno = 0;
     911    PyFPE_START_PROTECT("pow", return NULL)
     912    ix = pow(iv, iw);
     913    PyFPE_END_PROTECT(ix)
     914    Py_ADJUST_ERANGE1(ix);
     915    if (negate_result)
     916        ix = -ix;
     917
     918    if (errno != 0) {
     919        /* We don't expect any errno value other than ERANGE, but
     920         * the range of libm bugs appears unbounded.
     921         */
     922        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
     923                             PyExc_ValueError);
     924        return NULL;
     925    }
     926    return PyFloat_FromDouble(ix);
     927}
     928
     929#undef DOUBLE_IS_ODD_INTEGER
    985930
    986931static PyObject *
    987932float_neg(PyFloatObject *v)
    988933{
    989         return PyFloat_FromDouble(-v->ob_fval);
     934    return PyFloat_FromDouble(-v->ob_fval);
    990935}
    991936
     
    993938float_abs(PyFloatObject *v)
    994939{
    995         return PyFloat_FromDouble(fabs(v->ob_fval));
     940    return PyFloat_FromDouble(fabs(v->ob_fval));
    996941}
    997942
     
    999944float_nonzero(PyFloatObject *v)
    1000945{
    1001         return v->ob_fval != 0.0;
     946    return v->ob_fval != 0.0;
    1002947}
    1003948
     
    1005950float_coerce(PyObject **pv, PyObject **pw)
    1006951{
    1007         if (PyInt_Check(*pw)) {
    1008                 long x = PyInt_AsLong(*pw);
    1009                 *pw = PyFloat_FromDouble((double)x);
    1010                 Py_INCREF(*pv);
    1011                 return 0;
    1012         }
    1013         else if (PyLong_Check(*pw)) {
    1014                 double x = PyLong_AsDouble(*pw);
    1015                 if (x == -1.0 && PyErr_Occurred())
    1016                         return -1;
    1017                 *pw = PyFloat_FromDouble(x);
    1018                 Py_INCREF(*pv);
    1019                 return 0;
    1020         }
    1021         else if (PyFloat_Check(*pw)) {
    1022                 Py_INCREF(*pv);
    1023                 Py_INCREF(*pw);
    1024                 return 0;
    1025         }
    1026         return 1; /* Can't do it */
     952    if (PyInt_Check(*pw)) {
     953        long x = PyInt_AsLong(*pw);
     954        *pw = PyFloat_FromDouble((double)x);
     955        Py_INCREF(*pv);
     956        return 0;
     957    }
     958    else if (PyLong_Check(*pw)) {
     959        double x = PyLong_AsDouble(*pw);
     960        if (x == -1.0 && PyErr_Occurred())
     961            return -1;
     962        *pw = PyFloat_FromDouble(x);
     963        Py_INCREF(*pv);
     964        return 0;
     965    }
     966    else if (PyFloat_Check(*pw)) {
     967        Py_INCREF(*pv);
     968        Py_INCREF(*pw);
     969        return 0;
     970    }
     971    return 1; /* Can't do it */
    1027972}
    1028973
     
    1030975float_is_integer(PyObject *v)
    1031976{
    1032         double x = PyFloat_AsDouble(v);
    1033         PyObject *o;
    1034        
    1035         if (x == -1.0 && PyErr_Occurred())
    1036                 return NULL;
    1037         if (!Py_IS_FINITE(x))
    1038                 Py_RETURN_FALSE;
    1039         errno = 0;
    1040         PyFPE_START_PROTECT("is_integer", return NULL)
    1041         o = (floor(x) == x) ? Py_True : Py_False;
    1042         PyFPE_END_PROTECT(x)
    1043         if (errno != 0) {
    1044                 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
    1045                                                      PyExc_ValueError);
    1046                 return NULL;
    1047         }
    1048         Py_INCREF(o);
    1049         return o;
     977    double x = PyFloat_AsDouble(v);
     978    PyObject *o;
     979
     980    if (x == -1.0 && PyErr_Occurred())
     981        return NULL;
     982    if (!Py_IS_FINITE(x))
     983        Py_RETURN_FALSE;
     984    errno = 0;
     985    PyFPE_START_PROTECT("is_integer", return NULL)
     986    o = (floor(x) == x) ? Py_True : Py_False;
     987    PyFPE_END_PROTECT(x)
     988    if (errno != 0) {
     989        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
     990                             PyExc_ValueError);
     991        return NULL;
     992    }
     993    Py_INCREF(o);
     994    return o;
    1050995}
    1051996
     
    1054999float_is_inf(PyObject *v)
    10551000{
    1056         double x = PyFloat_AsDouble(v);
    1057         if (x == -1.0 && PyErr_Occurred())
    1058                 return NULL;
    1059         return PyBool_FromLong((long)Py_IS_INFINITY(x));
     1001    double x = PyFloat_AsDouble(v);
     1002    if (x == -1.0 && PyErr_Occurred())
     1003        return NULL;
     1004    return PyBool_FromLong((long)Py_IS_INFINITY(x));
    10601005}
    10611006
     
    10631008float_is_nan(PyObject *v)
    10641009{
    1065         double x = PyFloat_AsDouble(v);
    1066         if (x == -1.0 && PyErr_Occurred())
    1067                 return NULL;
    1068         return PyBool_FromLong((long)Py_IS_NAN(x));
     1010    double x = PyFloat_AsDouble(v);
     1011    if (x == -1.0 && PyErr_Occurred())
     1012        return NULL;
     1013    return PyBool_FromLong((long)Py_IS_NAN(x));
    10691014}
    10701015
     
    10721017float_is_finite(PyObject *v)
    10731018{
    1074         double x = PyFloat_AsDouble(v);
    1075         if (x == -1.0 && PyErr_Occurred())
    1076                 return NULL;
    1077         return PyBool_FromLong((long)Py_IS_FINITE(x));
     1019    double x = PyFloat_AsDouble(v);
     1020    if (x == -1.0 && PyErr_Occurred())
     1021        return NULL;
     1022    return PyBool_FromLong((long)Py_IS_FINITE(x));
    10781023}
    10791024#endif
     
    10821027float_trunc(PyObject *v)
    10831028{
    1084         double x = PyFloat_AsDouble(v);
    1085         double wholepart;       /* integral portion of x, rounded toward 0 */
    1086 
    1087         (void)modf(x, &wholepart);
    1088         /* Try to get out cheap if this fits in a Python int.  The attempt
    1089          * to cast to long must be protected, as C doesn't define what
    1090          * happens if the double is too big to fit in a long.  Some rare
    1091          * systems raise an exception then (RISCOS was mentioned as one,
    1092          * and someone using a non-default option on Sun also bumped into
    1093          * that).  Note that checking for >= and <= LONG_{MIN,MAX} would
    1094          * still be vulnerable:  if a long has more bits of precision than
    1095          * a double, casting MIN/MAX to double may yield an approximation,
    1096          * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
    1097          * yield true from the C expression wholepart<=LONG_MAX, despite
    1098          * that wholepart is actually greater than LONG_MAX.
    1099          */
    1100         if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
    1101                 const long aslong = (long)wholepart;
    1102                 return PyInt_FromLong(aslong);
    1103         }
    1104         return PyLong_FromDouble(wholepart);
     1029    double x = PyFloat_AsDouble(v);
     1030    double wholepart;           /* integral portion of x, rounded toward 0 */
     1031
     1032    (void)modf(x, &wholepart);
     1033    /* Try to get out cheap if this fits in a Python int.  The attempt
     1034     * to cast to long must be protected, as C doesn't define what
     1035     * happens if the double is too big to fit in a long.  Some rare
     1036     * systems raise an exception then (RISCOS was mentioned as one,
     1037     * and someone using a non-default option on Sun also bumped into
     1038     * that).  Note that checking for <= LONG_MAX is unsafe: if a long
     1039     * has more bits of precision than a double, casting LONG_MAX to
     1040     * double may yield an approximation, and if that's rounded up,
     1041     * then, e.g., wholepart=LONG_MAX+1 would yield true from the C
     1042     * expression wholepart<=LONG_MAX, despite that wholepart is
     1043     * actually greater than LONG_MAX.  However, assuming a two's complement
     1044     * machine with no trap representation, LONG_MIN will be a power of 2 (and
     1045     * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so
     1046     * the comparisons with (double)LONG_MIN below should be safe.
     1047     */
     1048    if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {
     1049        const long aslong = (long)wholepart;
     1050        return PyInt_FromLong(aslong);
     1051    }
     1052    return PyLong_FromDouble(wholepart);
    11051053}
    11061054
     
    11081056float_long(PyObject *v)
    11091057{
    1110         double x = PyFloat_AsDouble(v);
    1111         return PyLong_FromDouble(x);
    1112 }
     1058    double x = PyFloat_AsDouble(v);
     1059    return PyLong_FromDouble(x);
     1060}
     1061
     1062/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
     1063   10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=
     1064   ndigits <= 323).  Returns a Python float, or sets a Python error and
     1065   returns NULL on failure (OverflowError and memory errors are possible). */
     1066
     1067#ifndef PY_NO_SHORT_FLOAT_REPR
     1068/* version of _Py_double_round that uses the correctly-rounded string<->double
     1069   conversions from Python/dtoa.c */
     1070
     1071/* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as
     1072   a double.  Since we're using the code in Python/dtoa.c, it should be safe
     1073   to assume that C doubles are IEEE 754 binary64 format.  To be on the safe
     1074   side, we check this. */
     1075#if DBL_MANT_DIG == 53
     1076#define FIVE_POW_LIMIT 22
     1077#else
     1078#error "C doubles do not appear to be IEEE 754 binary64 format"
     1079#endif
     1080
     1081PyObject *
     1082_Py_double_round(double x, int ndigits) {
     1083
     1084    double rounded, m;
     1085    Py_ssize_t buflen, mybuflen=100;
     1086    char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
     1087    int decpt, sign, val, halfway_case;
     1088    PyObject *result = NULL;
     1089    _Py_SET_53BIT_PRECISION_HEADER;
     1090
     1091    /* Easy path for the common case ndigits == 0. */
     1092    if (ndigits == 0) {
     1093        rounded = round(x);
     1094        if (fabs(rounded - x) == 0.5)
     1095            /* halfway between two integers; use round-away-from-zero */
     1096            rounded = x + (x > 0.0 ? 0.5 : -0.5);
     1097        return PyFloat_FromDouble(rounded);
     1098    }
     1099
     1100    /* The basic idea is very simple: convert and round the double to a
     1101       decimal string using _Py_dg_dtoa, then convert that decimal string
     1102       back to a double with _Py_dg_strtod.  There's one minor difficulty:
     1103       Python 2.x expects round to do round-half-away-from-zero, while
     1104       _Py_dg_dtoa does round-half-to-even.  So we need some way to detect
     1105       and correct the halfway cases.
     1106
     1107       Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
     1108       some odd integer k.  Or in other words, a rational number x is
     1109       exactly halfway between two multiples of 10**-ndigits if its
     1110       2-valuation is exactly -ndigits-1 and its 5-valuation is at least
     1111       -ndigits.  For ndigits >= 0 the latter condition is automatically
     1112       satisfied for a binary float x, since any such float has
     1113       nonnegative 5-valuation.  For 0 > ndigits >= -22, x needs to be an
     1114       integral multiple of 5**-ndigits; we can check this using fmod.
     1115       For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
     1116       to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
     1117       23 takes at least 54 bits of precision to represent exactly.
     1118
     1119       Correction: a simple strategy for dealing with halfway cases is to
     1120       (for the halfway cases only) call _Py_dg_dtoa with an argument of
     1121       ndigits+1 instead of ndigits (thus doing an exact conversion to
     1122       decimal), round the resulting string manually, and then convert
     1123       back using _Py_dg_strtod.
     1124    */
     1125
     1126    /* nans, infinities and zeros should have already been dealt
     1127       with by the caller (in this case, builtin_round) */
     1128    assert(Py_IS_FINITE(x) && x != 0.0);
     1129
     1130    /* find 2-valuation val of x */
     1131    m = frexp(x, &val);
     1132    while (m != floor(m)) {
     1133        m *= 2.0;
     1134        val--;
     1135    }
     1136
     1137    /* determine whether this is a halfway case */
     1138    if (val == -ndigits-1) {
     1139        if (ndigits >= 0)
     1140            halfway_case = 1;
     1141        else if (ndigits >= -FIVE_POW_LIMIT) {
     1142            double five_pow = 1.0;
     1143            int i;
     1144            for (i=0; i < -ndigits; i++)
     1145                five_pow *= 5.0;
     1146            halfway_case = fmod(x, five_pow) == 0.0;
     1147        }
     1148        else
     1149            halfway_case = 0;
     1150    }
     1151    else
     1152        halfway_case = 0;
     1153
     1154    /* round to a decimal string; use an extra place for halfway case */
     1155    _Py_SET_53BIT_PRECISION_START;
     1156    buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
     1157    _Py_SET_53BIT_PRECISION_END;
     1158    if (buf == NULL) {
     1159        PyErr_NoMemory();
     1160        return NULL;
     1161    }
     1162    buflen = buf_end - buf;
     1163
     1164    /* in halfway case, do the round-half-away-from-zero manually */
     1165    if (halfway_case) {
     1166        int i, carry;
     1167        /* sanity check: _Py_dg_dtoa should not have stripped
     1168           any zeros from the result: there should be exactly
     1169           ndigits+1 places following the decimal point, and
     1170           the last digit in the buffer should be a '5'.*/
     1171        assert(buflen - decpt == ndigits+1);
     1172        assert(buf[buflen-1] == '5');
     1173
     1174        /* increment and shift right at the same time. */
     1175        decpt += 1;
     1176        carry = 1;
     1177        for (i=buflen-1; i-- > 0;) {
     1178            carry += buf[i] - '0';
     1179            buf[i+1] = carry % 10 + '0';
     1180            carry /= 10;
     1181        }
     1182        buf[0] = carry + '0';
     1183    }
     1184
     1185    /* Get new buffer if shortbuf is too small.  Space needed <= buf_end -
     1186       buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
     1187    if (buflen + 8 > mybuflen) {
     1188        mybuflen = buflen+8;
     1189        mybuf = (char *)PyMem_Malloc(mybuflen);
     1190        if (mybuf == NULL) {
     1191            PyErr_NoMemory();
     1192            goto exit;
     1193        }
     1194    }
     1195    /* copy buf to mybuf, adding exponent, sign and leading 0 */
     1196    PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
     1197                  buf, decpt - (int)buflen);
     1198
     1199    /* and convert the resulting string back to a double */
     1200    errno = 0;
     1201    _Py_SET_53BIT_PRECISION_START;
     1202    rounded = _Py_dg_strtod(mybuf, NULL);
     1203    _Py_SET_53BIT_PRECISION_END;
     1204    if (errno == ERANGE && fabs(rounded) >= 1.)
     1205        PyErr_SetString(PyExc_OverflowError,
     1206                        "rounded value too large to represent");
     1207    else
     1208        result = PyFloat_FromDouble(rounded);
     1209
     1210    /* done computing value;  now clean up */
     1211    if (mybuf != shortbuf)
     1212        PyMem_Free(mybuf);
     1213  exit:
     1214    _Py_dg_freedtoa(buf);
     1215    return result;
     1216}
     1217
     1218#undef FIVE_POW_LIMIT
     1219
     1220#else /* PY_NO_SHORT_FLOAT_REPR */
     1221
     1222/* fallback version, to be used when correctly rounded binary<->decimal
     1223   conversions aren't available */
     1224
     1225PyObject *
     1226_Py_double_round(double x, int ndigits) {
     1227    double pow1, pow2, y, z;
     1228    if (ndigits >= 0) {
     1229        if (ndigits > 22) {
     1230            /* pow1 and pow2 are each safe from overflow, but
     1231               pow1*pow2 ~= pow(10.0, ndigits) might overflow */
     1232            pow1 = pow(10.0, (double)(ndigits-22));
     1233            pow2 = 1e22;
     1234        }
     1235        else {
     1236            pow1 = pow(10.0, (double)ndigits);
     1237            pow2 = 1.0;
     1238        }
     1239        y = (x*pow1)*pow2;
     1240        /* if y overflows, then rounded value is exactly x */
     1241        if (!Py_IS_FINITE(y))
     1242            return PyFloat_FromDouble(x);
     1243    }
     1244    else {
     1245        pow1 = pow(10.0, (double)-ndigits);
     1246        pow2 = 1.0; /* unused; silences a gcc compiler warning */
     1247        y = x / pow1;
     1248    }
     1249
     1250    z = round(y);
     1251    if (fabs(y-z) == 0.5)
     1252        /* halfway between two integers; use round-away-from-zero */
     1253        z = y + copysign(0.5, y);
     1254
     1255    if (ndigits >= 0)
     1256        z = (z / pow2) / pow1;
     1257    else
     1258        z *= pow1;
     1259
     1260    /* if computation resulted in overflow, raise OverflowError */
     1261    if (!Py_IS_FINITE(z)) {
     1262        PyErr_SetString(PyExc_OverflowError,
     1263                        "overflow occurred during round");
     1264        return NULL;
     1265    }
     1266
     1267    return PyFloat_FromDouble(z);
     1268}
     1269
     1270#endif /* PY_NO_SHORT_FLOAT_REPR */
    11131271
    11141272static PyObject *
    11151273float_float(PyObject *v)
    11161274{
    1117         if (PyFloat_CheckExact(v))
    1118                 Py_INCREF(v);
    1119         else
    1120                 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
    1121         return v;
     1275    if (PyFloat_CheckExact(v))
     1276        Py_INCREF(v);
     1277    else
     1278        v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
     1279    return v;
    11221280}
    11231281
     
    11271285char_from_hex(int x)
    11281286{
    1129         assert(0 <= x && x < 16);
    1130         return "0123456789abcdef"[x];
     1287    assert(0 <= x && x < 16);
     1288    return "0123456789abcdef"[x];
    11311289}
    11321290
    11331291static int
    11341292hex_from_char(char c) {
    1135         int x;
    1136         switch(c) {
    1137         case '0':
    1138                 x = 0;
    1139                 break;
    1140         case '1':
    1141                 x = 1;
    1142                 break;
    1143         case '2':
    1144                 x = 2;
    1145                 break;
    1146         case '3':
    1147                 x = 3;
    1148                 break;
    1149         case '4':
    1150                 x = 4;
    1151                 break;
    1152         case '5':
    1153                 x = 5;
    1154                 break;
    1155         case '6':
    1156                 x = 6;
    1157                 break;
    1158         case '7':
    1159                 x = 7;
    1160                 break;
    1161         case '8':
    1162                 x = 8;
    1163                 break;
    1164         case '9':
    1165                 x = 9;
    1166                 break;
    1167         case 'a':
    1168         case 'A':
    1169                 x = 10;
    1170                 break;
    1171         case 'b':
    1172         case 'B':
    1173                 x = 11;
    1174                 break;
    1175         case 'c':
    1176         case 'C':
    1177                 x = 12;
    1178                 break;
    1179         case 'd':
    1180         case 'D':
    1181                 x = 13;
    1182                 break;
    1183         case 'e':
    1184         case 'E':
    1185                 x = 14;
    1186                 break;
    1187         case 'f':
    1188         case 'F':
    1189                 x = 15;
    1190                 break;
    1191         default:
    1192                 x = -1;
    1193                 break;
    1194         }
    1195         return x;
     1293    int x;
     1294    switch(c) {
     1295    case '0':
     1296        x = 0;
     1297        break;
     1298    case '1':
     1299        x = 1;
     1300        break;
     1301    case '2':
     1302        x = 2;
     1303        break;
     1304    case '3':
     1305        x = 3;
     1306        break;
     1307    case '4':
     1308        x = 4;
     1309        break;
     1310    case '5':
     1311        x = 5;
     1312        break;
     1313    case '6':
     1314        x = 6;
     1315        break;
     1316    case '7':
     1317        x = 7;
     1318        break;
     1319    case '8':
     1320        x = 8;
     1321        break;
     1322    case '9':
     1323        x = 9;
     1324        break;
     1325    case 'a':
     1326    case 'A':
     1327        x = 10;
     1328        break;
     1329    case 'b':
     1330    case 'B':
     1331        x = 11;
     1332        break;
     1333    case 'c':
     1334    case 'C':
     1335        x = 12;
     1336        break;
     1337    case 'd':
     1338    case 'D':
     1339        x = 13;
     1340        break;
     1341    case 'e':
     1342    case 'E':
     1343        x = 14;
     1344        break;
     1345    case 'f':
     1346    case 'F':
     1347        x = 15;
     1348        break;
     1349    default:
     1350        x = -1;
     1351        break;
     1352    }
     1353    return x;
    11961354}
    11971355
     
    12051363float_hex(PyObject *v)
    12061364{
    1207         double x, m;
    1208         int e, shift, i, si, esign;
    1209         /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
    1210            trailing NUL byte. */
    1211         char s[(TOHEX_NBITS-1)/4+3];
    1212 
    1213         CONVERT_TO_DOUBLE(v, x);
    1214 
    1215         if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
    1216                 return float_str((PyFloatObject *)v);
    1217 
    1218         if (x == 0.0) {
    1219                 if(copysign(1.0, x) == -1.0)
    1220                         return PyString_FromString("-0x0.0p+0");
    1221                 else
    1222                         return PyString_FromString("0x0.0p+0");
    1223         }
    1224 
    1225         m = frexp(fabs(x), &e);
    1226         shift = 1 - MAX(DBL_MIN_EXP - e, 0);
    1227         m = ldexp(m, shift);
    1228         e -= shift;
    1229 
    1230         si = 0;
    1231         s[si] = char_from_hex((int)m);
    1232         si++;
    1233         m -= (int)m;
    1234         s[si] = '.';
    1235         si++;
    1236         for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
    1237                 m *= 16.0;
    1238                 s[si] = char_from_hex((int)m);
    1239                 si++;
    1240                 m -= (int)m;
    1241         }
    1242         s[si] = '\0';
    1243 
    1244         if (e < 0) {
    1245                 esign = (int)'-';
    1246                 e = -e;
    1247         }
    1248         else
    1249                 esign = (int)'+';
    1250 
    1251         if (x < 0.0)
    1252                 return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
    1253         else
    1254                 return PyString_FromFormat("0x%sp%c%d", s, esign, e);
     1365    double x, m;
     1366    int e, shift, i, si, esign;
     1367    /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
     1368       trailing NUL byte. */
     1369    char s[(TOHEX_NBITS-1)/4+3];
     1370
     1371    CONVERT_TO_DOUBLE(v, x);
     1372
     1373    if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
     1374        return float_str((PyFloatObject *)v);
     1375
     1376    if (x == 0.0) {
     1377        if (copysign(1.0, x) == -1.0)
     1378            return PyString_FromString("-0x0.0p+0");
     1379        else
     1380            return PyString_FromString("0x0.0p+0");
     1381    }
     1382
     1383    m = frexp(fabs(x), &e);
     1384    shift = 1 - MAX(DBL_MIN_EXP - e, 0);
     1385    m = ldexp(m, shift);
     1386    e -= shift;
     1387
     1388    si = 0;
     1389    s[si] = char_from_hex((int)m);
     1390    si++;
     1391    m -= (int)m;
     1392    s[si] = '.';
     1393    si++;
     1394    for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
     1395        m *= 16.0;
     1396        s[si] = char_from_hex((int)m);
     1397        si++;
     1398        m -= (int)m;
     1399    }
     1400    s[si] = '\0';
     1401
     1402    if (e < 0) {
     1403        esign = (int)'-';
     1404        e = -e;
     1405    }
     1406    else
     1407        esign = (int)'+';
     1408
     1409    if (x < 0.0)
     1410        return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
     1411    else
     1412        return PyString_FromFormat("0x%sp%c%d", s, esign, e);
    12551413}
    12561414
     
    12641422'0x1.921f9f01b866ep+1'");
    12651423
    1266 /* Case-insensitive string match used for nan and inf detection. t should be
    1267    lower-case and null-terminated.  Return a nonzero result if the first
    1268    strlen(t) characters of s match t and 0 otherwise. */
     1424/* Case-insensitive locale-independent string match used for nan and inf
     1425   detection. t should be lower-case and null-terminated.  Return a nonzero
     1426   result if the first strlen(t) characters of s match t and 0 otherwise. */
    12691427
    12701428static int
    12711429case_insensitive_match(const char *s, const char *t)
    12721430{
    1273         while(*t && tolower(*s) == *t) {
    1274                 s++;
    1275                 t++;
    1276         }
    1277         return *t ? 0 : 1;
     1431    while(*t && Py_TOLOWER(*s) == *t) {
     1432        s++;
     1433        t++;
     1434    }
     1435    return *t ? 0 : 1;
    12781436}
    12791437
     
    12831441float_fromhex(PyObject *cls, PyObject *arg)
    12841442{
    1285         PyObject *result_as_float, *result;
    1286         double x;
    1287         long exp, top_exp, lsb, key_digit;
    1288         char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
    1289         int half_eps, digit, round_up, sign=1;
    1290         Py_ssize_t length, ndigits, fdigits, i;
    1291 
    1292         /*
    1293         * For the sake of simplicity and correctness, we impose an artificial
    1294         * limit on ndigits, the total number of hex digits in the coefficient
    1295         * The limit is chosen to ensure that, writing exp for the exponent,
    1296         *
    1297         *   (1) if exp > LONG_MAX/2 then the value of the hex string is
    1298         *   guaranteed to overflow (provided it's nonzero)
    1299         *
    1300         *   (2) if exp < LONG_MIN/2 then the value of the hex string is
    1301         *   guaranteed to underflow to 0.
    1302         *
    1303         *   (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
    1304         *   overflow in the calculation of exp and top_exp below.
    1305         *
    1306         * More specifically, ndigits is assumed to satisfy the following
    1307         * inequalities:
    1308         *
    1309         *   4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
    1310         *   4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
    1311         *
    1312         * If either of these inequalities is not satisfied, a ValueError is
    1313         * raised.  Otherwise, write x for the value of the hex string, and
    1314         * assume x is nonzero.  Then
    1315         *
    1316         *   2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
    1317         *
    1318         * Now if exp > LONG_MAX/2 then:
    1319         *
    1320         *   exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
    1321         *                    = DBL_MAX_EXP
    1322         *
    1323         * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
    1324         * double, so overflows.  If exp < LONG_MIN/2, then
    1325         *
    1326         *   exp + 4*ndigits <= LONG_MIN/2 - 1 + (
    1327         *                      DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
    1328         *                    = DBL_MIN_EXP - DBL_MANT_DIG - 1
    1329         *
    1330         * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
    1331         * when converted to a C double.
    1332         *
    1333         * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
    1334         * exp+4*ndigits and exp-4*ndigits are within the range of a long.
    1335         */
    1336 
    1337         if (PyString_AsStringAndSize(arg, &s, &length))
    1338                 return NULL;
    1339         s_end = s + length;
    1340 
    1341         /********************
    1342         * Parse the string *
    1343         ********************/
    1344 
    1345         /* leading whitespace and optional sign */
    1346         while (*s && isspace(Py_CHARMASK(*s)))
    1347                 s++;
    1348         if (*s == '-') {
    1349                 s++;
    1350                 sign = -1;
    1351         }
    1352         else if (*s == '+')
    1353                 s++;
    1354 
    1355         /* infinities and nans */
    1356         if (*s == 'i' || *s == 'I') {
    1357                 if (!case_insensitive_match(s+1, "nf"))
    1358                         goto parse_error;
    1359                 s += 3;
    1360                 x = Py_HUGE_VAL;
    1361                 if (case_insensitive_match(s, "inity"))
    1362                         s += 5;
    1363                 goto finished;
    1364         }
    1365         if (*s == 'n' || *s == 'N') {
    1366                 if (!case_insensitive_match(s+1, "an"))
    1367                         goto parse_error;
    1368                 s += 3;
    1369                 x = Py_NAN;
    1370                 goto finished;
    1371         }
    1372 
    1373         /* [0x] */
    1374         s_store = s;
    1375         if (*s == '0') {
    1376                 s++;
    1377                 if (tolower(*s) == (int)'x')
    1378                         s++;
    1379                 else
    1380                         s = s_store;
    1381         }
    1382 
    1383         /* coefficient: <integer> [. <fraction>] */
    1384         coeff_start = s;
    1385         while (hex_from_char(*s) >= 0)
    1386                 s++;
    1387         s_store = s;
    1388         if (*s == '.') {
    1389                 s++;
    1390                 while (hex_from_char(*s) >= 0)
    1391                         s++;
    1392                 coeff_end = s-1;
    1393         }
    1394         else
    1395                 coeff_end = s;
    1396 
    1397         /* ndigits = total # of hex digits; fdigits = # after point */
    1398         ndigits = coeff_end - coeff_start;
    1399         fdigits = coeff_end - s_store;
    1400         if (ndigits == 0)
    1401                 goto parse_error;
    1402         if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
    1403                           LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
    1404                 goto insane_length_error;
    1405 
    1406         /* [p <exponent>] */
    1407         if (tolower(*s) == (int)'p') {
    1408                 s++;
    1409                 exp_start = s;
    1410                 if (*s == '-' || *s == '+')
    1411                         s++;
    1412                 if (!('0' <= *s && *s <= '9'))
    1413                         goto parse_error;
    1414                 s++;
    1415                 while ('0' <= *s && *s <= '9')
    1416                         s++;
    1417                 exp = strtol(exp_start, NULL, 10);
    1418         }
    1419         else
    1420                 exp = 0;
     1443    PyObject *result_as_float, *result;
     1444    double x;
     1445    long exp, top_exp, lsb, key_digit;
     1446    char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
     1447    int half_eps, digit, round_up, sign=1;
     1448    Py_ssize_t length, ndigits, fdigits, i;
     1449
     1450    /*
     1451    * For the sake of simplicity and correctness, we impose an artificial
     1452    * limit on ndigits, the total number of hex digits in the coefficient
     1453    * The limit is chosen to ensure that, writing exp for the exponent,
     1454    *
     1455    *   (1) if exp > LONG_MAX/2 then the value of the hex string is
     1456    *   guaranteed to overflow (provided it's nonzero)
     1457    *
     1458    *   (2) if exp < LONG_MIN/2 then the value of the hex string is
     1459    *   guaranteed to underflow to 0.
     1460    *
     1461    *   (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
     1462    *   overflow in the calculation of exp and top_exp below.
     1463    *
     1464    * More specifically, ndigits is assumed to satisfy the following
     1465    * inequalities:
     1466    *
     1467    *   4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
     1468    *   4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
     1469    *
     1470    * If either of these inequalities is not satisfied, a ValueError is
     1471    * raised.  Otherwise, write x for the value of the hex string, and
     1472    * assume x is nonzero.  Then
     1473    *
     1474    *   2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
     1475    *
     1476    * Now if exp > LONG_MAX/2 then:
     1477    *
     1478    *   exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
     1479    *                    = DBL_MAX_EXP
     1480    *
     1481    * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
     1482    * double, so overflows.  If exp < LONG_MIN/2, then
     1483    *
     1484    *   exp + 4*ndigits <= LONG_MIN/2 - 1 + (
     1485    *                      DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
     1486    *                    = DBL_MIN_EXP - DBL_MANT_DIG - 1
     1487    *
     1488    * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
     1489    * when converted to a C double.
     1490    *
     1491    * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
     1492    * exp+4*ndigits and exp-4*ndigits are within the range of a long.
     1493    */
     1494
     1495    if (PyString_AsStringAndSize(arg, &s, &length))
     1496        return NULL;
     1497    s_end = s + length;
     1498
     1499    /********************
     1500    * Parse the string *
     1501    ********************/
     1502
     1503    /* leading whitespace and optional sign */
     1504    while (Py_ISSPACE(*s))
     1505        s++;
     1506    if (*s == '-') {
     1507        s++;
     1508        sign = -1;
     1509    }
     1510    else if (*s == '+')
     1511        s++;
     1512
     1513    /* infinities and nans */
     1514    if (*s == 'i' || *s == 'I') {
     1515        if (!case_insensitive_match(s+1, "nf"))
     1516            goto parse_error;
     1517        s += 3;
     1518        x = Py_HUGE_VAL;
     1519        if (case_insensitive_match(s, "inity"))
     1520            s += 5;
     1521        goto finished;
     1522    }
     1523    if (*s == 'n' || *s == 'N') {
     1524        if (!case_insensitive_match(s+1, "an"))
     1525            goto parse_error;
     1526        s += 3;
     1527        x = Py_NAN;
     1528        goto finished;
     1529    }
     1530
     1531    /* [0x] */
     1532    s_store = s;
     1533    if (*s == '0') {
     1534        s++;
     1535        if (*s == 'x' || *s == 'X')
     1536            s++;
     1537        else
     1538            s = s_store;
     1539    }
     1540
     1541    /* coefficient: <integer> [. <fraction>] */
     1542    coeff_start = s;
     1543    while (hex_from_char(*s) >= 0)
     1544        s++;
     1545    s_store = s;
     1546    if (*s == '.') {
     1547        s++;
     1548        while (hex_from_char(*s) >= 0)
     1549            s++;
     1550        coeff_end = s-1;
     1551    }
     1552    else
     1553        coeff_end = s;
     1554
     1555    /* ndigits = total # of hex digits; fdigits = # after point */
     1556    ndigits = coeff_end - coeff_start;
     1557    fdigits = coeff_end - s_store;
     1558    if (ndigits == 0)
     1559        goto parse_error;
     1560    if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
     1561                      LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
     1562        goto insane_length_error;
     1563
     1564    /* [p <exponent>] */
     1565    if (*s == 'p' || *s == 'P') {
     1566        s++;
     1567        exp_start = s;
     1568        if (*s == '-' || *s == '+')
     1569            s++;
     1570        if (!('0' <= *s && *s <= '9'))
     1571            goto parse_error;
     1572        s++;
     1573        while ('0' <= *s && *s <= '9')
     1574            s++;
     1575        exp = strtol(exp_start, NULL, 10);
     1576    }
     1577    else
     1578        exp = 0;
    14211579
    14221580/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
    1423 #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?            \
    1424                                      coeff_end-(j) :                    \
    1425                                      coeff_end-1-(j)))
    1426 
    1427         /*******************************************
    1428         * Compute rounded value of the hex string *
    1429         *******************************************/
    1430 
    1431         /* Discard leading zeros, and catch extreme overflow and underflow */
    1432         while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
    1433                 ndigits--;
    1434         if (ndigits == 0 || exp < LONG_MIN/2) {
    1435                 x = 0.0;
    1436                 goto finished;
    1437         }
    1438         if (exp > LONG_MAX/2)
    1439                 goto overflow_error;
    1440 
    1441         /* Adjust exponent for fractional part. */
    1442         exp = exp - 4*((long)fdigits);
    1443 
    1444         /* top_exp = 1 more than exponent of most sig. bit of coefficient */
    1445         top_exp = exp + 4*((long)ndigits - 1);
    1446         for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
    1447                 top_exp++;
    1448 
    1449         /* catch almost all nonextreme cases of overflow and underflow here */
    1450         if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
    1451                 x = 0.0;
    1452                 goto finished;
    1453         }
    1454         if (top_exp > DBL_MAX_EXP)
    1455                 goto overflow_error;
    1456 
    1457         /* lsb = exponent of least significant bit of the *rounded* value.
    1458            This is top_exp - DBL_MANT_DIG unless result is subnormal. */
    1459         lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
    1460 
    1461         x = 0.0;
    1462         if (exp >= lsb) {
    1463                 /* no rounding required */
    1464                 for (i = ndigits-1; i >= 0; i--)
    1465                         x = 16.0*x + HEX_DIGIT(i);
    1466                 x = ldexp(x, (int)(exp));
    1467                 goto finished;
    1468         }
    1469         /* rounding required.  key_digit is the index of the hex digit
    1470            containing the first bit to be rounded away. */
    1471         half_eps = 1 << (int)((lsb - exp - 1) % 4);
    1472         key_digit = (lsb - exp - 1) / 4;
    1473         for (i = ndigits-1; i > key_digit; i--)
    1474                 x = 16.0*x + HEX_DIGIT(i);
    1475         digit = HEX_DIGIT(key_digit);
    1476         x = 16.0*x + (double)(digit & (16-2*half_eps));
    1477 
    1478         /* round-half-even: round up if bit lsb-1 is 1 and at least one of
    1479            bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
    1480         if ((digit & half_eps) != 0) {
    1481                 round_up = 0;
    1482                 if ((digit & (3*half_eps-1)) != 0 ||
    1483                     (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
    1484                         round_up = 1;
    1485                 else
    1486                         for (i = key_digit-1; i >= 0; i--)
    1487                                 if (HEX_DIGIT(i) != 0) {
    1488                                         round_up = 1;
    1489                                         break;
    1490                                 }
    1491                 if (round_up == 1) {
    1492                         x += 2*half_eps;
    1493                         if (top_exp == DBL_MAX_EXP &&
    1494                             x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
    1495                                 /* overflow corner case: pre-rounded value <
    1496                                    2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
    1497                                 goto overflow_error;
    1498                 }
    1499         }
    1500         x = ldexp(x, (int)(exp+4*key_digit));
     1581#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ?            \
     1582                     coeff_end-(j) :                                    \
     1583                     coeff_end-1-(j)))
     1584
     1585    /*******************************************
     1586    * Compute rounded value of the hex string *
     1587    *******************************************/
     1588
     1589    /* Discard leading zeros, and catch extreme overflow and underflow */
     1590    while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
     1591        ndigits--;
     1592    if (ndigits == 0 || exp < LONG_MIN/2) {
     1593        x = 0.0;
     1594        goto finished;
     1595    }
     1596    if (exp > LONG_MAX/2)
     1597        goto overflow_error;
     1598
     1599    /* Adjust exponent for fractional part. */
     1600    exp = exp - 4*((long)fdigits);
     1601
     1602    /* top_exp = 1 more than exponent of most sig. bit of coefficient */
     1603    top_exp = exp + 4*((long)ndigits - 1);
     1604    for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
     1605        top_exp++;
     1606
     1607    /* catch almost all nonextreme cases of overflow and underflow here */
     1608    if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
     1609        x = 0.0;
     1610        goto finished;
     1611    }
     1612    if (top_exp > DBL_MAX_EXP)
     1613        goto overflow_error;
     1614
     1615    /* lsb = exponent of least significant bit of the *rounded* value.
     1616       This is top_exp - DBL_MANT_DIG unless result is subnormal. */
     1617    lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
     1618
     1619    x = 0.0;
     1620    if (exp >= lsb) {
     1621        /* no rounding required */
     1622        for (i = ndigits-1; i >= 0; i--)
     1623            x = 16.0*x + HEX_DIGIT(i);
     1624        x = ldexp(x, (int)(exp));
     1625        goto finished;
     1626    }
     1627    /* rounding required.  key_digit is the index of the hex digit
     1628       containing the first bit to be rounded away. */
     1629    half_eps = 1 << (int)((lsb - exp - 1) % 4);
     1630    key_digit = (lsb - exp - 1) / 4;
     1631    for (i = ndigits-1; i > key_digit; i--)
     1632        x = 16.0*x + HEX_DIGIT(i);
     1633    digit = HEX_DIGIT(key_digit);
     1634    x = 16.0*x + (double)(digit & (16-2*half_eps));
     1635
     1636    /* round-half-even: round up if bit lsb-1 is 1 and at least one of
     1637       bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
     1638    if ((digit & half_eps) != 0) {
     1639        round_up = 0;
     1640        if ((digit & (3*half_eps-1)) != 0 ||
     1641            (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
     1642            round_up = 1;
     1643        else
     1644            for (i = key_digit-1; i >= 0; i--)
     1645                if (HEX_DIGIT(i) != 0) {
     1646                    round_up = 1;
     1647                    break;
     1648                }
     1649        if (round_up == 1) {
     1650            x += 2*half_eps;
     1651            if (top_exp == DBL_MAX_EXP &&
     1652                x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
     1653                /* overflow corner case: pre-rounded value <
     1654                   2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
     1655                goto overflow_error;
     1656        }
     1657    }
     1658    x = ldexp(x, (int)(exp+4*key_digit));
    15011659
    15021660  finished:
    1503         /* optional trailing whitespace leading to the end of the string */
    1504         while (*s && isspace(Py_CHARMASK(*s)))
    1505                 s++;
    1506         if (s != s_end)
    1507                 goto parse_error;
    1508         result_as_float = Py_BuildValue("(d)", sign * x);
    1509         if (result_as_float == NULL)
    1510                 return NULL;
    1511         result = PyObject_CallObject(cls, result_as_float);
    1512         Py_DECREF(result_as_float);
    1513         return result;
     1661    /* optional trailing whitespace leading to the end of the string */
     1662    while (Py_ISSPACE(*s))
     1663        s++;
     1664    if (s != s_end)
     1665        goto parse_error;
     1666    result_as_float = Py_BuildValue("(d)", sign * x);
     1667    if (result_as_float == NULL)
     1668        return NULL;
     1669    result = PyObject_CallObject(cls, result_as_float);
     1670    Py_DECREF(result_as_float);
     1671    return result;
    15141672
    15151673  overflow_error:
    1516         PyErr_SetString(PyExc_OverflowError,
    1517                         "hexadecimal value too large to represent as a float");
    1518         return NULL;
     1674    PyErr_SetString(PyExc_OverflowError,
     1675                    "hexadecimal value too large to represent as a float");
     1676    return NULL;
    15191677
    15201678  parse_error:
    1521         PyErr_SetString(PyExc_ValueError,
    1522                         "invalid hexadecimal floating-point string");
    1523         return NULL;
     1679    PyErr_SetString(PyExc_ValueError,
     1680                    "invalid hexadecimal floating-point string");
     1681    return NULL;
    15241682
    15251683  insane_length_error:
    1526         PyErr_SetString(PyExc_ValueError,
    1527                         "hexadecimal string too long to convert");
    1528         return NULL;
     1684    PyErr_SetString(PyExc_ValueError,
     1685                    "hexadecimal string too long to convert");
     1686    return NULL;
    15291687}
    15301688
     
    15421700float_as_integer_ratio(PyObject *v, PyObject *unused)
    15431701{
    1544         double self;
    1545         double float_part;
    1546         int exponent;
    1547         int i;
    1548 
    1549         PyObject *prev;
    1550         PyObject *py_exponent = NULL;
    1551         PyObject *numerator = NULL;
    1552         PyObject *denominator = NULL;
    1553         PyObject *result_pair = NULL;
    1554         PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
     1702    double self;
     1703    double float_part;
     1704    int exponent;
     1705    int i;
     1706
     1707    PyObject *prev;
     1708    PyObject *py_exponent = NULL;
     1709    PyObject *numerator = NULL;
     1710    PyObject *denominator = NULL;
     1711    PyObject *result_pair = NULL;
     1712    PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
    15551713
    15561714#define INPLACE_UPDATE(obj, call) \
    1557         prev = obj; \
    1558         obj = call; \
    1559         Py_DECREF(prev); \
    1560 
    1561         CONVERT_TO_DOUBLE(v, self);
    1562 
    1563         if (Py_IS_INFINITY(self)) {
    1564           PyErr_SetString(PyExc_OverflowError,
    1565                           "Cannot pass infinity to float.as_integer_ratio.");
    1566           return NULL;
    1567         }
     1715    prev = obj; \
     1716    obj = call; \
     1717    Py_DECREF(prev); \
     1718
     1719    CONVERT_TO_DOUBLE(v, self);
     1720
     1721    if (Py_IS_INFINITY(self)) {
     1722      PyErr_SetString(PyExc_OverflowError,
     1723                      "Cannot pass infinity to float.as_integer_ratio.");
     1724      return NULL;
     1725    }
    15681726#ifdef Py_NAN
    1569         if (Py_IS_NAN(self)) {
    1570           PyErr_SetString(PyExc_ValueError,
    1571                           "Cannot pass NaN to float.as_integer_ratio.");
    1572           return NULL;
    1573         }
     1727    if (Py_IS_NAN(self)) {
     1728      PyErr_SetString(PyExc_ValueError,
     1729                      "Cannot pass NaN to float.as_integer_ratio.");
     1730      return NULL;
     1731    }
    15741732#endif
    15751733
    1576         PyFPE_START_PROTECT("as_integer_ratio", goto error);
    1577         float_part = frexp(self, &exponent);    /* self == float_part * 2**exponent exactly */
    1578         PyFPE_END_PROTECT(float_part);
    1579        
    1580         for (i=0; i<300 && float_part != floor(float_part) ; i++) {
    1581                 float_part *= 2.0;
    1582                 exponent--;
    1583         }       
    1584         /* self == float_part * 2**exponent exactly and float_part is integral.
    1585            If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
    1586            to be truncated by PyLong_FromDouble(). */
    1587 
    1588         numerator = PyLong_FromDouble(float_part);
    1589         if (numerator == NULL) goto error;
    1590 
    1591         /* fold in 2**exponent */
    1592         denominator = PyLong_FromLong(1);
    1593         py_exponent = PyLong_FromLong(labs((long)exponent));
    1594         if (py_exponent == NULL) goto error;
    1595         INPLACE_UPDATE(py_exponent,
    1596                        long_methods->nb_lshift(denominator, py_exponent));
    1597         if (py_exponent == NULL) goto error;
    1598         if (exponent > 0) {
    1599                 INPLACE_UPDATE(numerator,
    1600                                long_methods->nb_multiply(numerator, py_exponent));
    1601                 if (numerator == NULL) goto error;
    1602         }
    1603         else {
    1604                 Py_DECREF(denominator);
    1605                 denominator = py_exponent;
    1606                 py_exponent = NULL;
    1607         }
    1608 
    1609         /* Returns ints instead of longs where possible */
    1610         INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
    1611         if (numerator == NULL) goto error;
    1612         INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
    1613         if (denominator == NULL) goto error;
    1614 
    1615         result_pair = PyTuple_Pack(2, numerator, denominator);
     1734    PyFPE_START_PROTECT("as_integer_ratio", goto error);
     1735    float_part = frexp(self, &exponent);        /* self == float_part * 2**exponent exactly */
     1736    PyFPE_END_PROTECT(float_part);
     1737
     1738    for (i=0; i<300 && float_part != floor(float_part) ; i++) {
     1739        float_part *= 2.0;
     1740        exponent--;
     1741    }
     1742    /* self == float_part * 2**exponent exactly and float_part is integral.
     1743       If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
     1744       to be truncated by PyLong_FromDouble(). */
     1745
     1746    numerator = PyLong_FromDouble(float_part);
     1747    if (numerator == NULL) goto error;
     1748
     1749    /* fold in 2**exponent */
     1750    denominator = PyLong_FromLong(1);
     1751    py_exponent = PyLong_FromLong(labs((long)exponent));
     1752    if (py_exponent == NULL) goto error;
     1753    INPLACE_UPDATE(py_exponent,
     1754                   long_methods->nb_lshift(denominator, py_exponent));
     1755    if (py_exponent == NULL) goto error;
     1756    if (exponent > 0) {
     1757        INPLACE_UPDATE(numerator,
     1758                       long_methods->nb_multiply(numerator, py_exponent));
     1759        if (numerator == NULL) goto error;
     1760    }
     1761    else {
     1762        Py_DECREF(denominator);
     1763        denominator = py_exponent;
     1764        py_exponent = NULL;
     1765    }
     1766
     1767    /* Returns ints instead of longs where possible */
     1768    INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
     1769    if (numerator == NULL) goto error;
     1770    INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
     1771    if (denominator == NULL) goto error;
     1772
     1773    result_pair = PyTuple_Pack(2, numerator, denominator);
    16161774
    16171775#undef INPLACE_UPDATE
    16181776error:
    1619         Py_XDECREF(py_exponent);
    1620         Py_XDECREF(denominator);
    1621         Py_XDECREF(numerator);
    1622         return result_pair;
     1777    Py_XDECREF(py_exponent);
     1778    Py_XDECREF(denominator);
     1779    Py_XDECREF(numerator);
     1780    return result_pair;
    16231781}
    16241782
     
    16261784"float.as_integer_ratio() -> (int, int)\n"
    16271785"\n"
    1628 "Returns a pair of integers, whose ratio is exactly equal to the original\n"
     1786"Return a pair of integers, whose ratio is exactly equal to the original\n"
    16291787"float and with a positive denominator.\n"
    1630 "Raises OverflowError on infinities and a ValueError on NaNs.\n"
     1788"Raise OverflowError on infinities and a ValueError on NaNs.\n"
    16311789"\n"
    16321790">>> (10.0).as_integer_ratio()\n"
     
    16441802float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    16451803{
    1646         PyObject *x = Py_False; /* Integer zero */
    1647         static char *kwlist[] = {"x", 0};
    1648 
    1649         if (type != &PyFloat_Type)
    1650                 return float_subtype_new(type, args, kwds); /* Wimp out */
    1651         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
    1652                 return NULL;
    1653         /* If it's a string, but not a string subclass, use
    1654            PyFloat_FromString. */
    1655         if (PyString_CheckExact(x))
    1656                 return PyFloat_FromString(x, NULL);
    1657         return PyNumber_Float(x);
     1804    PyObject *x = Py_False; /* Integer zero */
     1805    static char *kwlist[] = {"x", 0};
     1806
     1807    if (type != &PyFloat_Type)
     1808        return float_subtype_new(type, args, kwds); /* Wimp out */
     1809    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
     1810        return NULL;
     1811    /* If it's a string, but not a string subclass, use
     1812       PyFloat_FromString. */
     1813    if (PyString_CheckExact(x))
     1814        return PyFloat_FromString(x, NULL);
     1815    return PyNumber_Float(x);
    16581816}
    16591817
     
    16661824float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    16671825{
    1668         PyObject *tmp, *newobj;
    1669 
    1670         assert(PyType_IsSubtype(type, &PyFloat_Type));
    1671         tmp = float_new(&PyFloat_Type, args, kwds);
    1672         if (tmp == NULL)
    1673                 return NULL;
    1674         assert(PyFloat_CheckExact(tmp));
    1675         newobj = type->tp_alloc(type, 0);
    1676         if (newobj == NULL) {
    1677                 Py_DECREF(tmp);
    1678                 return NULL;
    1679         }
    1680         ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
    1681         Py_DECREF(tmp);
    1682         return newobj;
     1826    PyObject *tmp, *newobj;
     1827
     1828    assert(PyType_IsSubtype(type, &PyFloat_Type));
     1829    tmp = float_new(&PyFloat_Type, args, kwds);
     1830    if (tmp == NULL)
     1831        return NULL;
     1832    assert(PyFloat_CheckExact(tmp));
     1833    newobj = type->tp_alloc(type, 0);
     1834    if (newobj == NULL) {
     1835        Py_DECREF(tmp);
     1836        return NULL;
     1837    }
     1838    ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
     1839    Py_DECREF(tmp);
     1840    return newobj;
    16831841}
    16841842
     
    16861844float_getnewargs(PyFloatObject *v)
    16871845{
    1688         return Py_BuildValue("(d)", v->ob_fval);
     1846    return Py_BuildValue("(d)", v->ob_fval);
    16891847}
    16901848
     
    16921850
    16931851typedef enum {
    1694         unknown_format, ieee_big_endian_format, ieee_little_endian_format
     1852    unknown_format, ieee_big_endian_format, ieee_little_endian_format
    16951853} float_format_type;
    16961854
     
    17011859float_getformat(PyTypeObject *v, PyObject* arg)
    17021860{
    1703         char* s;
    1704         float_format_type r;
    1705 
    1706         if (!PyString_Check(arg)) {
    1707                 PyErr_Format(PyExc_TypeError,
    1708              "__getformat__() argument must be string, not %.500s",
    1709                              Py_TYPE(arg)->tp_name);
    1710                 return NULL;
    1711         }
    1712         s = PyString_AS_STRING(arg);
    1713         if (strcmp(s, "double") == 0) {
    1714                 r = double_format;
    1715         }
    1716         else if (strcmp(s, "float") == 0) {
    1717                 r = float_format;
    1718         }
    1719         else {
    1720                 PyErr_SetString(PyExc_ValueError,
    1721                                 "__getformat__() argument 1 must be "
    1722                                 "'double' or 'float'");
    1723                 return NULL;
    1724         }
    1725        
    1726         switch (r) {
    1727         case unknown_format:
    1728                 return PyString_FromString("unknown");
    1729         case ieee_little_endian_format:
    1730                 return PyString_FromString("IEEE, little-endian");
    1731         case ieee_big_endian_format:
    1732                 return PyString_FromString("IEEE, big-endian");
    1733         default:
    1734                 Py_FatalError("insane float_format or double_format");
    1735                 return NULL;
    1736         }
     1861    char* s;
     1862    float_format_type r;
     1863
     1864    if (!PyString_Check(arg)) {
     1865        PyErr_Format(PyExc_TypeError,
     1866         "__getformat__() argument must be string, not %.500s",
     1867                         Py_TYPE(arg)->tp_name);
     1868        return NULL;
     1869    }
     1870    s = PyString_AS_STRING(arg);
     1871    if (strcmp(s, "double") == 0) {
     1872        r = double_format;
     1873    }
     1874    else if (strcmp(s, "float") == 0) {
     1875        r = float_format;
     1876    }
     1877    else {
     1878        PyErr_SetString(PyExc_ValueError,
     1879                        "__getformat__() argument 1 must be "
     1880                        "'double' or 'float'");
     1881        return NULL;
     1882    }
     1883
     1884    switch (r) {
     1885    case unknown_format:
     1886        return PyString_FromString("unknown");
     1887    case ieee_little_endian_format:
     1888        return PyString_FromString("IEEE, little-endian");
     1889    case ieee_big_endian_format:
     1890        return PyString_FromString("IEEE, big-endian");
     1891    default:
     1892        Py_FatalError("insane float_format or double_format");
     1893        return NULL;
     1894    }
    17371895}
    17381896
     
    17501908float_setformat(PyTypeObject *v, PyObject* args)
    17511909{
    1752         char* typestr;
    1753         char* format;
    1754         float_format_type f;
    1755         float_format_type detected;
    1756         float_format_type *p;
    1757 
    1758         if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
    1759                 return NULL;
    1760 
    1761         if (strcmp(typestr, "double") == 0) {
    1762                 p = &double_format;
    1763                 detected = detected_double_format;
    1764         }
    1765         else if (strcmp(typestr, "float") == 0) {
    1766                 p = &float_format;
    1767                 detected = detected_float_format;
    1768         }
    1769         else {
    1770                 PyErr_SetString(PyExc_ValueError,
    1771                                 "__setformat__() argument 1 must "
    1772                                 "be 'double' or 'float'");
    1773                 return NULL;
    1774         }
    1775        
    1776         if (strcmp(format, "unknown") == 0) {
    1777                 f = unknown_format;
    1778         }
    1779         else if (strcmp(format, "IEEE, little-endian") == 0) {
    1780                 f = ieee_little_endian_format;
    1781         }
    1782         else if (strcmp(format, "IEEE, big-endian") == 0) {
    1783                 f = ieee_big_endian_format;
    1784         }
    1785         else {
    1786                 PyErr_SetString(PyExc_ValueError,
    1787                                 "__setformat__() argument 2 must be "
    1788                                 "'unknown', 'IEEE, little-endian' or "
    1789                                 "'IEEE, big-endian'");
    1790                 return NULL;
    1791 
    1792         }
    1793 
    1794         if (f != unknown_format && f != detected) {
    1795                 PyErr_Format(PyExc_ValueError,
    1796                              "can only set %s format to 'unknown' or the "
    1797                              "detected platform value", typestr);
    1798                 return NULL;
    1799         }
    1800 
    1801         *p = f;
    1802         Py_RETURN_NONE;
     1910    char* typestr;
     1911    char* format;
     1912    float_format_type f;
     1913    float_format_type detected;
     1914    float_format_type *p;
     1915
     1916    if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
     1917        return NULL;
     1918
     1919    if (strcmp(typestr, "double") == 0) {
     1920        p = &double_format;
     1921        detected = detected_double_format;
     1922    }
     1923    else if (strcmp(typestr, "float") == 0) {
     1924        p = &float_format;
     1925        detected = detected_float_format;
     1926    }
     1927    else {
     1928        PyErr_SetString(PyExc_ValueError,
     1929                        "__setformat__() argument 1 must "
     1930                        "be 'double' or 'float'");
     1931        return NULL;
     1932    }
     1933
     1934    if (strcmp(format, "unknown") == 0) {
     1935        f = unknown_format;
     1936    }
     1937    else if (strcmp(format, "IEEE, little-endian") == 0) {
     1938        f = ieee_little_endian_format;
     1939    }
     1940    else if (strcmp(format, "IEEE, big-endian") == 0) {
     1941        f = ieee_big_endian_format;
     1942    }
     1943    else {
     1944        PyErr_SetString(PyExc_ValueError,
     1945                        "__setformat__() argument 2 must be "
     1946                        "'unknown', 'IEEE, little-endian' or "
     1947                        "'IEEE, big-endian'");
     1948        return NULL;
     1949
     1950    }
     1951
     1952    if (f != unknown_format && f != detected) {
     1953        PyErr_Format(PyExc_ValueError,
     1954                     "can only set %s format to 'unknown' or the "
     1955                     "detected platform value", typestr);
     1956        return NULL;
     1957    }
     1958
     1959    *p = f;
     1960    Py_RETURN_NONE;
    18031961}
    18041962
     
    18131971"one of the latter two if it appears to match the underlying C reality.\n"
    18141972"\n"
    1815 "Overrides the automatic determination of C-level floating point type.\n"
     1973"Override the automatic determination of C-level floating point type.\n"
    18161974"This affects how floats are converted to and from binary strings.");
    18171975
     
    18191977float_getzero(PyObject *v, void *closure)
    18201978{
    1821         return PyFloat_FromDouble(0.0);
     1979    return PyFloat_FromDouble(0.0);
    18221980}
    18231981
     
    18251983float__format__(PyObject *self, PyObject *args)
    18261984{
    1827         PyObject *format_spec;
    1828 
    1829         if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
    1830                 return NULL;
    1831         if (PyBytes_Check(format_spec))
    1832                 return _PyFloat_FormatAdvanced(self,
    1833                                                PyBytes_AS_STRING(format_spec),
    1834                                                PyBytes_GET_SIZE(format_spec));
    1835         if (PyUnicode_Check(format_spec)) {
    1836                 /* Convert format_spec to a str */
    1837                 PyObject *result;
    1838                 PyObject *str_spec = PyObject_Str(format_spec);
    1839 
    1840                 if (str_spec == NULL)
    1841                         return NULL;
    1842 
    1843                 result = _PyFloat_FormatAdvanced(self,
    1844                                                 PyBytes_AS_STRING(str_spec),
    1845                                                 PyBytes_GET_SIZE(str_spec));
    1846 
    1847                 Py_DECREF(str_spec);
    1848                 return result;
    1849         }
    1850         PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
    1851         return NULL;
     1985    PyObject *format_spec;
     1986
     1987    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
     1988        return NULL;
     1989    if (PyBytes_Check(format_spec))
     1990        return _PyFloat_FormatAdvanced(self,
     1991                                       PyBytes_AS_STRING(format_spec),
     1992                                       PyBytes_GET_SIZE(format_spec));
     1993    if (PyUnicode_Check(format_spec)) {
     1994        /* Convert format_spec to a str */
     1995        PyObject *result;
     1996        PyObject *str_spec = PyObject_Str(format_spec);
     1997
     1998        if (str_spec == NULL)
     1999            return NULL;
     2000
     2001        result = _PyFloat_FormatAdvanced(self,
     2002                                        PyBytes_AS_STRING(str_spec),
     2003                                        PyBytes_GET_SIZE(str_spec));
     2004
     2005        Py_DECREF(str_spec);
     2006        return result;
     2007    }
     2008    PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
     2009    return NULL;
    18522010}
    18532011
     
    18592017
    18602018static PyMethodDef float_methods[] = {
    1861         {"conjugate",   (PyCFunction)float_float,       METH_NOARGS,
    1862          "Returns self, the complex conjugate of any float."},
    1863         {"__trunc__",   (PyCFunction)float_trunc, METH_NOARGS,
    1864          "Returns the Integral closest to x between 0 and x."},
    1865         {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
    1866         float_as_integer_ratio_doc},
    1867         {"fromhex", (PyCFunction)float_fromhex,
    1868         METH_O|METH_CLASS, float_fromhex_doc},
    1869         {"hex", (PyCFunction)float_hex,
    1870         METH_NOARGS, float_hex_doc},
    1871         {"is_integer",  (PyCFunction)float_is_integer,  METH_NOARGS,
    1872          "Returns True if the float is an integer."},
     2019    {"conjugate",       (PyCFunction)float_float,       METH_NOARGS,
     2020     "Return self, the complex conjugate of any float."},
     2021    {"__trunc__",       (PyCFunction)float_trunc, METH_NOARGS,
     2022     "Return the Integral closest to x between 0 and x."},
     2023    {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
     2024    float_as_integer_ratio_doc},
     2025    {"fromhex", (PyCFunction)float_fromhex,
     2026    METH_O|METH_CLASS, float_fromhex_doc},
     2027    {"hex", (PyCFunction)float_hex,
     2028    METH_NOARGS, float_hex_doc},
     2029    {"is_integer",      (PyCFunction)float_is_integer,  METH_NOARGS,
     2030     "Return True if the float is an integer."},
    18732031#if 0
    1874         {"is_inf",      (PyCFunction)float_is_inf,      METH_NOARGS,
    1875          "Returns True if the float is positive or negative infinite."},
    1876         {"is_finite",   (PyCFunction)float_is_finite,   METH_NOARGS,
    1877          "Returns True if the float is finite, neither infinite nor NaN."},
    1878         {"is_nan",      (PyCFunction)float_is_nan,      METH_NOARGS,
    1879          "Returns True if the float is not a number (NaN)."},
     2032    {"is_inf",          (PyCFunction)float_is_inf,      METH_NOARGS,
     2033     "Return True if the float is positive or negative infinite."},
     2034    {"is_finite",       (PyCFunction)float_is_finite,   METH_NOARGS,
     2035     "Return True if the float is finite, neither infinite nor NaN."},
     2036    {"is_nan",          (PyCFunction)float_is_nan,      METH_NOARGS,
     2037     "Return True if the float is not a number (NaN)."},
    18802038#endif
    1881         {"__getnewargs__",      (PyCFunction)float_getnewargs,  METH_NOARGS},
    1882         {"__getformat__",       (PyCFunction)float_getformat,   
    1883          METH_O|METH_CLASS,             float_getformat_doc},
    1884         {"__setformat__",       (PyCFunction)float_setformat,   
    1885          METH_VARARGS|METH_CLASS,       float_setformat_doc},
    1886         {"__format__",          (PyCFunction)float__format__,
    1887          METH_VARARGS,                  float__format__doc},
    1888         {NULL,          NULL}           /* sentinel */
     2039    {"__getnewargs__",          (PyCFunction)float_getnewargs,  METH_NOARGS},
     2040    {"__getformat__",           (PyCFunction)float_getformat,
     2041     METH_O|METH_CLASS,                 float_getformat_doc},
     2042    {"__setformat__",           (PyCFunction)float_setformat,
     2043     METH_VARARGS|METH_CLASS,           float_setformat_doc},
     2044    {"__format__",          (PyCFunction)float__format__,
     2045     METH_VARARGS,                  float__format__doc},
     2046    {NULL,              NULL}           /* sentinel */
    18892047};
    18902048
    18912049static PyGetSetDef float_getset[] = {
    1892     {"real", 
     2050    {"real",
    18932051     (getter)float_float, (setter)NULL,
    18942052     "the real part of a complex number",
    18952053     NULL},
    1896     {"imag", 
     2054    {"imag",
    18972055     (getter)float_getzero, (setter)NULL,
    18982056     "the imaginary part of a complex number",
     
    19082066
    19092067static PyNumberMethods float_as_number = {
    1910         float_add,      /*nb_add*/
    1911         float_sub,      /*nb_subtract*/
    1912         float_mul,      /*nb_multiply*/
    1913         float_classic_div, /*nb_divide*/
    1914         float_rem,      /*nb_remainder*/
    1915         float_divmod,   /*nb_divmod*/
    1916         float_pow,      /*nb_power*/
    1917         (unaryfunc)float_neg, /*nb_negative*/
    1918         (unaryfunc)float_float, /*nb_positive*/
    1919         (unaryfunc)float_abs, /*nb_absolute*/
    1920         (inquiry)float_nonzero, /*nb_nonzero*/
    1921         0,              /*nb_invert*/
    1922         0,              /*nb_lshift*/
    1923         0,              /*nb_rshift*/
    1924         0,              /*nb_and*/
    1925         0,              /*nb_xor*/
    1926         0,              /*nb_or*/
    1927         float_coerce,   /*nb_coerce*/
    1928         float_trunc,    /*nb_int*/
    1929         float_long,     /*nb_long*/
    1930         float_float,    /*nb_float*/
    1931         0,              /* nb_oct */
    1932         0,              /* nb_hex */
    1933         0,              /* nb_inplace_add */
    1934         0,              /* nb_inplace_subtract */
    1935         0,              /* nb_inplace_multiply */
    1936         0,              /* nb_inplace_divide */
    1937         0,              /* nb_inplace_remainder */
    1938         0,              /* nb_inplace_power */
    1939         0,              /* nb_inplace_lshift */
    1940         0,              /* nb_inplace_rshift */
    1941         0,              /* nb_inplace_and */
    1942         0,              /* nb_inplace_xor */
    1943         0,              /* nb_inplace_or */
    1944         float_floor_div, /* nb_floor_divide */
    1945         float_div,      /* nb_true_divide */
    1946         0,              /* nb_inplace_floor_divide */
    1947         0,              /* nb_inplace_true_divide */
     2068    float_add,          /*nb_add*/
     2069    float_sub,          /*nb_subtract*/
     2070    float_mul,          /*nb_multiply*/
     2071    float_classic_div, /*nb_divide*/
     2072    float_rem,          /*nb_remainder*/
     2073    float_divmod,       /*nb_divmod*/
     2074    float_pow,          /*nb_power*/
     2075    (unaryfunc)float_neg, /*nb_negative*/
     2076    (unaryfunc)float_float, /*nb_positive*/
     2077    (unaryfunc)float_abs, /*nb_absolute*/
     2078    (inquiry)float_nonzero, /*nb_nonzero*/
     2079    0,                  /*nb_invert*/
     2080    0,                  /*nb_lshift*/
     2081    0,                  /*nb_rshift*/
     2082    0,                  /*nb_and*/
     2083    0,                  /*nb_xor*/
     2084    0,                  /*nb_or*/
     2085    float_coerce,       /*nb_coerce*/
     2086    float_trunc,        /*nb_int*/
     2087    float_long,         /*nb_long*/
     2088    float_float,        /*nb_float*/
     2089    0,                  /* nb_oct */
     2090    0,                  /* nb_hex */
     2091    0,                  /* nb_inplace_add */
     2092    0,                  /* nb_inplace_subtract */
     2093    0,                  /* nb_inplace_multiply */
     2094    0,                  /* nb_inplace_divide */
     2095    0,                  /* nb_inplace_remainder */
     2096    0,                  /* nb_inplace_power */
     2097    0,                  /* nb_inplace_lshift */
     2098    0,                  /* nb_inplace_rshift */
     2099    0,                  /* nb_inplace_and */
     2100    0,                  /* nb_inplace_xor */
     2101    0,                  /* nb_inplace_or */
     2102    float_floor_div, /* nb_floor_divide */
     2103    float_div,          /* nb_true_divide */
     2104    0,                  /* nb_inplace_floor_divide */
     2105    0,                  /* nb_inplace_true_divide */
    19482106};
    19492107
    19502108PyTypeObject PyFloat_Type = {
    1951         PyVarObject_HEAD_INIT(&PyType_Type, 0)
    1952         "float",
    1953         sizeof(PyFloatObject),
    1954         0,
    1955         (destructor)float_dealloc,              /* tp_dealloc */
    1956         (printfunc)float_print,                 /* tp_print */
    1957         0,                                      /* tp_getattr */
    1958         0,                                      /* tp_setattr */
    1959         0,                                      /* tp_compare */
    1960         (reprfunc)float_repr,                   /* tp_repr */
    1961         &float_as_number,                       /* tp_as_number */
    1962         0,                                      /* tp_as_sequence */
    1963         0,                                      /* tp_as_mapping */
    1964         (hashfunc)float_hash,                   /* tp_hash */
    1965         0,                                      /* tp_call */
    1966         (reprfunc)float_str,                    /* tp_str */
    1967         PyObject_GenericGetAttr,                /* tp_getattro */
    1968         0,                                      /* tp_setattro */
    1969         0,                                      /* tp_as_buffer */
    1970         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
    1971                 Py_TPFLAGS_BASETYPE,            /* tp_flags */
    1972         float_doc,                              /* tp_doc */
    1973         0,                                      /* tp_traverse */
    1974         0,                                      /* tp_clear */
    1975         float_richcompare,                      /* tp_richcompare */
    1976         0,                                      /* tp_weaklistoffset */
    1977         0,                                      /* tp_iter */
    1978         0,                                      /* tp_iternext */
    1979         float_methods,                          /* tp_methods */
    1980         0,                                      /* tp_members */
    1981         float_getset,                           /* tp_getset */
    1982         0,                                      /* tp_base */
    1983         0,                                      /* tp_dict */
    1984         0,                                      /* tp_descr_get */
    1985         0,                                      /* tp_descr_set */
    1986         0,                                      /* tp_dictoffset */
    1987         0,                                      /* tp_init */
    1988         0,                                      /* tp_alloc */
    1989         float_new,                              /* tp_new */
     2109    PyVarObject_HEAD_INIT(&PyType_Type, 0)
     2110    "float",
     2111    sizeof(PyFloatObject),
     2112    0,
     2113    (destructor)float_dealloc,                  /* tp_dealloc */
     2114    (printfunc)float_print,                     /* tp_print */
     2115    0,                                          /* tp_getattr */
     2116    0,                                          /* tp_setattr */
     2117    0,                                          /* tp_compare */
     2118    (reprfunc)float_repr,                       /* tp_repr */
     2119    &float_as_number,                           /* tp_as_number */
     2120    0,                                          /* tp_as_sequence */
     2121    0,                                          /* tp_as_mapping */
     2122    (hashfunc)float_hash,                       /* tp_hash */
     2123    0,                                          /* tp_call */
     2124    (reprfunc)float_str,                        /* tp_str */
     2125    PyObject_GenericGetAttr,                    /* tp_getattro */
     2126    0,                                          /* tp_setattro */
     2127    0,                                          /* tp_as_buffer */
     2128    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
     2129        Py_TPFLAGS_BASETYPE,                    /* tp_flags */
     2130    float_doc,                                  /* tp_doc */
     2131    0,                                          /* tp_traverse */
     2132    0,                                          /* tp_clear */
     2133    float_richcompare,                          /* tp_richcompare */
     2134    0,                                          /* tp_weaklistoffset */
     2135    0,                                          /* tp_iter */
     2136    0,                                          /* tp_iternext */
     2137    float_methods,                              /* tp_methods */
     2138    0,                                          /* tp_members */
     2139    float_getset,                               /* tp_getset */
     2140    0,                                          /* tp_base */
     2141    0,                                          /* tp_dict */
     2142    0,                                          /* tp_descr_get */
     2143    0,                                          /* tp_descr_set */
     2144    0,                                          /* tp_dictoffset */
     2145    0,                                          /* tp_init */
     2146    0,                                          /* tp_alloc */
     2147    float_new,                                  /* tp_new */
    19902148};
    19912149
     
    19932151_PyFloat_Init(void)
    19942152{
    1995         /* We attempt to determine if this machine is using IEEE
    1996            floating point formats by peering at the bits of some
    1997            carefully chosen values.  If it looks like we are on an
    1998            IEEE platform, the float packing/unpacking routines can
    1999            just copy bits, if not they resort to arithmetic & shifts
    2000            and masks.  The shifts & masks approach works on all finite
    2001            values, but what happens to infinities, NaNs and signed
    2002            zeroes on packing is an accident, and attempting to unpack
    2003            a NaN or an infinity will raise an exception.
    2004 
    2005            Note that if we're on some whacked-out platform which uses
    2006            IEEE formats but isn't strictly little-endian or big-
    2007            endian, we will fall back to the portable shifts & masks
    2008            method. */
     2153    /* We attempt to determine if this machine is using IEEE
     2154       floating point formats by peering at the bits of some
     2155       carefully chosen values.  If it looks like we are on an
     2156       IEEE platform, the float packing/unpacking routines can
     2157       just copy bits, if not they resort to arithmetic & shifts
     2158       and masks.  The shifts & masks approach works on all finite
     2159       values, but what happens to infinities, NaNs and signed
     2160       zeroes on packing is an accident, and attempting to unpack
     2161       a NaN or an infinity will raise an exception.
     2162
     2163       Note that if we're on some whacked-out platform which uses
     2164       IEEE formats but isn't strictly little-endian or big-
     2165       endian, we will fall back to the portable shifts & masks
     2166       method. */
    20092167
    20102168#if SIZEOF_DOUBLE == 8
    2011         {
    2012                 double x = 9006104071832581.0;
    2013                 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
    2014                         detected_double_format = ieee_big_endian_format;
    2015                 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
    2016                         detected_double_format = ieee_little_endian_format;
    2017                 else
    2018                         detected_double_format = unknown_format;
    2019         }
     2169    {
     2170        double x = 9006104071832581.0;
     2171        if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
     2172            detected_double_format = ieee_big_endian_format;
     2173        else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
     2174            detected_double_format = ieee_little_endian_format;
     2175        else
     2176            detected_double_format = unknown_format;
     2177    }
    20202178#else
    2021         detected_double_format = unknown_format;
     2179    detected_double_format = unknown_format;
    20222180#endif
    20232181
    20242182#if SIZEOF_FLOAT == 4
    2025         {
    2026                 float y = 16711938.0;
    2027                 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
    2028                         detected_float_format = ieee_big_endian_format;
    2029                 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
    2030                         detected_float_format = ieee_little_endian_format;
    2031                 else
    2032                         detected_float_format = unknown_format;
    2033         }
     2183    {
     2184        float y = 16711938.0;
     2185        if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
     2186            detected_float_format = ieee_big_endian_format;
     2187        else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
     2188            detected_float_format = ieee_little_endian_format;
     2189        else
     2190            detected_float_format = unknown_format;
     2191    }
    20342192#else
    2035         detected_float_format = unknown_format;
     2193    detected_float_format = unknown_format;
    20362194#endif
    20372195
    2038         double_format = detected_double_format;
    2039         float_format = detected_float_format;
    2040 
    2041         /* Init float info */
    2042         if (FloatInfoType.tp_name == 0)
    2043                 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
     2196    double_format = detected_double_format;
     2197    float_format = detected_float_format;
     2198
     2199    /* Init float info */
     2200    if (FloatInfoType.tp_name == 0)
     2201        PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
    20442202}
    20452203
     
    20472205PyFloat_ClearFreeList(void)
    20482206{
    2049         PyFloatObject *p;
    2050         PyFloatBlock *list, *next;
    2051         int i;
    2052         int u;                  /* remaining unfreed ints per block */
    2053         int freelist_size = 0;
    2054 
    2055         list = block_list;
    2056         block_list = NULL;
    2057         free_list = NULL;
    2058         while (list != NULL) {
    2059                 u = 0;
    2060                 for (i = 0, p = &list->objects[0];
    2061                      i < N_FLOATOBJECTS;
    2062                      i++, p++) {
    2063                         if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
    2064                                 u++;
    2065                 }
    2066                 next = list->next;
    2067                 if (u) {
    2068                         list->next = block_list;
    2069                         block_list = list;
    2070                         for (i = 0, p = &list->objects[0];
    2071                              i < N_FLOATOBJECTS;
    2072                              i++, p++) {
    2073                                 if (!PyFloat_CheckExact(p) ||
    2074                                     Py_REFCNT(p) == 0) {
    2075                                         Py_TYPE(p) = (struct _typeobject *)
    2076                                                 free_list;
    2077                                         free_list = p;
    2078                                 }
    2079                         }
    2080                 }
    2081                 else {
    2082                         PyMem_FREE(list);
    2083                 }
    2084                 freelist_size += u;
    2085                 list = next;
    2086         }
    2087         return freelist_size;
     2207    PyFloatObject *p;
     2208    PyFloatBlock *list, *next;
     2209    int i;
     2210    int u;                      /* remaining unfreed ints per block */
     2211    int freelist_size = 0;
     2212
     2213    list = block_list;
     2214    block_list = NULL;
     2215    free_list = NULL;
     2216    while (list != NULL) {
     2217        u = 0;
     2218        for (i = 0, p = &list->objects[0];
     2219             i < N_FLOATOBJECTS;
     2220             i++, p++) {
     2221            if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
     2222                u++;
     2223        }
     2224        next = list->next;
     2225        if (u) {
     2226            list->next = block_list;
     2227            block_list = list;
     2228            for (i = 0, p = &list->objects[0];
     2229                 i < N_FLOATOBJECTS;
     2230                 i++, p++) {
     2231                if (!PyFloat_CheckExact(p) ||
     2232                    Py_REFCNT(p) == 0) {
     2233                    Py_TYPE(p) = (struct _typeobject *)
     2234                        free_list;
     2235                    free_list = p;
     2236                }
     2237            }
     2238        }
     2239        else {
     2240            PyMem_FREE(list);
     2241        }
     2242        freelist_size += u;
     2243        list = next;
     2244    }
     2245    return freelist_size;
    20882246}
    20892247
     
    20912249PyFloat_Fini(void)
    20922250{
    2093         PyFloatObject *p;
    2094         PyFloatBlock *list;
    2095         int i;
    2096         int u;                  /* total unfreed floats per block */
    2097 
    2098         u = PyFloat_ClearFreeList();
    2099 
    2100         if (!Py_VerboseFlag)
    2101                 return;
    2102         fprintf(stderr, "# cleanup floats");
    2103         if (!u) {
    2104                 fprintf(stderr, "\n");
    2105         }
    2106         else {
    2107                 fprintf(stderr,
    2108                         ": %d unfreed float%s\n",
    2109                         u, u == 1 ? "" : "s");
    2110         }
    2111         if (Py_VerboseFlag > 1) {
    2112                 list = block_list;
    2113                 while (list != NULL) {
    2114                         for (i = 0, p = &list->objects[0];
    2115                              i < N_FLOATOBJECTS;
    2116                              i++, p++) {
    2117                                 if (PyFloat_CheckExact(p) &&
    2118                                     Py_REFCNT(p) != 0) {
    2119                                         char buf[100];
    2120                                         PyFloat_AsString(buf, p);
    2121                                         /* XXX(twouters) cast refcount to
    2122                                            long until %zd is universally
    2123                                            available
    2124                                          */
    2125                                         fprintf(stderr,
    2126                              "#   <float at %p, refcnt=%ld, val=%s>\n",
    2127                                                 p, (long)Py_REFCNT(p), buf);
    2128                                 }
    2129                         }
    2130                         list = list->next;
    2131                 }
    2132         }
     2251    PyFloatObject *p;
     2252    PyFloatBlock *list;
     2253    int i;
     2254    int u;                      /* total unfreed floats per block */
     2255
     2256    u = PyFloat_ClearFreeList();
     2257
     2258    if (!Py_VerboseFlag)
     2259        return;
     2260    fprintf(stderr, "# cleanup floats");
     2261    if (!u) {
     2262        fprintf(stderr, "\n");
     2263    }
     2264    else {
     2265        fprintf(stderr,
     2266            ": %d unfreed float%s\n",
     2267            u, u == 1 ? "" : "s");
     2268    }
     2269    if (Py_VerboseFlag > 1) {
     2270        list = block_list;
     2271        while (list != NULL) {
     2272            for (i = 0, p = &list->objects[0];
     2273                 i < N_FLOATOBJECTS;
     2274                 i++, p++) {
     2275                if (PyFloat_CheckExact(p) &&
     2276                    Py_REFCNT(p) != 0) {
     2277                    char *buf = PyOS_double_to_string(
     2278                        PyFloat_AS_DOUBLE(p), 'r',
     2279                        0, 0, NULL);
     2280                    if (buf) {
     2281                        /* XXX(twouters) cast
     2282                           refcount to long
     2283                           until %zd is
     2284                           universally
     2285                           available
     2286                        */
     2287                        fprintf(stderr,
     2288                 "#   <float at %p, refcnt=%ld, val=%s>\n",
     2289                                    p, (long)Py_REFCNT(p), buf);
     2290                                    PyMem_Free(buf);
     2291                            }
     2292                }
     2293            }
     2294            list = list->next;
     2295        }
     2296    }
    21332297}
    21342298
     
    21392303_PyFloat_Pack4(double x, unsigned char *p, int le)
    21402304{
    2141         if (float_format == unknown_format) {
    2142                 unsigned char sign;
    2143                 int e;
    2144                 double f;
    2145                 unsigned int fbits;
    2146                 int incr = 1;
    2147 
    2148                 if (le) {
    2149                         p += 3;
    2150                         incr = -1;
    2151                 }
    2152 
    2153                 if (x < 0) {
    2154                         sign = 1;
    2155                         x = -x;
    2156                 }
    2157                 else
    2158                         sign = 0;
    2159 
    2160                 f = frexp(x, &e);
    2161 
    2162                 /* Normalize f to be in the range [1.0, 2.0) */
    2163                 if (0.5 <= f && f < 1.0) {
    2164                         f *= 2.0;
    2165                         e--;
    2166                 }
    2167                 else if (f == 0.0)
    2168                         e = 0;
    2169                 else {
    2170                         PyErr_SetString(PyExc_SystemError,
    2171                                         "frexp() result out of range");
    2172                         return -1;
    2173                 }
    2174 
    2175                 if (e >= 128)
    2176                         goto Overflow;
    2177                 else if (e < -126) {
    2178                         /* Gradual underflow */
    2179                         f = ldexp(f, 126 + e);
    2180                         e = 0;
    2181                 }
    2182                 else if (!(e == 0 && f == 0.0)) {
    2183                         e += 127;
    2184                         f -= 1.0; /* Get rid of leading 1 */
    2185                 }
    2186 
    2187                 f *= 8388608.0; /* 2**23 */
    2188                 fbits = (unsigned int)(f + 0.5); /* Round */
    2189                 assert(fbits <= 8388608);
    2190                 if (fbits >> 23) {
    2191                         /* The carry propagated out of a string of 23 1 bits. */
    2192                         fbits = 0;
    2193                         ++e;
    2194                         if (e >= 255)
    2195                                 goto Overflow;
    2196                 }
    2197 
    2198                 /* First byte */
    2199                 *p = (sign << 7) | (e >> 1);
    2200                 p += incr;
    2201 
    2202                 /* Second byte */
    2203                 *p = (char) (((e & 1) << 7) | (fbits >> 16));
    2204                 p += incr;
    2205 
    2206                 /* Third byte */
    2207                 *p = (fbits >> 8) & 0xFF;
    2208                 p += incr;
    2209 
    2210                 /* Fourth byte */
    2211                 *p = fbits & 0xFF;
    2212 
    2213                 /* Done */
    2214                 return 0;
    2215 
    2216         }
    2217         else {
    2218                 float y = (float)x;
    2219                 const char *s = (char*)&y;
    2220                 int i, incr = 1;
    2221 
    2222                 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
    2223                         goto Overflow;
    2224 
    2225                 if ((float_format == ieee_little_endian_format && !le)
    2226                     || (float_format == ieee_big_endian_format && le)) {
    2227                         p += 3;
    2228                         incr = -1;
    2229                 }
    2230 
    2231                 for (i = 0; i < 4; i++) {
    2232                         *p = *s++;
    2233                         p += incr;
    2234                 }
    2235                 return 0;
    2236         }
     2305    if (float_format == unknown_format) {
     2306        unsigned char sign;
     2307        int e;
     2308        double f;
     2309        unsigned int fbits;
     2310        int incr = 1;
     2311
     2312        if (le) {
     2313            p += 3;
     2314            incr = -1;
     2315        }
     2316
     2317        if (x < 0) {
     2318            sign = 1;
     2319            x = -x;
     2320        }
     2321        else
     2322            sign = 0;
     2323
     2324        f = frexp(x, &e);
     2325
     2326        /* Normalize f to be in the range [1.0, 2.0) */
     2327        if (0.5 <= f && f < 1.0) {
     2328            f *= 2.0;
     2329            e--;
     2330        }
     2331        else if (f == 0.0)
     2332            e = 0;
     2333        else {
     2334            PyErr_SetString(PyExc_SystemError,
     2335                            "frexp() result out of range");
     2336            return -1;
     2337        }
     2338
     2339        if (e >= 128)
     2340            goto Overflow;
     2341        else if (e < -126) {
     2342            /* Gradual underflow */
     2343            f = ldexp(f, 126 + e);
     2344            e = 0;
     2345        }
     2346        else if (!(e == 0 && f == 0.0)) {
     2347            e += 127;
     2348            f -= 1.0; /* Get rid of leading 1 */
     2349        }
     2350
     2351        f *= 8388608.0; /* 2**23 */
     2352        fbits = (unsigned int)(f + 0.5); /* Round */
     2353        assert(fbits <= 8388608);
     2354        if (fbits >> 23) {
     2355            /* The carry propagated out of a string of 23 1 bits. */
     2356            fbits = 0;
     2357            ++e;
     2358            if (e >= 255)
     2359                goto Overflow;
     2360        }
     2361
     2362        /* First byte */
     2363        *p = (sign << 7) | (e >> 1);
     2364        p += incr;
     2365
     2366        /* Second byte */
     2367        *p = (char) (((e & 1) << 7) | (fbits >> 16));
     2368        p += incr;
     2369
     2370        /* Third byte */
     2371        *p = (fbits >> 8) & 0xFF;
     2372        p += incr;
     2373
     2374        /* Fourth byte */
     2375        *p = fbits & 0xFF;
     2376
     2377        /* Done */
     2378        return 0;
     2379
     2380    }
     2381    else {
     2382        float y = (float)x;
     2383        const char *s = (char*)&y;
     2384        int i, incr = 1;
     2385
     2386        if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
     2387            goto Overflow;
     2388
     2389        if ((float_format == ieee_little_endian_format && !le)
     2390            || (float_format == ieee_big_endian_format && le)) {
     2391            p += 3;
     2392            incr = -1;
     2393        }
     2394
     2395        for (i = 0; i < 4; i++) {
     2396            *p = *s++;
     2397            p += incr;
     2398        }
     2399        return 0;
     2400    }
    22372401  Overflow:
    2238         PyErr_SetString(PyExc_OverflowError,
    2239                         "float too large to pack with f format");
    2240         return -1;
     2402    PyErr_SetString(PyExc_OverflowError,
     2403                    "float too large to pack with f format");
     2404    return -1;
    22412405}
    22422406
     
    22442408_PyFloat_Pack8(double x, unsigned char *p, int le)
    22452409{
    2246         if (double_format == unknown_format) {
    2247                 unsigned char sign;
    2248                 int e;
    2249                 double f;
    2250                 unsigned int fhi, flo;
    2251                 int incr = 1;
    2252 
    2253                 if (le) {
    2254                         p += 7;
    2255                         incr = -1;
    2256                 }
    2257 
    2258                 if (x < 0) {
    2259                         sign = 1;
    2260                         x = -x;
    2261                 }
    2262                 else
    2263                         sign = 0;
    2264 
    2265                 f = frexp(x, &e);
    2266 
    2267                 /* Normalize f to be in the range [1.0, 2.0) */
    2268                 if (0.5 <= f && f < 1.0) {
    2269                         f *= 2.0;
    2270                         e--;
    2271                 }
    2272                 else if (f == 0.0)
    2273                         e = 0;
    2274                 else {
    2275                         PyErr_SetString(PyExc_SystemError,
    2276                                         "frexp() result out of range");
    2277                         return -1;
    2278                 }
    2279 
    2280                 if (e >= 1024)
    2281                         goto Overflow;
    2282                 else if (e < -1022) {
    2283                         /* Gradual underflow */
    2284                         f = ldexp(f, 1022 + e);
    2285                         e = 0;
    2286                 }
    2287                 else if (!(e == 0 && f == 0.0)) {
    2288                         e += 1023;
    2289                         f -= 1.0; /* Get rid of leading 1 */
    2290                 }
    2291 
    2292                 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
    2293                 f *= 268435456.0; /* 2**28 */
    2294                 fhi = (unsigned int)f; /* Truncate */
    2295                 assert(fhi < 268435456);
    2296 
    2297                 f -= (double)fhi;
    2298                 f *= 16777216.0; /* 2**24 */
    2299                 flo = (unsigned int)(f + 0.5); /* Round */
    2300                 assert(flo <= 16777216);
    2301                 if (flo >> 24) {
    2302                         /* The carry propagated out of a string of 24 1 bits. */
    2303                         flo = 0;
    2304                         ++fhi;
    2305                         if (fhi >> 28) {
    2306                                 /* And it also progagated out of the next 28 bits. */
    2307                                 fhi = 0;
    2308                                 ++e;
    2309                                 if (e >= 2047)
    2310                                         goto Overflow;
    2311                         }
    2312                 }
    2313 
    2314                 /* First byte */
    2315                 *p = (sign << 7) | (e >> 4);
    2316                 p += incr;
    2317 
    2318                 /* Second byte */
    2319                 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
    2320                 p += incr;
    2321 
    2322                 /* Third byte */
    2323                 *p = (fhi >> 16) & 0xFF;
    2324                 p += incr;
    2325 
    2326                 /* Fourth byte */
    2327                 *p = (fhi >> 8) & 0xFF;
    2328                 p += incr;
    2329 
    2330                 /* Fifth byte */
    2331                 *p = fhi & 0xFF;
    2332                 p += incr;
    2333 
    2334                 /* Sixth byte */
    2335                 *p = (flo >> 16) & 0xFF;
    2336                 p += incr;
    2337 
    2338                 /* Seventh byte */
    2339                 *p = (flo >> 8) & 0xFF;
    2340                 p += incr;
    2341 
    2342                 /* Eighth byte */
    2343                 *p = flo & 0xFF;
    2344                 p += incr;
    2345 
    2346                 /* Done */
    2347                 return 0;
    2348 
    2349           Overflow:
    2350                 PyErr_SetString(PyExc_OverflowError,
    2351                                 "float too large to pack with d format");
    2352                 return -1;
    2353         }
    2354         else {
    2355                 const char *s = (char*)&x;
    2356                 int i, incr = 1;
    2357 
    2358                 if ((double_format == ieee_little_endian_format && !le)
    2359                     || (double_format == ieee_big_endian_format && le)) {
    2360                         p += 7;
    2361                         incr = -1;
    2362                 }
    2363                
    2364                 for (i = 0; i < 8; i++) {
    2365                         *p = *s++;
    2366                         p += incr;
    2367                 }
    2368                 return 0;
    2369         }
     2410    if (double_format == unknown_format) {
     2411        unsigned char sign;
     2412        int e;
     2413        double f;
     2414        unsigned int fhi, flo;
     2415        int incr = 1;
     2416
     2417        if (le) {
     2418            p += 7;
     2419            incr = -1;
     2420        }
     2421
     2422        if (x < 0) {
     2423            sign = 1;
     2424            x = -x;
     2425        }
     2426        else
     2427            sign = 0;
     2428
     2429        f = frexp(x, &e);
     2430
     2431        /* Normalize f to be in the range [1.0, 2.0) */
     2432        if (0.5 <= f && f < 1.0) {
     2433            f *= 2.0;
     2434            e--;
     2435        }
     2436        else if (f == 0.0)
     2437            e = 0;
     2438        else {
     2439            PyErr_SetString(PyExc_SystemError,
     2440                            "frexp() result out of range");
     2441            return -1;
     2442        }
     2443
     2444        if (e >= 1024)
     2445            goto Overflow;
     2446        else if (e < -1022) {
     2447            /* Gradual underflow */
     2448            f = ldexp(f, 1022 + e);
     2449            e = 0;
     2450        }
     2451        else if (!(e == 0 && f == 0.0)) {
     2452            e += 1023;
     2453            f -= 1.0; /* Get rid of leading 1 */
     2454        }
     2455
     2456        /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
     2457        f *= 268435456.0; /* 2**28 */
     2458        fhi = (unsigned int)f; /* Truncate */
     2459        assert(fhi < 268435456);
     2460
     2461        f -= (double)fhi;
     2462        f *= 16777216.0; /* 2**24 */
     2463        flo = (unsigned int)(f + 0.5); /* Round */
     2464        assert(flo <= 16777216);
     2465        if (flo >> 24) {
     2466            /* The carry propagated out of a string of 24 1 bits. */
     2467            flo = 0;
     2468            ++fhi;
     2469            if (fhi >> 28) {
     2470                /* And it also progagated out of the next 28 bits. */
     2471                fhi = 0;
     2472                ++e;
     2473                if (e >= 2047)
     2474                    goto Overflow;
     2475            }
     2476        }
     2477
     2478        /* First byte */
     2479        *p = (sign << 7) | (e >> 4);
     2480        p += incr;
     2481
     2482        /* Second byte */
     2483        *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
     2484        p += incr;
     2485
     2486        /* Third byte */
     2487        *p = (fhi >> 16) & 0xFF;
     2488        p += incr;
     2489
     2490        /* Fourth byte */
     2491        *p = (fhi >> 8) & 0xFF;
     2492        p += incr;
     2493
     2494        /* Fifth byte */
     2495        *p = fhi & 0xFF;
     2496        p += incr;
     2497
     2498        /* Sixth byte */
     2499        *p = (flo >> 16) & 0xFF;
     2500        p += incr;
     2501
     2502        /* Seventh byte */
     2503        *p = (flo >> 8) & 0xFF;
     2504        p += incr;
     2505
     2506        /* Eighth byte */
     2507        *p = flo & 0xFF;
     2508        /* p += incr; Unneeded (for now) */
     2509
     2510        /* Done */
     2511        return 0;
     2512
     2513      Overflow:
     2514        PyErr_SetString(PyExc_OverflowError,
     2515                        "float too large to pack with d format");
     2516        return -1;
     2517    }
     2518    else {
     2519        const char *s = (char*)&x;
     2520        int i, incr = 1;
     2521
     2522        if ((double_format == ieee_little_endian_format && !le)
     2523            || (double_format == ieee_big_endian_format && le)) {
     2524            p += 7;
     2525            incr = -1;
     2526        }
     2527
     2528        for (i = 0; i < 8; i++) {
     2529            *p = *s++;
     2530            p += incr;
     2531        }
     2532        return 0;
     2533    }
    23702534}
    23712535
     
    23732537_PyFloat_Unpack4(const unsigned char *p, int le)
    23742538{
    2375         if (float_format == unknown_format) {
    2376                 unsigned char sign;
    2377                 int e;
    2378                 unsigned int f;
    2379                 double x;
    2380                 int incr = 1;
    2381 
    2382                 if (le) {
    2383                         p += 3;
    2384                         incr = -1;
    2385                 }
    2386 
    2387                 /* First byte */
    2388                 sign = (*p >> 7) & 1;
    2389                 e = (*p & 0x7F) << 1;
    2390                 p += incr;
    2391 
    2392                 /* Second byte */
    2393                 e |= (*p >> 7) & 1;
    2394                 f = (*p & 0x7F) << 16;
    2395                 p += incr;
    2396 
    2397                 if (e == 255) {
    2398                         PyErr_SetString(
    2399                                 PyExc_ValueError,
    2400                                 "can't unpack IEEE 754 special value "
    2401                                 "on non-IEEE platform");
    2402                         return -1;
    2403                 }
    2404 
    2405                 /* Third byte */
    2406                 f |= *p << 8;
    2407                 p += incr;
    2408 
    2409                 /* Fourth byte */
    2410                 f |= *p;
    2411 
    2412                 x = (double)f / 8388608.0;
    2413 
    2414                 /* XXX This sadly ignores Inf/NaN issues */
    2415                 if (e == 0)
    2416                         e = -126;
    2417                 else {
    2418                         x += 1.0;
    2419                         e -= 127;
    2420                 }
    2421                 x = ldexp(x, e);
    2422 
    2423                 if (sign)
    2424                         x = -x;
    2425 
    2426                 return x;
    2427         }
    2428         else {
    2429                 float x;
    2430 
    2431                 if ((float_format == ieee_little_endian_format && !le)
    2432                     || (float_format == ieee_big_endian_format && le)) {
    2433                         char buf[4];
    2434                         char *d = &buf[3];
    2435                         int i;
    2436 
    2437                         for (i = 0; i < 4; i++) {
    2438                                 *d-- = *p++;
    2439                         }
    2440                         memcpy(&x, buf, 4);
    2441                 }
    2442                 else {
    2443                         memcpy(&x, p, 4);
    2444                 }
    2445 
    2446                 return x;
    2447         }               
     2539    if (float_format == unknown_format) {
     2540        unsigned char sign;
     2541        int e;
     2542        unsigned int f;
     2543        double x;
     2544        int incr = 1;
     2545
     2546        if (le) {
     2547            p += 3;
     2548            incr = -1;
     2549        }
     2550
     2551        /* First byte */
     2552        sign = (*p >> 7) & 1;
     2553        e = (*p & 0x7F) << 1;
     2554        p += incr;
     2555
     2556        /* Second byte */
     2557        e |= (*p >> 7) & 1;
     2558        f = (*p & 0x7F) << 16;
     2559        p += incr;
     2560
     2561        if (e == 255) {
     2562            PyErr_SetString(
     2563                PyExc_ValueError,
     2564                "can't unpack IEEE 754 special value "
     2565                "on non-IEEE platform");
     2566            return -1;
     2567        }
     2568
     2569        /* Third byte */
     2570        f |= *p << 8;
     2571        p += incr;
     2572
     2573        /* Fourth byte */
     2574        f |= *p;
     2575
     2576        x = (double)f / 8388608.0;
     2577
     2578        /* XXX This sadly ignores Inf/NaN issues */
     2579        if (e == 0)
     2580            e = -126;
     2581        else {
     2582            x += 1.0;
     2583            e -= 127;
     2584        }
     2585        x = ldexp(x, e);
     2586
     2587        if (sign)
     2588            x = -x;
     2589
     2590        return x;
     2591    }
     2592    else {
     2593        float x;
     2594
     2595        if ((float_format == ieee_little_endian_format && !le)
     2596            || (float_format == ieee_big_endian_format && le)) {
     2597            char buf[4];
     2598            char *d = &buf[3];
     2599            int i;
     2600
     2601            for (i = 0; i < 4; i++) {
     2602                *d-- = *p++;
     2603            }
     2604            memcpy(&x, buf, 4);
     2605        }
     2606        else {
     2607            memcpy(&x, p, 4);
     2608        }
     2609
     2610        return x;
     2611    }
    24482612}
    24492613
     
    24512615_PyFloat_Unpack8(const unsigned char *p, int le)
    24522616{
    2453         if (double_format == unknown_format) {
    2454                 unsigned char sign;
    2455                 int e;
    2456                 unsigned int fhi, flo;
    2457                 double x;
    2458                 int incr = 1;
    2459 
    2460                 if (le) {
    2461                         p += 7;
    2462                         incr = -1;
    2463                 }
    2464 
    2465                 /* First byte */
    2466                 sign = (*p >> 7) & 1;
    2467                 e = (*p & 0x7F) << 4;
    2468                
    2469                 p += incr;
    2470 
    2471                 /* Second byte */
    2472                 e |= (*p >> 4) & 0xF;
    2473                 fhi = (*p & 0xF) << 24;
    2474                 p += incr;
    2475 
    2476                 if (e == 2047) {
    2477                         PyErr_SetString(
    2478                                 PyExc_ValueError,
    2479                                 "can't unpack IEEE 754 special value "
    2480                                 "on non-IEEE platform");
    2481                         return -1.0;
    2482                 }
    2483 
    2484                 /* Third byte */
    2485                 fhi |= *p << 16;
    2486                 p += incr;
    2487 
    2488                 /* Fourth byte */
    2489                 fhi |= *p  << 8;
    2490                 p += incr;
    2491 
    2492                 /* Fifth byte */
    2493                 fhi |= *p;
    2494                 p += incr;
    2495 
    2496                 /* Sixth byte */
    2497                 flo = *p << 16;
    2498                 p += incr;
    2499 
    2500                 /* Seventh byte */
    2501                 flo |= *p << 8;
    2502                 p += incr;
    2503 
    2504                 /* Eighth byte */
    2505                 flo |= *p;
    2506 
    2507                 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
    2508                 x /= 268435456.0; /* 2**28 */
    2509 
    2510                 if (e == 0)
    2511                         e = -1022;
    2512                 else {
    2513                         x += 1.0;
    2514                         e -= 1023;
    2515                 }
    2516                 x = ldexp(x, e);
    2517 
    2518                 if (sign)
    2519                         x = -x;
    2520 
    2521                 return x;
    2522         }
    2523         else {
    2524                 double x;
    2525 
    2526                 if ((double_format == ieee_little_endian_format && !le)
    2527                     || (double_format == ieee_big_endian_format && le)) {
    2528                         char buf[8];
    2529                         char *d = &buf[7];
    2530                         int i;
    2531                        
    2532                         for (i = 0; i < 8; i++) {
    2533                                 *d-- = *p++;
    2534                         }
    2535                         memcpy(&x, buf, 8);
    2536                 }
    2537                 else {
    2538                         memcpy(&x, p, 8);
    2539                 }
    2540 
    2541                 return x;
    2542         }
    2543 }
     2617    if (double_format == unknown_format) {
     2618        unsigned char sign;
     2619        int e;
     2620        unsigned int fhi, flo;
     2621        double x;
     2622        int incr = 1;
     2623
     2624        if (le) {
     2625            p += 7;
     2626            incr = -1;
     2627        }
     2628
     2629        /* First byte */
     2630        sign = (*p >> 7) & 1;
     2631        e = (*p & 0x7F) << 4;
     2632
     2633        p += incr;
     2634
     2635        /* Second byte */
     2636        e |= (*p >> 4) & 0xF;
     2637        fhi = (*p & 0xF) << 24;
     2638        p += incr;
     2639
     2640        if (e == 2047) {
     2641            PyErr_SetString(
     2642                PyExc_ValueError,
     2643                "can't unpack IEEE 754 special value "
     2644                "on non-IEEE platform");
     2645            return -1.0;
     2646        }
     2647
     2648        /* Third byte */
     2649        fhi |= *p << 16;
     2650        p += incr;
     2651
     2652        /* Fourth byte */
     2653        fhi |= *p  << 8;
     2654        p += incr;
     2655
     2656        /* Fifth byte */
     2657        fhi |= *p;
     2658        p += incr;
     2659
     2660        /* Sixth byte */
     2661        flo = *p << 16;
     2662        p += incr;
     2663
     2664        /* Seventh byte */
     2665        flo |= *p << 8;
     2666        p += incr;
     2667
     2668        /* Eighth byte */
     2669        flo |= *p;
     2670
     2671        x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
     2672        x /= 268435456.0; /* 2**28 */
     2673
     2674        if (e == 0)
     2675            e = -1022;
     2676        else {
     2677            x += 1.0;
     2678            e -= 1023;
     2679        }
     2680        x = ldexp(x, e);
     2681
     2682        if (sign)
     2683            x = -x;
     2684
     2685        return x;
     2686    }
     2687    else {
     2688        double x;
     2689
     2690        if ((double_format == ieee_little_endian_format && !le)
     2691            || (double_format == ieee_big_endian_format && le)) {
     2692            char buf[8];
     2693            char *d = &buf[7];
     2694            int i;
     2695
     2696            for (i = 0; i < 8; i++) {
     2697                *d-- = *p++;
     2698            }
     2699            memcpy(&x, buf, 8);
     2700        }
     2701        else {
     2702            memcpy(&x, p, 8);
     2703        }
     2704
     2705        return x;
     2706    }
     2707}
Note: See TracChangeset for help on using the changeset viewer.