From 55ed8c59393153ee0fda9d8f377cbbf56c2728c3 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Thu, 5 Mar 2026 22:11:23 +0000 Subject: [PATCH] lisp: lisp_reset, vec: vec_reset Reset method to "clear the memory" of a lisp object. Only operates on heap allocated objects. --- include/alisp/lisp.h | 9 +++++---- include/alisp/vec.h | 1 + src/lisp.c | 34 ++++++++++++++++++++++++++++++++++ src/vec.c | 8 ++++++++ 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/include/alisp/lisp.h b/include/alisp/lisp.h index 5f24853..630082b 100644 --- a/include/alisp/lisp.h +++ b/include/alisp/lisp.h @@ -49,6 +49,11 @@ typedef enum Tag #define INT_MIN (-(INT_MAX + 1)) tag_t tag_get(const lisp_t *); +u64 tag_sizeof(tag_t); +u64 lisp_sizeof(lisp_t *); +lisp_t *lisp_reset(lisp_t *); +void lisp_print(FILE *, lisp_t *); + lisp_t *tag_smi(const i64); lisp_t *tag_sym(const char *); lisp_t *tag_cons(const cons_t *); @@ -65,10 +70,6 @@ str_t *as_str(lisp_t *); #define CAR(L) (as_cons(L)->car) #define CDR(L) (as_cons(L)->cdr) -void lisp_print(FILE *, lisp_t *); -u64 tag_sizeof(tag_t); -u64 lisp_sizeof(lisp_t *); - #endif /* Copyright (C) 2026 Aryadev Chavali diff --git a/include/alisp/vec.h b/include/alisp/vec.h index 1bbdb6a..cdc3633 100644 --- a/include/alisp/vec.h +++ b/include/alisp/vec.h @@ -36,6 +36,7 @@ static_assert(sizeof(vec_t) == 64, "vec_t has to be 64 bytes as part of SBO"); void vec_init(vec_t *, u64); void vec_free(vec_t *); +void vec_reset(vec_t *); u8 *vec_data(vec_t *); // Append, possibly reallocating memory diff --git a/src/lisp.c b/src/lisp.c index cdc9cfa..4ad3791 100644 --- a/src/lisp.c +++ b/src/lisp.c @@ -238,6 +238,40 @@ u64 lisp_sizeof(lisp_t *lisp) return tag_sizeof(tag_get(lisp)); } +lisp_t *lisp_reset(lisp_t *lisp) +{ + switch (tag_get(lisp)) + { + case TAG_NIL: + case TAG_SMI: + case TAG_SYM: + // Nothing to "reset" here. + return lisp; + case TAG_CONS: + { + // Make `car` and `cons` NIL + CAR(lisp) = NIL; + CDR(lisp) = NIL; + return lisp; + } + case TAG_VEC: + { + vec_reset(as_vec(lisp)); + return lisp; + } + case TAG_STR: + { + vec_reset(&as_str(lisp)->data); + return lisp; + } + default: + { + FAIL("Unreachable"); + return lisp; + } + } +} + /* Copyright (C) 2025, 2026 Aryadev Chavali * This program is distributed in the hope that it will be useful, but WITHOUT diff --git a/src/vec.c b/src/vec.c index c522f96..66c59e3 100644 --- a/src/vec.c +++ b/src/vec.c @@ -38,6 +38,14 @@ void vec_free(vec_t *vec) memset(vec, 0, sizeof(*vec)); } +void vec_reset(vec_t *vec) +{ + if (!vec) + return; + memset(vec_data(vec), 0, vec->capacity); + vec->size = 0; +} + u8 *vec_data(vec_t *vec) { return vec->not_inlined ? vec->ptr : vec->inlined;