Skip to content

Instantly share code, notes, and snippets.

@caiodanielnunessantos
Created December 7, 2020 16:39
Show Gist options
  • Save caiodanielnunessantos/29a51a2732793a484c8557bdebdad215 to your computer and use it in GitHub Desktop.
Save caiodanielnunessantos/29a51a2732793a484c8557bdebdad215 to your computer and use it in GitHub Desktop.
typedef struct {
size_t element_type_size;
size_t size;
size_t capacity;
char* elements;
} _GenericVector;
void* _GenericVectorGetReference(_GenericVector* vector_address, size_t index) {
if (index >= vector_address->size) return (void*)0;
return vector_address->elements + vector_address->elements_type_size * index;
}
void _GenericVectorAssignElement(_GenericVector* vector_address, size_t index, void* element_address) {
memcpy(_GenericVectorGetReference(vector_address, index), element_address, vector_address->elements_type_size);
}
void _GenericVectorCheckOverflow(_GenericVector* vector_address) {
if (vector_address->size == vector_address->capacity) {
vector_address->capacity *= 2;
vector_address->elements = realloc(vector_address->elements,
vector_address->capacity * vector_address->elements_type_size);
}
}
void _GenericVectorCheckUnderflow(_GenericVector* vector_address) {
if (vector_address->size <= vector_address->capacity / 2) {
vector_address->capacity /= 2;
vector_address->elements = realloc(vector_address->elements,
vector_address->capacity * vector_address->elements_type_size);
}
}
void _GenericVectorPushBack(_GenericVector* vector_address, void* element_address) {
_GenericVectorCheckOverflow(vector_address);
vector_address->size++;
_GenericVectorAssignElement(vector_address, vector_address->size, element_address);
}
void _GenericVectorShiftRight(_GenericVector* vector_address, size_t index) {
_GenericVectorCheckOverflow(vector_address);
memmove(_GenericVectorGetReference(vector_address, index), _GenericVectorGetReference(vector_address, index + 1));
vector_address->size++;
}
void _GenericVectorShiftLeft(_GenericVector* vector_address, size_t index) {
memmove(_GenericVectorGetReference(vector_address, index), _GenericVectorGetReference(vector_address, index - 1));
vector_address->size--;
_GenericVectorCheckUnderflow(vector_address);
}
void _GenericVectorInsert(_GenericVector* vector_address, size_t index, void* element_address) {
if (index > vector_address->size) return;
_GenericVectorShiftRight(vector_address, index + 1);
_GenericVectorAssign(vector_address, index, element_address);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment