varray.h (2032B)
1 #ifndef VARRAY_H 2 #define VARRAY_H 3 4 typedef struct { 5 void *data; 6 7 int count; 8 int allocation; /* We actually allocate one more element than this for temp storage. */ 9 10 int element_size; 11 12 /* Will be called when an empty element is created; returning NULL will fail the insert */ 13 void *(*init_func)(void *element); 14 /* Will be called for each element on _destroy */ 15 void (*destroy_func)(void *element); 16 17 /* Compare two array items, is passed to qsort */ 18 int (*sort_compar)(const void *el1, const void *el2); 19 /* Compare a key and an array item, for search; sort_compar will be used if NULL */ 20 int (*search_compar)(const void *key, const void *element); 21 } varray; 22 23 varray *varray_new(int element_size, int initial_allocation); /* Allocate and initialize new varray */ 24 varray *varray_init(varray *va, int element_size, int initial_allocation); /* Initialize new varray only */ 25 void varray_destroy(varray *va); /* Deinitialize varray contents */ 26 void varray_free(varray *va); /* Deinitialize and free memory */ 27 28 void *varray_extract_array(varray *va); /* Compact array storage and return; va becomes uninitialized */ 29 30 int varray_get_index(varray *va, void *element_ptr); 31 32 /* if element is NULL in either function, the new element will be initialized to zero. */ 33 void *varray_push(varray *va, void *element); 34 void *varray_insert(varray *va, void *element, int index); 35 36 /* _pop and _remove will return a value that is only valid until the next array insert. */ 37 void *varray_pop(varray *va); 38 void *varray_remove(varray *va, int index); 39 40 void varray_sort(varray *va); 41 void *varray_sorted_search(const varray *va, const void *key); 42 void *varray_sorted_insert(varray *va, void *element); 43 void *varray_sorted_insert_ex(varray *va, void *element, int allow_dup); 44 /* found_existing, if not NULL, will be set to 1 if an existing element was found, otherwise 0 */ 45 void *varray_sorted_search_or_insert(varray *va, const void *key, int *found_existing); 46 47 #define VARRAY_ELEMENT(va, index) ((va)->data + ((index) * (va)->element_size)) 48 49 #endif