From 6e2db6825d4ff4b57be3086f654a84cc9ff64bcf Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Wed, 20 Aug 2025 22:33:40 +0100 Subject: Stable vector implementation Stable vectors will be used in the lisp runtime to implement actual vectors, instead of using the disgusting lvec trick. This way we at least can get attributes about the vector through one pointer hop. --- alisp.h | 12 ++++++++++++ build.sh | 2 +- vec.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 vec.c diff --git a/alisp.h b/alisp.h index cf9ef55..fe24c74 100644 --- a/alisp.h +++ b/alisp.h @@ -46,6 +46,18 @@ typedef struct sv_t sv_copy(sv_t); +/// Good ol' Dynamic Arrays +typedef struct Vector +{ + u64 size, capacity; + void *data; +} vec_t; + +#define VEC_MULT 2 +void vec_free(vec_t *); +void vec_ensure_free(vec_t *, u64); +void vec_append(vec_t *, void *, u64); +void vec_clone(vec_t *, vec_t *); /// Inlined Dynamic arrays typedef struct InlineVector diff --git a/build.sh b/build.sh index a5c8f0a..c97fac8 100644 --- a/build.sh +++ b/build.sh @@ -1,7 +1,7 @@ #!/usr/bin/env sh CFLAGS="-Wall -Wextra -std=c11 -ggdb -fsanitize=address -fsanitize=undefined" -SRC="ivec.c symtable.c tag.c constructor.c sys.c main.c" +SRC="vec.c ivec.c symtable.c tag.c constructor.c sys.c main.c" OUT="alisp.out" set -xe diff --git a/vec.c b/vec.c new file mode 100644 index 0000000..84f6944 --- /dev/null +++ b/vec.c @@ -0,0 +1,57 @@ +/* Copyright (C) 2025 Aryadev Chavali + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Unlicense + * for details. + + * You may distribute and modify this code under the terms of the + * Unlicense, which you should have received a copy of along with this + * program. If not, please go to . + + * Created: 2025-08-20 + * Description: Stable Vector implementation + */ + +#include +#include + +#include "./alisp.h" + +void vec_free(vec_t *vec) +{ + if (!vec) + return; + if (vec->data) + free(vec->data); + memset(vec, 0, sizeof(*vec)); +} + +void vec_ensure_free(vec_t *vec, u64 size) +{ + if (!vec) + return; + if (vec->capacity - vec->size < size) + { + vec->capacity = MAX(vec->capacity * VEC_MULT, vec->size + size); + vec->data = realloc(vec->data, vec->capacity); + } +} + +void vec_append(vec_t *vec, void *ptr, u64 size) +{ + if (!vec) + return; + vec_ensure_free(vec, size); + memcpy(vec->data + vec->size, ptr, size); + vec->size += size; +} + +void vec_clone(vec_t *dest, vec_t *src) +{ + if (!src || !dest) + return; + dest = src; + dest->data = calloc(1, dest->capacity); + memcpy(dest->data, src->data, src->size); +} -- cgit v1.2.3-13-gbd6f