parse_number: Switch to C library's strtod

Replaces the hand written floating point parser with the C library
implementation.
This commit is contained in:
Max Bruckner 2017-02-03 22:09:04 +01:00
parent f09bdef15e
commit 0747669972

71
cJSON.c
View File

@ -164,83 +164,34 @@ void cJSON_Delete(cJSON *c)
/* Parse the input text to generate a number, and populate the result into item. */ /* Parse the input text to generate a number, and populate the result into item. */
static const unsigned char *parse_number(cJSON *item, const unsigned char *num) static const unsigned char *parse_number(cJSON *item, const unsigned char *num)
{ {
double n = 0; double number = 0;
double sign = 1; unsigned char *endpointer = NULL;
double scale = 0;
int subscale = 0;
int signsubscale = 1;
/* Has sign? */ number = strtod((const char*)num, (char**)&endpointer);
if (*num == '-') if ((num == endpointer) || (num == NULL))
{ {
sign = -1; /* parse_error */
num++; return NULL;
}
/* is zero */
if (*num == '0')
{
num++;
}
/* Number? */
if ((*num >= '1') && (*num <= '9'))
{
do
{
n = (n * 10.0) + (*num++ - '0');
}
while ((*num >= '0') && (*num<='9'));
}
/* Fractional part? */
if ((*num == '.') && (num[1] >= '0') && (num[1] <= '9'))
{
num++;
do
{
n = (n *10.0) + (*num++ - '0');
scale--;
} while ((*num >= '0') && (*num <= '9'));
}
/* Exponent? */
if ((*num == 'e') || (*num == 'E'))
{
num++;
/* With sign? */
if (*num == '+')
{
num++;
}
else if (*num == '-')
{
signsubscale = -1;
num++;
}
/* Number? */
while ((*num>='0') && (*num<='9'))
{
subscale = (subscale * 10) + (*num++ - '0');
}
} }
/* number = +/- number.fraction * 10^+/- exponent */ item->valuedouble = number;
n = sign * n * pow(10.0, (scale + subscale * signsubscale));
item->valuedouble = n;
/* use saturation in case of overflow */ /* use saturation in case of overflow */
if (n >= INT_MAX) if (number >= INT_MAX)
{ {
item->valueint = INT_MAX; item->valueint = INT_MAX;
} }
else if (n <= INT_MIN) else if (number <= INT_MIN)
{ {
item->valueint = INT_MIN; item->valueint = INT_MIN;
} }
else else
{ {
item->valueint = (int)n; item->valueint = (int)number;
} }
item->type = cJSON_Number; item->type = cJSON_Number;
return num; return endpointer;
} }
/* calculate the next largest power of 2 */ /* calculate the next largest power of 2 */