This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
sys_prog/collections/vector.c

63 lines
1.4 KiB
C
Raw Normal View History

2019-09-01 12:52:45 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
2019-09-01 15:50:45 +00:00
// Type for vector, change to the desired type to be used in the vector
#define VECTOR_TYPE int
2019-09-01 12:52:45 +00:00
2019-09-01 15:50:45 +00:00
typedef struct vector {
2019-09-01 12:52:45 +00:00
size_t length;
VECTOR_TYPE* arr;
2019-09-01 12:52:45 +00:00
size_t start;
size_t size;
} vector_t;
2019-09-01 12:52:45 +00:00
2019-09-01 14:07:21 +00:00
inline static size_t vector_end(vector_t* self) {
return (self->start + self->size) % self->length;
}
vector_t vector_init(size_t length) {
vector_t self;
2019-09-01 12:52:45 +00:00
self.length = length;
self.arr = malloc(length * sizeof(VECTOR_TYPE));
2019-09-01 12:52:45 +00:00
self.start = 0;
self.size = 0;
return self;
}
bool vector_add(vector_t* self, VECTOR_TYPE element, bool to_end) {
2019-09-01 12:52:45 +00:00
if (self->size == self->length) {
return false;
}
if (to_end) {
2019-09-01 14:07:21 +00:00
self->arr[vector_end(self)] = element;
} else {
if (self->size == 0) {
self->arr[self->start] = element;
} else {
self->arr[self->start - 1] = element;
self->start--;
}
}
2019-09-01 12:52:45 +00:00
self->size++;
return true;
}
bool vector_remove(vector_t* self, VECTOR_TYPE* destination, bool from_end) {
2019-09-01 12:52:45 +00:00
if (self->size == 0) {
return false;
}
2019-09-01 14:07:21 +00:00
*destination = self->arr[!from_end ? vector_end(self) : self->start];
2019-09-01 15:50:45 +00:00
self->start = from_end ? (self->start + 1) % self->length : self->start;
2019-09-01 12:52:45 +00:00
self->size--;
return true;
}
void vector_destroy(vector_t* self) {
2019-09-01 12:52:45 +00:00
if (self->arr != NULL) {
free(self->arr);
self->arr = NULL;
}
}