2023-08-23 21:14:12 -04:00
|
|
|
#ifndef VECTOR_H
|
|
|
|
#define VECTOR_H
|
|
|
|
|
2023-08-23 19:29:23 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
// TODO: Handle error warnings?
|
|
|
|
// TODO: Implement more useful functions?
|
|
|
|
|
|
|
|
typedef struct {
|
|
|
|
char * data;
|
|
|
|
size_t element_size;
|
|
|
|
size_t element_count;
|
|
|
|
} vector_t;
|
|
|
|
|
|
|
|
extern void vector_init(vector_t * vector,
|
|
|
|
size_t element_size,
|
|
|
|
size_t element_count);
|
|
|
|
|
|
|
|
extern void vector_push(vector_t * vector,
|
|
|
|
void * data);
|
|
|
|
|
|
|
|
extern void vector_pop(vector_t * vector);
|
|
|
|
|
2023-08-23 21:14:12 -04:00
|
|
|
extern void * vector_get(const vector_t * const vector,
|
|
|
|
const size_t element);
|
2023-08-23 19:29:23 -04:00
|
|
|
|
|
|
|
extern void vector_set(vector_t * vector,
|
|
|
|
void * data,
|
|
|
|
size_t element);
|
|
|
|
|
|
|
|
extern void vector_free(vector_t * vector);
|
|
|
|
|
|
|
|
void vector_init(vector_t * vector,
|
|
|
|
size_t element_size,
|
|
|
|
size_t element_count) {
|
|
|
|
vector->data = NULL;
|
|
|
|
vector->element_size = element_size;
|
|
|
|
vector->element_count = element_count;
|
|
|
|
|
|
|
|
vector->data = malloc(vector->element_size * vector->element_count);
|
|
|
|
|
|
|
|
if ((! vector->data) && (vector->element_count)) {
|
|
|
|
puts("vector_init");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
memset(vector->data,
|
|
|
|
0,
|
|
|
|
vector->element_size * vector->element_count);
|
|
|
|
}
|
|
|
|
|
|
|
|
void vector_push(vector_t * vector,
|
|
|
|
void * data) {
|
|
|
|
++vector->element_count;
|
|
|
|
|
|
|
|
vector->data = realloc(vector->data,
|
|
|
|
vector->element_size * vector->element_count);
|
|
|
|
|
|
|
|
if (! vector->data) {
|
|
|
|
puts("vector_push");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
memcpy(&vector->data[(vector->element_count - 1) * vector->element_size],
|
|
|
|
data,
|
|
|
|
vector->element_size);
|
|
|
|
}
|
|
|
|
|
|
|
|
void vector_pop(vector_t * vector) {
|
|
|
|
(void) vector;
|
|
|
|
}
|
|
|
|
|
2023-08-23 21:14:12 -04:00
|
|
|
void * vector_get(const vector_t * const vector,
|
|
|
|
const size_t element) {
|
2023-08-23 19:29:23 -04:00
|
|
|
if (element >= vector->element_count) {
|
|
|
|
puts("vector_get");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
return &vector->data[vector->element_size * element];
|
|
|
|
}
|
|
|
|
|
|
|
|
void vector_set(vector_t * vector,
|
|
|
|
void * data,
|
|
|
|
size_t element) {
|
|
|
|
if (element >= vector->element_count) {
|
|
|
|
puts("vector_set");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
memcpy(&vector->data[vector->element_size * element],
|
|
|
|
data,
|
|
|
|
vector->element_size);
|
|
|
|
}
|
|
|
|
|
|
|
|
void vector_free(vector_t * vector) {
|
|
|
|
free(vector->data);
|
|
|
|
}
|
2023-08-23 21:14:12 -04:00
|
|
|
|
|
|
|
#endif
|