From 53b4b4818b20fe531bed0913cd3b66f0bf27de40 Mon Sep 17 00:00:00 2001 From: Quantum Date: Sun, 22 Aug 2021 08:09:29 -0400 Subject: [PATCH] [common] vector: allow inplace construction with vector_push This makes vector_push return a pointer to the pushed element. It also allows the user to push a NULL pointer, which means allocating the memory for the element but do not copy anything into it. --- common/include/common/vector.h | 2 +- common/src/vector.c | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/common/include/common/vector.h b/common/include/common/vector.h index 9d08ddf1..e015d423 100644 --- a/common/include/common/vector.h +++ b/common/include/common/vector.h @@ -34,7 +34,7 @@ Vector; Vector * vector_create(size_t itemSize, size_t capacity); void vector_free(Vector * vector); -bool vector_push(Vector * vector, void * item); +void * vector_push(Vector * vector, void * item); void vector_pop(Vector * vector); size_t vector_size(Vector * vector); void * vector_data(Vector * vector); diff --git a/common/src/vector.c b/common/src/vector.c index 66ccd321..1288cf16 100644 --- a/common/src/vector.c +++ b/common/src/vector.c @@ -53,7 +53,7 @@ void vector_free(Vector * vector) free(vector); } -bool vector_push(Vector * vector, void * item) +void * vector_push(Vector * vector, void * item) { if (vector->size >= vector->capacity) { @@ -62,16 +62,18 @@ bool vector_push(Vector * vector, void * item) if (!new) { DEBUG_ERROR("Failed to allocate memory in vector: %" PRIuPTR " bytes", newCapacity * vector->itemSize); - return false; + return NULL; } vector->capacity = newCapacity; vector->data = new; } - memcpy((char *)vector->data + vector->size * vector->itemSize, item, vector->itemSize); + void * ptr = (char *)vector->data + vector->size * vector->itemSize; + if (item) + memcpy(ptr, item, vector->itemSize); ++vector->size; - return true; + return ptr; } void vector_pop(Vector * vector)