r3/src/list.c

123 lines
2.3 KiB
C
Raw Normal View History

2014-05-14 23:52:45 -04:00
/*
2014-05-26 13:07:33 -04:00
* list.c Copyright (C) 2014 c9s <c9s@c9smba.local>
*
2014-05-14 23:52:45 -04:00
* Distributed under terms of the MIT license.
*/
#include <stdlib.h>
2014-05-16 08:22:25 -04:00
#include "r3_list.h"
#include "zmalloc.h"
2014-05-14 23:52:45 -04:00
/* Naive linked list implementation */
2014-05-26 13:07:33 -04:00
list *
2014-05-14 23:52:45 -04:00
list_create()
{
2014-05-26 13:07:33 -04:00
list *l = (list *) zmalloc(sizeof(list));
l->count = 0;
l->head = NULL;
l->tail = NULL;
pthread_mutex_init(&(l->mutex), NULL);
return l;
2014-05-14 23:52:45 -04:00
}
2014-05-14 23:52:45 -04:00
void
list_free(l)
2014-05-26 13:07:33 -04:00
list *l;
2014-05-14 23:52:45 -04:00
{
2014-05-26 13:07:33 -04:00
if (l) {
list_item *li, *tmp;
pthread_mutex_lock(&(l->mutex));
if (l != NULL) {
li = l->head;
while (li != NULL) {
tmp = li->next;
li = tmp;
}
}
pthread_mutex_unlock(&(l->mutex));
pthread_mutex_destroy(&(l->mutex));
zfree(l);
2014-05-14 23:52:45 -04:00
}
}
2014-05-26 13:07:33 -04:00
list_item * list_add_element(list * l, void * ptr)
2014-05-14 23:52:45 -04:00
{
2014-05-26 13:07:33 -04:00
list_item *li;
2014-05-26 13:07:33 -04:00
pthread_mutex_lock(&(l->mutex));
2014-05-26 13:07:33 -04:00
li = (list_item *) zmalloc(sizeof(list_item));
li->value = ptr;
li->next = NULL;
li->prev = l->tail;
2014-05-26 13:07:33 -04:00
if (l->tail == NULL) {
l->head = l->tail = li;
} else {
l->tail = li;
}
l->count++;
2014-05-26 13:07:33 -04:00
pthread_mutex_unlock(&(l->mutex));
2014-05-26 13:07:33 -04:00
return li;
2014-05-14 23:52:45 -04:00
}
2014-05-14 23:52:45 -04:00
int
list_remove_element(l, ptr)
2014-05-26 13:07:33 -04:00
list *l;
void *ptr;
2014-05-14 23:52:45 -04:00
{
2014-05-26 13:07:33 -04:00
int result = 0;
list_item *li = l->head;
pthread_mutex_lock(&(l->mutex));
while (li != NULL) {
if (li->value == ptr) {
if (li->prev == NULL) {
l->head = li->next;
} else {
li->prev->next = li->next;
}
if (li->next == NULL) {
l->tail = li->prev;
} else {
li->next->prev = li->prev;
}
l->count--;
zfree(li);
result = 1;
break;
}
li = li->next;
2014-05-14 23:52:45 -04:00
}
2014-05-26 13:07:33 -04:00
pthread_mutex_unlock(&(l->mutex));
2014-05-26 13:07:33 -04:00
return result;
2014-05-14 23:52:45 -04:00
}
2014-05-14 23:52:45 -04:00
void
list_each_element(l, func)
2014-05-26 13:07:33 -04:00
list *l;
int (*func) (list_item *);
2014-05-14 23:52:45 -04:00
{
2014-05-26 13:07:33 -04:00
list_item *li;
2014-05-26 13:07:33 -04:00
pthread_mutex_lock(&(l->mutex));
2014-05-26 13:07:33 -04:00
li = l->head;
while (li != NULL) {
if (func(li) == 1) {
break;
}
li = li->next;
2014-05-14 23:52:45 -04:00
}
2014-05-26 13:07:33 -04:00
pthread_mutex_unlock(&(l->mutex));
2014-05-14 23:52:45 -04:00
}