/*
 * Copyright (C) 2020 Uniontech Technology Co., Ltd.
 *
 * Author:     xinbo wang <wangxinbo@uniontech.com>
 *
 * Maintainer: xinbo wang <wangxinbo@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#include "dtk_utils.h"

DTK_EXPORT void
dtk_array_init(struct dtk_array *array)
{
    memset(array, 0, sizeof *array);
}

DTK_EXPORT void
dtk_array_release(struct dtk_array *array)
{
    free(array->data);
    array->data = (void *) 4;
}

DTK_EXPORT void *
dtk_array_add(struct dtk_array *array, size_t size)
{
    size_t alloc;
    void *data, *p;

    if (array->alloc > 0)
        alloc = array->alloc;
    else
        alloc = 16;

    while (alloc < array->size + size)
        alloc *= 2;

    if (array->alloc < alloc) {
        if (array->alloc > 0)
            data = realloc(array->data, alloc);
        else
            data = malloc(alloc);

        if (data == NULL)
            return NULL;
        array->data = data;
        array->alloc = alloc;
    }

    p = (char *)array->data + array->size;
    array->size += size;

    return p;
}

DTK_EXPORT int
dtk_array_copy(struct dtk_array *array, struct dtk_array *source)
{
    if (array->size < source->size) {
        if (!dtk_array_add(array, source->size - array->size))
            return -1;
    } else {
        array->size = source->size;
    }

    if (source->size > 0)
        memcpy(array->data, source->data, source->size);

    return 0;
}
