mirror of
https://github.com/DaveGamble/cJSON.git
synced 2024-12-26 12:41:03 +08:00
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:
parent
f09bdef15e
commit
0747669972
71
cJSON.c
71
cJSON.c
@ -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 */
|
||||
|
Loading…
x
Reference in New Issue
Block a user