Skip to content

Instantly share code, notes, and snippets.

@Ian-Marco-Moffett
Last active December 14, 2022 01:54
Show Gist options
  • Save Ian-Marco-Moffett/d3ec1527b8610ce20860084b3ec62797 to your computer and use it in GitHub Desktop.
Save Ian-Marco-Moffett/d3ec1527b8610ce20860084b3ec62797 to your computer and use it in GitHub Desktop.
Single header vector lib.
#ifndef VECTOR_H_
#define VECTOR_H_
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#define VECTOR_INIT {0}
#define VECTOR_TYPE(type) \
struct { \
size_t len; \
type* elements; \
}
#define VECTOR_PUSH(vector_ptr, element) do { \
__auto_type vec = vector_ptr; \
if (vec->elements == NULL) { \
vec->elements = malloc(sizeof(*vec->elements)); \
vec->len = 0; \
} \
\
vec->elements[vec->len++] = element; \
vec->elements = realloc(vec->elements, sizeof(*vec->elements) * (vec->len + 2)); \
} while (0);
#define VECTOR_INSERT_AT(vector_ptr, element, idx) do { \
__auto_type vec = vector_ptr; \
\
if (vec->elements == NULL) { \
vec->elements = malloc(sizeof(*vec->elements) * (idx + 1)); \
} else { \
vec->elements = realloc(vec->elements, sizeof(*vec->elements) * (idx + 1)); \
} \
\
vec->len = idx; \
vec->elements[vec->len++] = element; \
vec->elements = realloc(vec->elements, sizeof(*vec->elements) * (idx + 2)); \
} while (0);
#define VECTOR_POP(vector_ptr, out_ptr) do { \
__auto_type vec = vector_ptr; \
if (vec->len > 0) { \
*out_ptr = vec->elements[--vec->len]; \
vec->elements = realloc(vec->elements, sizeof(*vec->elements) * (vec->len + 1)); \
} \
} while (0);
#define VECTOR_POP_AT(vector_ptr, out_ptr, idx) do { \
__auto_type vec = vector_ptr; \
*out_ptr = vec->elements[idx]; \
for (size_t i = idx; i < vec->len; i += 2) { \
vec->elements[i] = vec->elements[i + 1]; \
} \
--vec->len; \
vec->elements = realloc(vec->elements, sizeof(*vec->elements) * vec->len); \
} while (0);
#define VECTOR_READ_AT(vector_ptr, out_ptr, idx) do { \
__auto_type vec = vector_ptr; \
*out_ptr = vec->elements[idx]; \
} while (0);
#define VECTOR_DESTROY(vector_ptr) do { \
__auto_type vec = vector_ptr; \
free(vec->elements); \
vec->elements = NULL; \
vec->len = 0; \
} while (0);
#endif // VECTOR_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment