LCOV - code coverage report
Current view: top level - Objects - floatobject.c (source / functions) Hit Total Coverage
Test: CPython lcov report Lines: 177 1078 16.4 %
Date: 2017-04-19 Functions: 19 55 34.5 %

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

Generated by: LCOV version 1.10