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