Render the number nicely from the given item into a string. */
| 483 | |
| 484 | /* Render the number nicely from the given item into a string. */ |
| 485 | static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) |
| 486 | { |
| 487 | unsigned char *output_pointer = NULL; |
| 488 | double d = item->valuedouble; |
| 489 | int length = 0; |
| 490 | size_t i = 0; |
| 491 | unsigned char number_buffer[26]; /* temporary buffer to print the number into */ |
| 492 | unsigned char decimal_point = get_decimal_point(); |
| 493 | double test; |
| 494 | |
| 495 | if (output_buffer == NULL) |
| 496 | { |
| 497 | return false; |
| 498 | } |
| 499 | |
| 500 | /* For integer which is out of the range of [INT_MIN, INT_MAX], valuestring is an integer literal. */ |
| 501 | if (item->valuestring) |
| 502 | { |
| 503 | length = sprintf((char*)number_buffer, "%s", item->valuestring); |
| 504 | } |
| 505 | /* This checks for NaN and Infinity */ |
| 506 | else if ((d * 0) != 0) |
| 507 | { |
| 508 | length = sprintf((char*)number_buffer, "null"); |
| 509 | } |
| 510 | else |
| 511 | { |
| 512 | /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ |
| 513 | length = sprintf((char*)number_buffer, "%1.15g", d); |
| 514 | |
| 515 | /* Check whether the original double can be recovered */ |
| 516 | if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || ((double)test != d)) |
| 517 | { |
| 518 | /* If not, print with 17 decimal places of precision */ |
| 519 | length = sprintf((char*)number_buffer, "%1.17g", d); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | /* sprintf failed or buffer overrun occurred */ |
| 524 | if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) |
| 525 | { |
| 526 | return false; |
| 527 | } |
| 528 | |
| 529 | /* reserve appropriate space in the output */ |
| 530 | output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); |
| 531 | if (output_pointer == NULL) |
| 532 | { |
| 533 | return false; |
| 534 | } |
| 535 | |
| 536 | /* copy the printed number to the output and replace locale |
| 537 | * dependent decimal point with '.' */ |
| 538 | for (i = 0; i < ((size_t)length); i++) |
| 539 | { |
| 540 | if (number_buffer[i] == decimal_point) |
| 541 | { |
| 542 | output_pointer[i] = '.'; |
no test coverage detected