/*
 * list.h
 *
 * Copyright (C) 2015 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

#ifndef __MONOLITHIUM_LIST_H__
#define __MONOLITHIUM_LIST_H__

#include "defs.h"

#define LIST_INITIALIZER(name) { &name, &name }
#define DECLARE_LIST(name) list_entry_t name = LIST_INITIALIZER(name)

#define list_put_after  list_prepend
#define list_put_before list_append

typedef struct _list_entry_t
{
    struct _list_entry_t *next, *prev;
} list_entry_t;

static inline void list_prepend(list_entry_t *list, list_entry_t *entry)
{
    entry->next = list->next;
    entry->prev = list;
    entry->next->prev = entry;
    entry->prev->next = entry;
}

static inline void list_append(list_entry_t *list, list_entry_t *entry)
{
    entry->next = list;
    entry->prev = list->prev;
    entry->next->prev = entry;
    entry->prev->next = entry;
}

static inline void list_remove(list_entry_t *entry)
{
    entry->next->prev = entry->prev;
    entry->prev->next = entry->next;
}

static inline void list_init(list_entry_t *list)
{
    list->next = list->prev = list;
}

static inline void list_init_array(list_entry_t *list_array, size_t size)
{
    size_t i;
    for (i = 0; i < size; i++) list_init(&list_array[i]);
}

#endif
