diff options
author | Kimplul <kimi.h.kuparinen@gmail.com> | 2024-10-19 21:43:48 +0300 |
---|---|---|
committer | Kimplul <kimi.h.kuparinen@gmail.com> | 2024-10-23 18:25:23 +0300 |
commit | e3bb9a4ddc0465d4a75ca64e36416a9568c74d27 (patch) | |
tree | 2a0281b4885f49ad92a4e5acfe4c28fa88a24129 /src/vec.c | |
parent | 7c5f098511b8f612a17f4ccdd8a4924c325d37e1 (diff) | |
download | lyn-e3bb9a4ddc0465d4a75ca64e36416a9568c74d27.tar.gz lyn-e3bb9a4ddc0465d4a75ca64e36416a9568c74d27.zip |
some basic programs run
Diffstat (limited to 'src/vec.c')
-rw-r--r-- | src/vec.c | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/vec.c b/src/vec.c new file mode 100644 index 0000000..dc7d3b1 --- /dev/null +++ b/src/vec.c @@ -0,0 +1,67 @@ +/* SPDX-License-Identifier: copyleft-next-0.3.1 */ + +#include <stdlib.h> +#include <assert.h> +#include <string.h> + +#include <lyn/vec.h> + +struct vec vec_create(size_t ns) +{ + return (struct vec) { + .n = 0, + .s = 1, + .ns = ns, + .buf = malloc(ns), + }; +} + +size_t vec_len(struct vec *v) +{ + return v->n; +} + +void *vec_at(struct vec *v, size_t i) +{ + assert(i < v->n && "out of vector bounds"); + return v->buf + i * v->ns; +} + +void *vec_back(struct vec *v) +{ + assert(v->n); + return v->buf + (v->n - 1) * v->ns; +} + +void *vec_pop(struct vec *v) +{ + assert(v->n && "attempting to pop empty vector"); + v->n--; + return v->buf + v->n * v->ns; +} + +void vec_append(struct vec *v, void *n) +{ + v->n++; + if (v->n >= v->s) { + v->s *= 2; + v->buf = realloc(v->buf, v->s * v->ns); + } + + void *p = vec_at(v, v->n - 1); + memcpy(p, n, v->ns); +} + +void vec_reset(struct vec *v) +{ + v->n = 0; +} + +void vec_destroy(struct vec *v) { + free(v->buf); +} + +void vec_sort(struct vec *v, vec_comp_t comp) +{ + qsort(v->buf, v->n, v->ns, comp); +} |