/* * CS5600 University of Utah * Charles McGarvey * mcgarvey@eng.utah.edu */ #ifndef _LIST_H_ #define _LIST_H_ #include "common.h" /* * A linked-list with a stack-like interface. * The value of each node can be any pointer. */ struct list { void* val; struct list* link; void (*dtor)(void*); }; typedef struct list list_t; /* * Add a value to the list. It will become the first item. * This is a O(1) operation. */ INLINE_MAYBE void list_push2(list_t** l, void* value, void (*destructor)(void*)) { list_t* n = (list_t*)mem_alloc(sizeof(list_t)); n->val = value; n->link = *l; n->dtor = destructor; *l = n; } /* * Add a value to the list with no destructor set. */ INLINE_MAYBE void list_push(list_t** l, void* value) { list_push2(l, value, NULL); } /* * Create a new list with a single value. */ INLINE_MAYBE list_t* list_new2(void* value, void (*destructor)(void*)) { list_t* l = NULL; list_push2(&l, value, destructor); return l; } /* * Create a new list with a single value without a destructor set. */ INLINE_MAYBE list_t* list_new(void* value) { list_t* l = NULL; list_push2(&l, value, 0); return l; } /* * Remove a value from the front of the list. If the node has dtor set, it * will be used to destroy the value. * This is a O(1) operation. */ INLINE_MAYBE void list_pop(list_t** l) { list_t* n = (*l)->link; if ((*l)->dtor) { (*l)->dtor((*l)->val); } mem_free(*l); *l = n; } /* * Destroy the list, freeing up all of its memory. * This is a O(n) operation. */ INLINE_MAYBE void list_destroy(list_t** l) { while (*l) { list_pop(l); } } /* * Reverse the order of the items in the list. * This is a O(n) operation. */ void list_reverse(list_t** l); #endif // _LIST_H_