Skip to content

Commit

Permalink
parse_number: Switch to C library's strtod
Browse files Browse the repository at this point in the history
Replaces the hand written floating point parser with the C library
implementation.
  • Loading branch information
FSMaxB committed Feb 7, 2017
1 parent f09bdef commit 0747669
Showing 1 changed file with 11 additions and 60 deletions.
71 changes: 11 additions & 60 deletions cJSON.c
Expand Up @@ -164,83 +164,34 @@ void cJSON_Delete(cJSON *c)
/* 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)
{
double n = 0;
double sign = 1;
double scale = 0;
int subscale = 0;
int signsubscale = 1;
double number = 0;
unsigned char *endpointer = NULL;

/* Has sign? */
if (*num == '-')
number = strtod((const char*)num, (char**)&endpointer);
if ((num == endpointer) || (num == NULL))
{
sign = -1;
num++;
}
/* 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');
}
/* parse_error */
return NULL;
}

/* number = +/- number.fraction * 10^+/- exponent */
n = sign * n * pow(10.0, (scale + subscale * signsubscale));
item->valuedouble = number;

item->valuedouble = n;
/* use saturation in case of overflow */
if (n >= INT_MAX)
if (number >= INT_MAX)
{
item->valueint = INT_MAX;
}
else if (n <= INT_MIN)
else if (number <= INT_MIN)
{
item->valueint = INT_MIN;
}
else
{
item->valueint = (int)n;
item->valueint = (int)number;
}
item->type = cJSON_Number;

return num;
return endpointer;
}

/* calculate the next largest power of 2 */
Expand Down

0 comments on commit 0747669

Please sign in to comment.