Render the number nicely from the given item into a string. */
| 551 | |
| 552 | /* Render the number nicely from the given item into a string. */ |
| 553 | static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) |
| 554 | { |
| 555 | unsigned char *output_pointer = NULL; |
| 556 | double d = item->valuedouble; |
| 557 | int length = 0; |
| 558 | size_t i = 0; |
| 559 | unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ |
| 560 | unsigned char decimal_point = get_decimal_point(); |
| 561 | double test = 0.0; |
| 562 | |
| 563 | if (output_buffer == NULL) |
| 564 | { |
| 565 | return false; |
| 566 | } |
| 567 | |
| 568 | /* This checks for NaN and Infinity */ |
| 569 | if (isnan(d) || isinf(d)) |
| 570 | { |
| 571 | length = sprintf((char*)number_buffer, "null"); |
| 572 | } |
| 573 | else if(d == (double)item->valueint) |
| 574 | { |
| 575 | length = sprintf((char*)number_buffer, "%d", item->valueint); |
| 576 | } |
| 577 | else |
| 578 | { |
| 579 | /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ |
| 580 | length = sprintf((char*)number_buffer, "%1.15g", d); |
| 581 | |
| 582 | /* Check whether the original double can be recovered */ |
| 583 | if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) |
| 584 | { |
| 585 | /* If not, print with 17 decimal places of precision */ |
| 586 | length = sprintf((char*)number_buffer, "%1.17g", d); |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | /* sprintf failed or buffer overrun occurred */ |
| 591 | if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) |
| 592 | { |
| 593 | return false; |
| 594 | } |
| 595 | |
| 596 | /* reserve appropriate space in the output */ |
| 597 | output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); |
| 598 | if (output_pointer == NULL) |
| 599 | { |
| 600 | return false; |
| 601 | } |
| 602 | |
| 603 | /* copy the printed number to the output and replace locale |
| 604 | * dependent decimal point with '.' */ |
| 605 | for (i = 0; i < ((size_t)length); i++) |
| 606 | { |
| 607 | if (number_buffer[i] == decimal_point) |
| 608 | { |
| 609 | output_pointer[i] = '.'; |
| 610 | continue; |
no test coverage detected