diff options
Diffstat (limited to 'src/timeline.c')
| -rw-r--r-- | src/timeline.c | 70 | 
1 files changed, 70 insertions, 0 deletions
| diff --git a/src/timeline.c b/src/timeline.c new file mode 100644 index 0000000..c2ca486 --- /dev/null +++ b/src/timeline.c @@ -0,0 +1,70 @@ +#define _POSIX_C_SOURCE 200809L +#include <err.h> +#include <string.h> +#include <jansson.h> +#include "timeline.h" + +struct timeline *timeline_from_json(char *json_data) +{ +    json_t *root; +    json_error_t error; +    struct timeline *t; + +    root = json_loads(json_data, 0, &error); + +    if (!root) { +        fprintf(stderr, "timeline_free(): json root it null\n"); +        return NULL; +    } + +    if (!json_is_array(root)) { +        fprintf(stderr, "timeline_free(): timeline not initialized\n"); +        json_decref(root); +        return NULL; +    } + +    t = calloc(1, sizeof(struct timeline)); +    if (!t) { +        err(1, "timeline_from_json(): failed to allocate memory"); +        json_decref(root); +        return NULL; +    } + +    t->size = json_array_size(root); +    t->statuses = calloc(t->size, sizeof(struct status *)); +    if (!(t->statuses)) { +        err(1, "timeline_from_json(): failed to allocate memory"); +        json_decref(root); +        return NULL; +    } + +    for (size_t i = 0; i < t->size; i++) { +        json_t *data; +        data = json_array_get(root, i); +        if (!data) +            goto error; +        t->statuses[i] = status_from_json_t(data); +        if (!(t->statuses[i])) +            goto error; +    } +    json_decref(root); +    return t; + +error: +    timeline_free(t); +    json_decref(root); +    return NULL; +} + +void timeline_free(struct timeline *t) +{ +    if (!t) { +        fprintf(stderr, "timeline_free(): timeline not initialized\n"); +        return; +    } +    for (size_t i = 0; i < t->size; i++) { +        if (t->statuses[i]) +            status_free(t->statuses[i]); +    } +    free(t); +} | 
