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