/* Terminality - a portable terminal handling library * Copyright (C) 1998-2002, Emil Mikulic. * This is LGPL - look at COPYING.LIB */ /* Linked list code * Written by Emil Mikulic, 1999. * Overhauled by Michal Safranek, 2001. */ #include "list.h" #include #include const char list_rcsid[] = "$Id: list.c,v 1.11 2002/07/26 01:39:40 darkmoon Exp $"; /* create new list element */ tn_list *tn_list_new(void *x) { tn_list *tmp = NULL; tmp = (tn_list *)xmalloc(sizeof(tn_list)); tmp->alloc_by = STARTING_POOL; tmp->elements = (void *) xmalloc(sizeof(void *) * tmp->alloc_by); memset(tmp->elements, 0, sizeof(void *) * tmp->alloc_by); tmp->allocated = tmp->alloc_by; tmp->elements[0] = x; tmp->count = 1; return tmp; } /* add an element on to a list */ int tn_list_add(tn_list *dest, void *elem) { void *tmp = NULL; assert(dest != NULL); if(dest->count == dest->allocated) { tmp = (void *) xrealloc(dest->elements, sizeof(void *) * (dest->allocated + dest->alloc_by)); dest->elements = tmp; dest->allocated += dest->alloc_by; } dest->elements[dest->count] = elem; dest->count++; return 1; } /* get the number of items in the list */ int tn_list_size(tn_list *x) { if (x == NULL) return 0; return x->count; } /* free the whole list */ void tn_list_free(tn_list *x) { if (x == NULL) return; if(x->elements != 0) { x->allocated = 0; xfree(x->elements); x->elements = NULL; x->count = 0; } } /* free space used by list */ void tn_list_kill(tn_list *x) { if (x == NULL) return; if(tn_list_size(x)){ tn_list_free(x); } xfree(x); } /* get the nth item (data) in a list */ void *tn_list_getdata(tn_list *x, int n) { assert(x != NULL); assert(n < tn_list_size(x)); assert(n > -1); return x->elements[n]; } /* delete the nth element of list */ int tn_list_delete(tn_list *x, int n) { assert(x != NULL); assert(n < tn_list_size(x)); assert(n > -1); if(x->count > 1) { memmove(&(x->elements[n]), &(x->elements[n+1]), (x->count - n - 1) * sizeof(void *)); } x->count--; return 1; } /* replace nth element in a list */ void tn_list_replace(tn_list *dest, int n, void *elem){ assert(dest != NULL); assert(n < tn_list_size(dest)); assert(n > -1); dest->elements[n] = elem; }