diff --git a/server/include/list.h b/server/include/list.h new file mode 100644 index 000000000..1defacaf4 --- /dev/null +++ b/server/include/list.h @@ -0,0 +1,51 @@ +/** A generic linked list + * + * Linked lists a used for several data structures in the code. + * + * @author Steffen Vogel + * @copyright 2015, Institute for Automation of Complex Power Systems, EONERC + * @file + */ + +#ifndef _LIST_H_ +#define _LIST_H_ + +#include + +/* Forward declarations */ +struct list_elm; + +/** Static list initialization */ +#define LIST_INIT { \ + .head = NULL, \ + .tail = NULL, \ + .count = 0, \ + .lock = PTHREAD_MUTEX_INITIALIZER \ +} + +#define FOREACH(list, elm) \ + for ( struct list_elm *elm = (list)->head, ; \ + elm != (list)->tail; elm = elm->next ) + +struct list { + struct list_elm *head, tail; + int count; + + pthread_mutex_lock_t lock; +}; + +struct list_elm { + void *data; + + struct list_elm *prev, next; +}; + +void list_init(struct list *l); + +void list_destroy(struct list *l); + +void list_push(struct list *l, void *d); + +struct list_elm * list_search(struct list *l, int (*cmp)(void *)); + +#endif /* _LIST_H_ */ \ No newline at end of file diff --git a/server/src/list.c b/server/src/list.c new file mode 100644 index 000000000..247d8af61 --- /dev/null +++ b/server/src/list.c @@ -0,0 +1,60 @@ +/** A generic linked list + * + * Linked lists a used for several data structures in the code. + * + * @author Steffen Vogel + * @copyright 2015, Institute for Automation of Complex Power Systems, EONERC + * @file + */ + +#include "list.h" + +void list_init(struct list *l) +{ + pthread_mutex_init(&l->lock, NULL); + + l->count = 0; + l->head = NULL; + l->tail = NULL; +} + +void list_destroy(struct list *l) +{ + pthread_mutex_lock(&l->lock); + + struct list_elm *elm = l->head; + while (elm) { + struct list_elm *tmp = elm; + free(tmp); + + elm = elm->next; + } + + pthread_mutex_destroy(&l->lock); +} + +void list_push(struct list *l, void *d) +{ + struct list_elm *e = alloc(sizeof(struct list_elm)); + + pthread_mutex_lock(&l->lock); + + e->data = d; + e->prev = l->tail; + e->next = NULL; + + l->tail->next = e; + l->tail = e; + + pthread_mutex_unlock(&l->lock); +} + +struct list_elm * list_search(struct list *l, int (*cmp)(void *)) +{ + foreach(l, it) { + if (!cmp(it->data)) + return it; + } + + return NULL; +}