diff options
author | David Herrmann <dh.herrmann@gmail.com> | 2013-03-05 01:21:29 +0100 |
---|---|---|
committer | David Herrmann <dh.herrmann@gmail.com> | 2013-03-05 01:21:29 +0100 |
commit | b8f58fea9caed09cfbceea713389a93b02d59d42 (patch) | |
tree | 6c848d89b81b54af26f4b44b460c820562690cf4 | |
parent | 350a9ca5a2fa1e826a1b6c830db78033074e2706 (diff) |
shl: array: add shl_array_zresize()
This helper resizes the array to a given length and zeroes out all new
elements.
Signed-off-by: David Herrmann <dh.herrmann@gmail.com>
-rw-r--r-- | src/shl_array.h | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/src/shl_array.h b/src/shl_array.h index e108ca3..9daf409 100644 --- a/src/shl_array.h +++ b/src/shl_array.h @@ -35,6 +35,7 @@ #include <stddef.h> #include <stdint.h> #include <stdlib.h> +#include "shl_misc.h" struct shl_array { size_t element_size; @@ -84,6 +85,32 @@ static inline void shl_array_free(struct shl_array *arr) free(arr); } +/* resize to length=size and zero out new array entries */ +static inline int shl_array_zresize(struct shl_array *arr, size_t size) +{ + void *tmp; + size_t newsize; + + if (!arr) + return -EINVAL; + + if (size > arr->size) { + newsize = shl_next_pow2(size); + tmp = realloc(arr->data, arr->element_size * newsize); + if (!tmp) + return -ENOMEM; + + arr->data = tmp; + arr->size = newsize; + + memset(((uint8_t*)arr->data) + arr->element_size * arr->length, + 0, arr->element_size * (size - arr->length)); + } + + arr->length = size; + return 0; +} + static inline int shl_array_push(struct shl_array *arr, const void *data) { void *tmp; |