cvector/src/vector.h

83 lines
2.3 KiB
C

#ifndef VECTOR_H
#define VECTOR_H
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef DEBUG
# define DEBUG 0
#endif
#define ERR_MEM_ALLOC 1
#define NO_COLOR "\x1b[0m"
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define BROWN "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define GRAY "\x1b[37m"
#define UNINPLEMENTED printf("%s:%d: Not yet implemented", __FILE__, __LINE__)
#define INITIAL_CAPACITY 4
#define PCOMMON(color, format, ...) \
fprintf(stderr, \
"%s%s:%d%s\t" format "\n", \
color, \
__FILE__, \
__LINE__, \
NO_COLOR, \
__VA_ARGS__)
#define PDEB(format, ...) PCOMMON(GREEN, format, __VA_ARGS__)
#define PERR(format, ...) PCOMMON(RED, format, __VA_ARGS__)
/* Destructor typedef */
typedef void (*Destructor)(void *element);
typedef struct Vector_s {
size_t length;
size_t capacity;
const size_t offset;
void ** elements;
Destructor destroy;
} Vector;
typedef struct Result_s {
union {
const char *message;
void * value;
} result;
bool error;
} Result;
Result vec_new(Destructor destructor);
Result vec_with_capacity(Destructor const destructor, size_t const capacity);
Result vec_push(Vector *const self, void *const element);
Result vec_shrink_to_fit(Vector *const self);
void * vec_safe_at(Vector const *const self, size_t const index);
void vec_pop(Vector *const self);
void vec_delete(Vector *const self);
inline size_t vec_length(Vector const *const self)
{
return self->length;
}
inline size_t vec_capacity(Vector const *const self)
{
return self->capacity;
}
inline void *vec_at(Vector const *const self, size_t const index)
{
return self->elements[index];
}
inline void *vec_last(Vector const *const self)
{
return vec_at(self, vec_length(self) - 1);
}
#endif /* VECTOR_H */