is_nan and is_infinity macros

This commit is contained in:
Max Bruckner 2018-01-20 15:14:27 +01:00
parent 1e95d4fe9a
commit 9000f08b17
2 changed files with 24 additions and 2 deletions

View File

@ -470,6 +470,9 @@ static void update_offset(printbuffer * const buffer)
buffer->offset += strlen((const char*)buffer_pointer); buffer->offset += strlen((const char*)buffer_pointer);
} }
#define is_nan(number) (number != number)
#define is_infinity(number) (!is_nan(number) && (number * 0) != 0)
/* Render the number nicely from the given item into a string. */ /* Render the number nicely from the given item into a string. */
static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
{ {
@ -486,8 +489,7 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
return false; return false;
} }
/* This checks for NaN and Infinity */ if (is_nan(d) || is_infinity(d))
if ((d * 0) != 0)
{ {
length = sprintf((char*)number_buffer, "null"); length = sprintf((char*)number_buffer, "null");
} }

View File

@ -527,6 +527,24 @@ static void cjson_add_item_to_object_should_not_use_after_free_when_string_is_al
cJSON_Delete(object); cJSON_Delete(object);
} }
static void is_nan_should_detect_nan(void)
{
double nan = 0.0/0.0;
TEST_ASSERT_TRUE(is_nan(nan));
TEST_ASSERT_FALSE(is_nan(1));
}
static void is_infinity_should_detect_infinity(void)
{
double negative_infinity = -1.0/0.0;
double positive_infinity = 1.0/0.0;
TEST_ASSERT_TRUE(is_infinity(negative_infinity));
TEST_ASSERT_TRUE(is_infinity(positive_infinity));
TEST_ASSERT_FALSE(is_infinity(1));
}
int main(void) int main(void)
{ {
UNITY_BEGIN(); UNITY_BEGIN();
@ -550,6 +568,8 @@ int main(void)
RUN_TEST(cjson_create_object_reference_should_create_an_object_reference); RUN_TEST(cjson_create_object_reference_should_create_an_object_reference);
RUN_TEST(cjson_create_array_reference_should_create_an_array_reference); RUN_TEST(cjson_create_array_reference_should_create_an_array_reference);
RUN_TEST(cjson_add_item_to_object_should_not_use_after_free_when_string_is_aliased); RUN_TEST(cjson_add_item_to_object_should_not_use_after_free_when_string_is_aliased);
RUN_TEST(is_nan_should_detect_nan);
RUN_TEST(is_infinity_should_detect_infinity);
return UNITY_END(); return UNITY_END();
} }