Render the number nicely from the given item into a string. */
| 589 | |
| 590 | /* Render the number nicely from the given item into a string. */ |
| 591 | static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) |
| 592 | { |
| 593 | unsigned char *output_pointer = NULL; |
| 594 | double d = item->valuedouble; |
| 595 | int length = 0; |
| 596 | size_t i = 0; |
| 597 | unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ |
| 598 | unsigned char decimal_point = get_decimal_point(); |
| 599 | double test = 0.0; |
| 600 | |
| 601 | if (output_buffer == NULL) |
| 602 | { |
| 603 | return false; |
| 604 | } |
| 605 | |
| 606 | /* This checks for NaN and Infinity */ |
| 607 | if (isnan(d) || isinf(d)) |
| 608 | { |
| 609 | length = sprintf((char*)number_buffer, "null"); |
| 610 | } |
| 611 | else if(d == (double)item->valueint) |
| 612 | { |
| 613 | length = sprintf((char*)number_buffer, "%d", item->valueint); |
| 614 | } |
| 615 | else |
| 616 | { |
| 617 | /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ |
| 618 | length = sprintf((char*)number_buffer, "%1.15g", d); |
| 619 | |
| 620 | /* Check whether the original double can be recovered */ |
| 621 | if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) |
| 622 | { |
| 623 | /* If not, print with 17 decimal places of precision */ |
| 624 | length = sprintf((char*)number_buffer, "%1.17g", d); |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | /* sprintf failed or buffer overrun occurred */ |
| 629 | if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) |
| 630 | { |
| 631 | return false; |
| 632 | } |
| 633 | |
| 634 | /* reserve appropriate space in the output */ |
| 635 | output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); |
| 636 | if (output_pointer == NULL) |
| 637 | { |
| 638 | return false; |
| 639 | } |
| 640 | |
| 641 | /* copy the printed number to the output and replace locale |
| 642 | * dependent decimal point with '.' */ |
| 643 | for (i = 0; i < ((size_t)length); i++) |
| 644 | { |
| 645 | if (number_buffer[i] == decimal_point) |
| 646 | { |
| 647 | output_pointer[i] = '.'; |
| 648 | continue; |
no test coverage detected
searching dependent graphs…