#ifndef LIST_H #define LIST_H #include #include "util.h" /* Use an enumeration instead of a MACRO */ enum { LIST_INIT_AMOUNT = 32 }; /* The elements of the list are all void pointers, so the users of the list should determine the types of the elements manually. */ typedef struct List_s List; /* allocate a new list */ /* upon failure return NULL */ List *new_list(); /* add an element to the end of the list */ /* upon failure return non-zero */ BOOL add_to_list(List *ls, void *element); /* pop an element from the end of the list, and return that element */ /* upon failure return NULL */ void *pop_from_list(List *ls); typedef void (*printer)(void *); typedef printer acter; /* a type that can act on list elements */ typedef void (*doer)(void); void map_list(List *ls, acter f); void map_list_between(List *ls, acter f, doer d); void print_list(List *ls, printer prt); /* COPYER is expected to return NULL when it fails to copy. */ typedef void *(*copyer)(void *); /* upon failure return NULL */ void *copy_num(void *); /* upon failure return 1 */ BOOL copy_list(List *dest, List *source, copyer copyf); void *list_nth(const List * const ls, NUM n); NUM list_length(const List * const restrict ls); /* Make sure the list has at least SIZE slots to use. This should only be used to create fixed capacity arrays, otherwise we risk frequently re-allocating and hence losing performance. */ /* Upon failure return non-zero. */ BOOL list_assure_size(List *ls, NUM size); /* This is mainly used to set the length of a sparse list, since only when dealing with sparse lists do we not need to care about the elements. */ /* Upon failure return non-zero. */ BOOL list_set_length(List *ls, NUM len); /* Convert a list to an array. ELEMENT_BYTES means the size of the type of elements. This is used to calculate the number of elements in the array. The number of elements of the array will be stored in *NUM. */ void *list_to_array(List *ls, NUM element_bytes, NUM *num); /* Return the array of the list. */ void **list_array(List *ls); /* Create a list from an array. The array will be re-used, so it will be destroyed when the list is destroyed. */ List *array_to_list(void ** array, NUM size); /* destroy the list: If ALL_FREE_P is 1, this frees every void pointers contained in the list; if it is 2, this frees the first pointer. In any case, the list is de-allocated. */ void destroy_list(List *ls, BOOL all_free_p); void destroy_list_free_all(void *ls); void destroy_list_free_first(void *ls); void destroy_list_no_free(void *ls); #endif