#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
#include "genlist.h"
struct genlist *
genlist_init (void)
{
struct genlist *new = calloc(sizeof(struct genlist), 1);
TAILQ_INIT(new);
return new;
}
struct genlist_entry *
genlist_insert (struct genlist *head, void *data)
{
struct genlist_entry *entry = calloc(sizeof(struct genlist_entry), 1);
entry->data = data;
TAILQ_INSERT_HEAD(head, entry, chain);
return entry;
}
struct genlist_entry *
genlist_append (struct genlist *head, void *data)
{
struct genlist_entry *entry = calloc(sizeof(struct genlist_entry), 1);
entry->data = data;
TAILQ_INSERT_TAIL(head, entry, chain);
return entry;
}
void *
genlist_foreach (struct genlist *head, genlist_func_t func, void *arg)
{
struct genlist_entry *p;
void *ret = NULL;
TAILQ_FOREACH(p, head, chain) {
ret = (*func)(p->data, arg);
if (ret)
break;
}
return ret;
}
void *
genlist_next (struct genlist *head, struct genlist_entry **buf)
{
struct genlist_entry *p;
if (head)
p = TAILQ_FIRST(head);
else
p = (buf && *buf) ? TAILQ_NEXT(*buf, chain) : NULL;
if (buf)
*buf = p;
return (p ? p->data : NULL);
}
void
genlist_free (struct genlist *head, genlist_freedata_t func)
{
struct genlist_entry *p;
while ((p = TAILQ_LAST(head, genlist)) != NULL) {
TAILQ_REMOVE(head, p, chain);
if (func)
func(p->data);
free(p);
}
free(head);
}
#if 0
struct conf {
struct genlist *l1, *l2;
};
void *
print_entry(void *entry, void *arg)
{
if (!entry)
return NULL;
printf("%s\n", (char *)entry);
return NULL;
}
void
dump_list(struct genlist *head)
{
genlist_foreach(head, print_entry, NULL);
}
void
free_data(void *data)
{
printf ("removing %s\n", (char *)data);
}
int main()
{
struct conf *cf;
char *cp;
struct genlist_entry *gpb;
cf = calloc(sizeof(struct conf), 1);
cf->l1 = genlist_init();
cf->l2 = genlist_init();
genlist_insert(cf->l1, "Ahoj");
genlist_insert(cf->l1, "Cau");
genlist_insert(cf->l1, "Nazdar");
genlist_insert(cf->l1, "Te buch");
genlist_append(cf->l2, "Curak");
genlist_append(cf->l2, "Kozy");
genlist_append(cf->l2, "Pica");
genlist_append(cf->l2, "Prdel");
printf("List 2\n");
dump_list(cf->l2);
printf("\nList 1\n");
dump_list(cf->l1);
printf("\nList 2 - using genlist_next()\n");
for (cp = genlist_next (cf->l2, &gpb); cp; cp = genlist_next (0, &gpb))
printf("%s\n", cp);
printf("\nFreeing List 1\n");
genlist_free (cf->l1, free_data);
cf->l1 = 0;
return 0;
}
#endif