#include <u.h>
#include <libc.h>
#include "list.h"

static void
printallocs(void)
{
	print("listallocs=%d\n", listallocs);
}

static void
add(List **lp, void *val, int ret)
{
	int r;

	print("add \"%S\"\n", val);
	r = listadd(lp, val);
	assert(r == ret);
}

static void
del(List **lp, void *val, int ret)
{
	int r;

	print("del \"%S\"\n", val);
	r = listdel(lp, val);
	assert(r == ret);
}

static void
walk(List *l)
{
	print("walk:\n");

	while(l != nil){
		print("val=\"%S\"\n", l->val);
		l = l->next;
	}
}

void
main(void)
{
	Rune *words[] = { L"one", L"two", L"three", L"four", L"five",
	                  L"six", L"seven", L"eight", L"nine", L"" };
	List *l;
	int i, n, free;

	l = nil;
	n = nelem(words);
	free = 1;
	assert(listallocs == 0);
	printallocs();
start:
	for(i = 0; i < n; i++)
		add(&l, words[i], 1);

	assert(listallocs == n);
	printallocs();

	if(free--){
		print("free list\n");
		listfree(&l);
		assert(l == nil);
		assert(listallocs == 0);
		printallocs();
		goto start;
	}
	for(i = 0; i < n; i++)
		add(&l, words[i], 0);

	walk(l);

	for(i = 0; i < n; i += 2)
		del(&l, words[i], 1);

	printallocs();

	for(i = 0; i < n; i += 2)
		del(&l, words[i], 0);

	walk(l);

	for(i = 1; i < n; i += 2)
		del(&l, words[i], 1);

	walk(l);

	assert(l == nil);
	assert(listallocs == 0);
	print("free list\n");
	listfree(&l);
	assert(l == nil);
	assert(listallocs == 0);
	printallocs();
	exits(0);
}
