From 87f77274de6b3af00fb9b9a7f3b900ef382296c2 Mon Sep 17 00:00:00 2001 From: Max Bruckner Date: Tue, 7 Feb 2017 00:05:27 +0100 Subject: [PATCH] cJSON_SetNumberValue: Fix undefined double to int conversion This might cause slight changes in behavior, but it shouldn't break anything that is not already broken (for example the original macro could either return a double, or an integer or whatever depending on if object is NULL or not.) --- cJSON.c | 19 +++++++++++++++++++ cJSON.h | 6 ++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/cJSON.c b/cJSON.c index c53f10e..13d5a02 100644 --- a/cJSON.c +++ b/cJSON.c @@ -194,6 +194,25 @@ static const unsigned char *parse_number(cJSON *item, const unsigned char *num) return endpointer; } +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +double cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = cJSON_Number; + } + + return object->valuedouble = number; +} + /* calculate the next largest power of 2 */ static int pow2gt (int x) { diff --git a/cJSON.h b/cJSON.h index a9bf4f2..8502048 100644 --- a/cJSON.h +++ b/cJSON.h @@ -169,8 +169,10 @@ extern void cJSON_Minify(char *json); #define cJSON_AddRawToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateRaw(s)) /* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object,val) ((object) ? (object)->valueint = (object)->valuedouble = (val) : (val)) -#define cJSON_SetNumberValue(object,val) ((object) ? (object)->valueint = (object)->valuedouble = (val) : (val)) +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +extern double cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object) ? cJSON_SetNumberHelper(object, (double)number) : (number)) /* Macro for iterating over an array */ #define cJSON_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)