From 074766997246481dfc72bfa78f07898a2716473f Mon Sep 17 00:00:00 2001 From: Max Bruckner Date: Fri, 3 Feb 2017 22:09:04 +0100 Subject: [PATCH] parse_number: Switch to C library's strtod Replaces the hand written floating point parser with the C library implementation. --- cJSON.c | 71 +++++++++------------------------------------------------ 1 file changed, 11 insertions(+), 60 deletions(-) diff --git a/cJSON.c b/cJSON.c index b64e4e7..e2efd31 100644 --- a/cJSON.c +++ b/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 */