diff --git a/rmutil/vector.c b/rmutil/vector.c index 3902405..f255844 100644 --- a/rmutil/vector.c +++ b/rmutil/vector.c @@ -14,35 +14,39 @@ int __vector_PushPtr(Vector *v, void *elem) { int Vector_Get(Vector *v, int pos, void *ptr) { + // return 0 if pos is out of bounds if (pos >= v->top) { return 0; } + memcpy(ptr, v->data + (pos * v->elemSize), v->elemSize); return 1; } int __vector_PutPtr(Vector *v, int pos, void *elem) { - if (pos > v->cap) { + // resize if pos is out of bounds + if (pos >= v->cap) { Vector_Resize(v, pos+1); } memcpy(v->data + pos*v->elemSize, elem, v->elemSize); + // move the end offset to pos if we grew if (pos > v->top) { v->top = pos; } - - //printf("v: %s",v->data); return 1; } int Vector_Resize(Vector *v, int newcap) { + int oldcap = v->cap; v->cap = newcap; v->data = realloc(v->data, v->cap*v->elemSize); int offset = v->top*v->elemSize; + // put all zeros at the newly realloc'd part of the vector memset(v->data + offset, 0, v->cap*v->elemSize - offset); return v->cap; } diff --git a/rmutil/vector.h b/rmutil/vector.h index d88dac7..5682d75 100644 --- a/rmutil/vector.h +++ b/rmutil/vector.h @@ -13,7 +13,7 @@ typedef struct { int elemSize; int cap; int top; - int isPtr; + } Vector; // Create a new vector with element size. This should generally be used internall by the NewVector macro