From fe310f8b7a54f31b7270107b57b5ffcc00966f45 Mon Sep 17 00:00:00 2001 From: Jordan Augé Date: Wed, 2 Sep 2020 08:43:12 +0200 Subject: [HICN-555] Base data structures: vector, bitmap, pool (code + doc) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I30b559974d4bdf57eb458f1c43a71f47598c2e70 Signed-off-by: Jordan Augé --- hicn-light/src/hicn/base/vector.c | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) (limited to 'hicn-light/src/hicn/base/vector.c') diff --git a/hicn-light/src/hicn/base/vector.c b/hicn-light/src/hicn/base/vector.c index d090588b4..b994a4465 100644 --- a/hicn-light/src/hicn/base/vector.c +++ b/hicn-light/src/hicn/base/vector.c @@ -18,19 +18,28 @@ * \brief Implementation of resizeable static array */ +#include #include // size_t #include // calloc #include #include "vector.h" +#define DEFAULT_VECTOR_SIZE 64 + void -_vector_init(void ** vector_ptr, size_t elt_size, size_t max_elts) +_vector_init(void ** vector_ptr, size_t elt_size, size_t init_size) { - vector_hdr_t * vh = calloc(VECTOR_HDRLEN + elt_size * max_elts, 1); - *vector_ptr = (uint8_t*)vh + VECTOR_HDRLEN; - vh->max_elts = max_elts; - vh->num_elts = 0; + assert(vector_ptr); + + if (init_size == 0) + init_size = DEFAULT_VECTOR_SIZE; + + *vector_ptr = NULL; + _vector_resize(vector_ptr, elt_size, init_size); + + vector_hdr_t * vh = vector_hdr(*vector_ptr); + vh->cur_size = 0; } void @@ -40,18 +49,23 @@ _vector_free(void ** vector_ptr) *vector_ptr = NULL; } -void +bool _vector_resize(void ** vector_ptr, size_t elt_size, off_t pos) { - vector_hdr_t * vh = vector_hdr(*vector_ptr); - size_t new_elts = (pos > 0) ? next_pow2(pos) : vh->max_elts * 2; + vector_hdr_t * vh = *vector_ptr ? vector_hdr(*vector_ptr) : NULL; + + /* + * Round the allocated size to the next power of 2 of the requested position + */ + size_t new_elts = (pos > 0) ? next_pow2(pos) : vh->max_size * 2; - /* Double the allocated vector size */ vh = realloc(vh, VECTOR_HDRLEN + new_elts * elt_size); if (!vh) - abort(); - vh->max_elts = new_elts; + return false; + vh->max_size = new_elts; /* Reassign vector pointer */ *vector_ptr = (uint8_t*)vh + VECTOR_HDRLEN; + + return true; } -- cgit 1.2.3-korg