list.h 2.12 KB
#ifndef __LIST_H__
#define __LIST_H__

#include <stddef.h>

/**
 * A growable array of general data type objects, stored as pointers to
 * malloc()ed objects. A list owns all the elements in it, so it is responsible
 * for free()ing them. This line does two things:
 * - Declares a "struct list" type
 * - Makes "list_t" an alias for "struct list"
 */
typedef struct list list_t;

/**
 * Allocates memory for a new list with space for the given number of elements.
 * The list is initially empty.
 * Asserts that the required memory was allocated.
 *
 * @param initial_size the number of list elements to allocate space for
 * @return a pointer to the newly allocated list
 */
list_t *list_init(size_t initial_size);

/**
 * Releases the memory allocated for a list.
 * Also frees all elements of the list.
 *
 * @param list a pointer to a list returned from list_init()
 */
void list_free(list_t *list);

/**
 * Gets the size of a list (the number of occupied elements).
 * Note that this is NOT the list's capacity.
 *
 * @param list a pointer to a list returned from list_init()
 * @return the number of elements in the list
 */
size_t list_size(list_t *list);

/**
 * Gets the element at a given index in a list.
 * Asserts that the index is valid, given the list's current size.
 *
 * @param list a pointer to a list returned from list_init()
 * @param index an index in the list (the first element is at 0)
 * @return the element at the given index
 */
void *list_get(list_t *list, size_t index);

/**
 * Appends an element to the end of a list.
 * Asserts that the value being added is not NULL.
 *
 * @param list a pointer to a list returned from list_init()
 * @param value the value to add to the end of the list
 */
void list_add(list_t *list, void *value);

/**
 * Removes the element at a given index in a list and returns it,
 * moving all subsequent elements towards the start of the list.
 * Asserts that the index is valid, given the list's current size.
 *
 * @param list a pointer to a list returned from list_init()
 * @return the element at the given index in the list
 */
void *list_remove(list_t *list, size_t index);

#endif // #ifndef __LIST_H__