/*
 * 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 <loop.h>
#include <loop/types.h>
#include <aio.h>
#include <stdlib.h>

int loop_rm_aio(struct aio *const aio)
{
    for (struct aio_poll *p = loop_aio_head; p; p = p->next)
        if (p->aio == aio)
        {
            struct aio_poll *const prev = p->prev, *const next = p->next;

            if (!prev)
            {
                loop_aio_head = next;

                if (next)
                    next->prev = NULL;
                else
                    loop_aio_tail = NULL;
            }
            else if ((prev->next = next))
                next->prev = prev;
            else
                loop_aio_tail = prev;

            free(p);
            return 0;
        }

    return -1;
}
