r3/src/list.c

131 lines
1.9 KiB
C
Raw Normal View History

2014-05-14 23:52:45 -04:00
/*
* list.c
* Copyright (C) 2014 c9s <c9s@c9smba.local>
*
* 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-14 23:52:45 -04:00
list *
list_create()
{
list *l = (list *) zmalloc(sizeof(list));
2014-05-14 23:52:45 -04:00
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
void
list_free(l)
list *l;
{
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;
}
2014-05-14 23:52:45 -04:00
}
pthread_mutex_unlock(&(l->mutex));
pthread_mutex_destroy(&(l->mutex));
zfree(l);
}
2014-05-14 23:52:45 -04:00
}
2014-05-14 23:52:45 -04:00
list_item *
list_add_element(l, ptr)
list *l;
void *ptr;
{
list_item *li;
2014-05-14 23:52:45 -04:00
pthread_mutex_lock(&(l->mutex));
li = (list_item *) zmalloc(sizeof(list_item));
2014-05-14 23:52:45 -04:00
li->value = ptr;
li->next = NULL;
li->prev = l->tail;
2014-05-14 23:52:45 -04:00
if (l->tail == NULL) {
l->head = l->tail = li;
}
else {
l->tail = li;
}
l->count++;
2014-05-14 23:52:45 -04:00
pthread_mutex_unlock(&(l->mutex));
2014-05-14 23:52:45 -04:00
return li;
}
2014-05-14 23:52:45 -04:00
int
list_remove_element(l, ptr)
list *l;
void *ptr;
{
int result = 0;
list_item *li = l->head;
2014-05-14 23:52:45 -04:00
pthread_mutex_lock(&(l->mutex));
2014-05-14 23:52:45 -04:00
while (li != NULL) {
if (li->value == ptr) {
if (li->prev == NULL) {
l->head = li->next;
}
else {
li->prev->next = li->next;
}
2014-05-14 23:52:45 -04:00
if (li->next == NULL) {
l->tail = li->prev;
}
else {
li->next->prev = li->prev;
}
l->count--;
zfree(li);
2014-05-14 23:52:45 -04:00
result = 1;
break;
}
li = li->next;
}
2014-05-14 23:52:45 -04:00
pthread_mutex_unlock(&(l->mutex));
2014-05-14 23:52:45 -04:00
return result;
}
2014-05-14 23:52:45 -04:00
void
list_each_element(l, func)
list *l;
int (*func)(list_item *);
{
list_item *li;
2014-05-14 23:52:45 -04:00
pthread_mutex_lock(&(l->mutex));
2014-05-14 23:52:45 -04:00
li = l->head;
while (li != NULL) {
if (func(li) == 1) {
break;
}
li = li->next;
}
2014-05-14 23:52:45 -04:00
pthread_mutex_unlock(&(l->mutex));
}