added append implementation

This commit is contained in:
2026-05-26 13:40:09 -05:00
parent 826de732d4
commit 76247fec68
3 changed files with 38 additions and 3 deletions

View File

@@ -57,8 +57,13 @@ vector_struct
}
vector_struct;
vector_struct* vector_initialize();
vector_struct*
vector_initialize();
void vector_free_members();
void
vector_free_members();
bool
vector_grow(vector_struct* vector);
#endif /* INTERNAL_MARIGOLD_VECTOR_H */

View File

@@ -1,6 +1,7 @@
#include "marigold_vector.h"
#include <stdio.h>
#include <string.h>
vector_struct*
vector_create(size_t item_size,
@@ -85,9 +86,38 @@ vector_get_raw_data_pointer(const vector_struct* vector)
}
bool
vector_append(vector_struct* vector, const void* element)
vector_append(vector_struct* vector,
const void* element)
{
const bool is_thread_safe = vector_is_thread_safe(vector);
if (is_thread_safe)
{ /* if thread safe enabled, locking before vector modification. */
pthread_mutex_lock(vector->mutex_lock);
}
if (vector->current_occupancy == vector->current_capacity)
{
if (!vector_grow(vector))
{ /* failed to grow vector (probably out of memory)*/
if (is_thread_safe)
{ /* unlocking mutex during fail case if it is locked. */
pthread_mutex_unlock(vector->mutex_lock);
}
return false; /* returns false to show append failed. */
}
}
char* data = (char*)vector->data_pointer;
size_t offset = vector->current_occupancy * vector->item_size;
memcpy(data + offset, element, vector->item_size);
vector->current_occupancy++;
if (is_thread_safe)
{ /* unlocking mutex post vector modification if it exists/is locked. */
pthread_mutex_unlock(vector->mutex_lock);
}
return true; /* returns true to show append success. */
}
bool