From 42be2e658987225458a98a54d5a9917c8d997457 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Sat, 31 May 2014 12:40:24 -0400 Subject: array: Allow arrays to be allocated from pools. --- libdimension/dimension/array.h | 50 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) (limited to 'libdimension/dimension') diff --git a/libdimension/dimension/array.h b/libdimension/dimension/array.h index 6a8249f..9261a0e 100644 --- a/libdimension/dimension/array.h +++ b/libdimension/dimension/array.h @@ -36,21 +36,32 @@ typedef struct dmnsn_array { } dmnsn_array; /** - * Allocate an array. + * @internal + * Initialize a new array. + * @param[out] array The array to initialize. * @param[in] obj_size The size of the objects to store in the array. - * @return An empty array. */ -DMNSN_INLINE dmnsn_array * -dmnsn_new_array(size_t obj_size) +DMNSN_INLINE void +dmnsn_init_array(dmnsn_array *array, size_t obj_size) { - dmnsn_array *array = (dmnsn_array *)dmnsn_malloc(sizeof(dmnsn_array)); array->obj_size = obj_size; array->length = 0; array->capacity = 2; /* Start with capacity of 2 */ /* Allocate the memory */ array->ptr = dmnsn_malloc(array->capacity*array->obj_size); +} +/** + * Allocate an array. + * @param[in] obj_size The size of the objects to store in the array. + * @return An empty array. + */ +DMNSN_INLINE dmnsn_array * +dmnsn_new_array(size_t obj_size) +{ + dmnsn_array *array = DMNSN_MALLOC(dmnsn_array); + dmnsn_init_array(array, obj_size); return array; } @@ -74,6 +85,35 @@ dmnsn_delete_array(dmnsn_array *array) } } +/** + * @internal + * Free a pool-allocated array. + * @param[in,out] ptr The array to clean up. + */ +void dmnsn_array_cleanup(void *ptr); + +/** + * Allocate an array from a pool. + * @param[in] pool The memory pool to allocate from. + * @param[in] obj_size The size of the objects to store in the array. + * @return An empty array. + */ +DMNSN_INLINE dmnsn_array * +dmnsn_palloc_array(dmnsn_pool *pool, size_t obj_size) +{ + dmnsn_array *array = DMNSN_PALLOC_TIDY(pool, dmnsn_array, dmnsn_array_cleanup); + dmnsn_init_array(array, obj_size); + return array; +} + +/** + * Allocate an array from a pool. + * @param[in] pool The memory pool to allocate from. + * @param[in] type Type type of element to store in the array. + * @return An empty array. + */ +#define DMNSN_PALLOC_ARRAY(pool, type) (dmnsn_palloc_array(pool, sizeof(type))) + /** * Get the size of the array. * @param[in] array The array in question. -- cgit v1.2.3