static void *tree_create_data(int type, const char *data, uint32_t length)
{
    json_val_t *v;

    v = (json_val_t *)malloc(sizeof(json_val_t));
    if (v) {
        v->type = type;
        v->length = length;
        switch (type) {
        case JSON_STRING:
            v->u.str_val = memalloc_copy_length(data, length);
            if (!v->u.str_val) {
                free(v);
                return NULL;
            }
            break;

        case JSON_INT:
            v->u.int_val = strtoll(data, NULL, 10);
            break;

        case JSON_FLOAT:
            v->u.float_val = atof(data);
            break;
        }
    }
    return v;
}
static int tree_append(void *structure, char *key, uint32_t key_length, void *obj)
{
    json_val_t *parent = (json_val_t *)structure;
    if (key) {
        struct json_val_elem *objelem;

        if (parent->length == 0) {
            parent->u.object = (json_val_elem **)calloc(1 + 1, sizeof(json_val_t *)); /* +1 for null */
            if (!parent->u.object)
                return 1;
        }
        else {
            uint32_t newsize = parent->length + 1 + 1; /* +1 for null */
            void *newptr;

            newptr = realloc(parent->u.object, newsize * sizeof(json_val_t *));
            if (!newptr)
                return -1;
            parent->u.object = (json_val_elem **)newptr;
        }

        objelem = (json_val_elem *)malloc(sizeof(struct json_val_elem));
        if (!objelem)
            return -1;

        objelem->key = memalloc_copy_length(key, key_length);
        objelem->key_length = key_length;
        objelem->val = (json_val_t *)obj;
        parent->u.object[parent->length++] = objelem;
        parent->u.object[parent->length] = NULL;
    }
    else {
        if (parent->length == 0) {
            parent->u.array = (json_val_t **)calloc(1 + 1, sizeof(json_val_t *)); /* +1 for null */
            if (!parent->u.array)
                return 1;
        }
        else {
            uint32_t newsize = parent->length + 1 + 1; /* +1 for null */
            void *newptr;

            newptr = realloc(parent->u.object, newsize * sizeof(json_val_t *));
            if (!newptr)
                return -1;
            parent->u.array = (json_val_t **)newptr;
        }
        parent->u.array[parent->length++] = (json_val_t *)obj;
        parent->u.array[parent->length] = NULL;
    }
    return 0;
}
Ejemplo n.º 3
0
static void *tree_create_data(int type, const char *data, uint32_t length)
{
    json_val_t *v;

    v = malloc(sizeof(json_val_t));
    if (v) {
        v->type = type;
        v->length = length;
        v->u.data = memalloc_copy_length(data, length);
        if (!v->u.data) {
            free(v);
            return NULL;
        }
    }
    return v;
}