added support for NULL insert on vectors

master
Dvir Volk 8 years ago
parent 23896a8a10
commit c3d0c99023

@ -1,13 +1,12 @@
#include "vector.h" #include "vector.h"
#include <stdio.h> #include <stdio.h>
int __vector_PushPtr(Vector *v, void *elem) { inline int __vector_PushPtr(Vector *v, void *elem) {
if (v->top == v->cap - 1) { if (v->top == v->cap) {
Vector_Resize(v, v->cap ? v->cap * 2 : 1); Vector_Resize(v, v->cap ? v->cap * 2 : 1);
} }
__vector_PutPtr(v, v->top, elem); __vector_PutPtr(v, v->top++, elem);
v->top++;
return v->top; return v->top;
} }
@ -33,13 +32,17 @@ inline int Vector_Pop(Vector *v, void *ptr) {
return 0; return 0;
} }
int __vector_PutPtr(Vector *v, size_t pos, void *elem) { inline int __vector_PutPtr(Vector *v, size_t pos, void *elem) {
// resize if pos is out of bounds // resize if pos is out of bounds
if (pos >= v->cap) { if (pos >= v->cap) {
Vector_Resize(v, pos + 1); Vector_Resize(v, pos + 1);
} }
memcpy(v->data + pos * v->elemSize, elem, v->elemSize); if (elem) {
memcpy(v->data + pos * v->elemSize, elem, v->elemSize);
} else {
memset(v->data + pos * v->elemSize, 0, v->elemSize);
}
// move the end offset to pos if we grew // move the end offset to pos if we grew
if (pos > v->top) { if (pos > v->top) {
v->top = pos; v->top = pos;

@ -47,11 +47,11 @@ int Vector_Pop(Vector *v, void *ptr);
* Put an element at pos. * Put an element at pos.
* Note: If pos is outside the vector capacity, we resize it accordingly * Note: If pos is outside the vector capacity, we resize it accordingly
*/ */
#define Vector_Put(v, pos, elem) __vector_PutPtr(v, pos, &(typeof(elem)){elem}) #define Vector_Put(v, pos, elem) __vector_PutPtr(v, pos, elem ? &(typeof(elem)){elem} : NULL)
/* Push an element at the end of v, resizing it if needed. This macro wraps /* Push an element at the end of v, resizing it if needed. This macro wraps
* __vector_PushPtr */ * __vector_PushPtr */
#define Vector_Push(v, elem) __vector_PushPtr(v, &(typeof(elem)){elem}) #define Vector_Push(v, elem) __vector_PushPtr(v, elem ? &(typeof(elem)){elem} : NULL)
int __vector_PushPtr(Vector *v, void *elem); int __vector_PushPtr(Vector *v, void *elem);

Loading…
Cancel
Save