mirror of
https://github.com/gnif/LookingGlass.git
synced 2024-11-25 23:07:18 +00:00
[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.
This commit is contained in:
parent
07d3d6cbe7
commit
53b4b4818b
@ -34,7 +34,7 @@ Vector;
|
|||||||
Vector * vector_create(size_t itemSize, size_t capacity);
|
Vector * vector_create(size_t itemSize, size_t capacity);
|
||||||
void vector_free(Vector * vector);
|
void vector_free(Vector * vector);
|
||||||
|
|
||||||
bool vector_push(Vector * vector, void * item);
|
void * vector_push(Vector * vector, void * item);
|
||||||
void vector_pop(Vector * vector);
|
void vector_pop(Vector * vector);
|
||||||
size_t vector_size(Vector * vector);
|
size_t vector_size(Vector * vector);
|
||||||
void * vector_data(Vector * vector);
|
void * vector_data(Vector * vector);
|
||||||
|
@ -53,7 +53,7 @@ void vector_free(Vector * vector)
|
|||||||
free(vector);
|
free(vector);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool vector_push(Vector * vector, void * item)
|
void * vector_push(Vector * vector, void * item)
|
||||||
{
|
{
|
||||||
if (vector->size >= vector->capacity)
|
if (vector->size >= vector->capacity)
|
||||||
{
|
{
|
||||||
@ -62,16 +62,18 @@ bool vector_push(Vector * vector, void * item)
|
|||||||
if (!new)
|
if (!new)
|
||||||
{
|
{
|
||||||
DEBUG_ERROR("Failed to allocate memory in vector: %" PRIuPTR " bytes", newCapacity * vector->itemSize);
|
DEBUG_ERROR("Failed to allocate memory in vector: %" PRIuPTR " bytes", newCapacity * vector->itemSize);
|
||||||
return false;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
vector->capacity = newCapacity;
|
vector->capacity = newCapacity;
|
||||||
vector->data = new;
|
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;
|
++vector->size;
|
||||||
return true;
|
return ptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
void vector_pop(Vector * vector)
|
void vector_pop(Vector * vector)
|
||||||
|
Loading…
Reference in New Issue
Block a user