Render an array to text */
| 578 | |
| 579 | /* Render an array to text */ |
| 580 | static char *print_array(cJSON *item, int depth, int fmt) |
| 581 | { |
| 582 | char **entries; |
| 583 | char *out = 0, *ptr, *ret; |
| 584 | int len = 5; |
| 585 | cJSON *child = item->child; |
| 586 | int numentries = 0, i = 0, fail = 0; |
| 587 | |
| 588 | /* How many entries in the array? */ |
| 589 | while (child) |
| 590 | numentries++, child = child->next; |
| 591 | /* Allocate an array to hold the values for each */ |
| 592 | entries = (char**) cJSON_malloc(numentries * sizeof(char*)); |
| 593 | if (!entries) |
| 594 | return 0; |
| 595 | memset(entries, 0, numentries * sizeof(char*)); |
| 596 | /* Retrieve all the results: */ |
| 597 | child = item->child; |
| 598 | while (child && !fail) |
| 599 | { |
| 600 | ret = print_value(child, depth + 1, fmt); |
| 601 | entries[i++] = ret; |
| 602 | if (ret) |
| 603 | len += strlen(ret) + 2 + (fmt ? 1 : 0); |
| 604 | else |
| 605 | fail = 1; |
| 606 | child = child->next; |
| 607 | } |
| 608 | |
| 609 | /* If we didn't fail, try to malloc the output string */ |
| 610 | if (!fail) |
| 611 | out = (char*) cJSON_malloc(len); |
| 612 | /* If that fails, we fail. */ |
| 613 | if (!out) |
| 614 | fail = 1; |
| 615 | |
| 616 | /* Handle failure. */ |
| 617 | if (fail) |
| 618 | { |
| 619 | for (i = 0; i < numentries; i++) |
| 620 | if (entries[i]) |
| 621 | cJSON_free(entries[i]); |
| 622 | cJSON_free(entries); |
| 623 | return 0; |
| 624 | } |
| 625 | |
| 626 | /* Compose the output array. */ |
| 627 | *out = '['; |
| 628 | ptr = out + 1; |
| 629 | *ptr = 0; |
| 630 | for (i = 0; i < numentries; i++) |
| 631 | { |
| 632 | strcpy(ptr, entries[i]); |
| 633 | ptr += strlen(entries[i]); |
| 634 | if (i != numentries - 1) |
| 635 | { |
| 636 | *ptr++ = ','; |
| 637 | if (fmt) |
no test coverage detected