/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <caio.h>
#include <caio/types.h>
#include <errno.h>
#include <stdlib.h>

int caio_set_caches(struct caio *const a, const size_t n)
{
    struct caio_cache *c, *prev = NULL;
    size_t i;

    if (!n)
    {
        errno = EINVAL;
        return -1;
    }

    for (i = 0, c = a->caches; i < n; i++)
    {
        if (!c)
        {
            struct caio_cache *const nc = malloc(sizeof *nc);

            if (!nc)
                return -1;

            *nc = (const struct caio_cache){0};

            if (!a->caches)
                a->caches = nc;
            else if (prev)
            {
                prev->next = nc;
                nc->prev = prev;
            }

            prev = nc;
        }
        else
        {
            prev = c;
            c = c->next;
        }
    }

    for (i = 0, c = a->caches; c; i++)
    {
        struct caio_cache *const next = c->next;

        if (i >= n)
        {
            c->prev = c->next;
            c->next = c->prev;
            free(c);
        }

        c = next;
    }

    return 0;
}
