From 0e75b541df04d51fbe8cc94490b7aa30d1f12b19 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Fri, 13 Feb 2026 00:07:24 +0000 Subject: [PATCH] vec: vec_try_append Essentially a method to attempt to append data but without doing any reallocation - stay within the bounds of the capacity. --- include/alisp/vec.h | 3 +++ src/vec.c | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/include/alisp/vec.h b/include/alisp/vec.h index 035021b..50cb4f9 100644 --- a/include/alisp/vec.h +++ b/include/alisp/vec.h @@ -36,7 +36,10 @@ void vec_init(vec_t *, u64); void vec_free(vec_t *); u8 *vec_data(vec_t *); +// Append, possibly reallocating memory void vec_append(vec_t *, const void *const, u64); +// Try to append without allocating memory +bool vec_try_append(vec_t *, const void *const, u64); void vec_ensure_free(vec_t *, u64); void vec_clone(vec_t *, vec_t *); diff --git a/src/vec.c b/src/vec.c index e4b9d6f..c522f96 100644 --- a/src/vec.c +++ b/src/vec.c @@ -81,10 +81,24 @@ void vec_append(vec_t *vec, const void *const ptr, u64 size) if (!vec) return; vec_ensure_free(vec, size); - memcpy(vec_data(vec) + vec->size, ptr, size); + if (ptr) + memcpy(vec_data(vec) + vec->size, ptr, size); vec->size += size; } +bool vec_try_append(vec_t *vec, const void *const ptr, u64 size) +{ + if (!vec || vec->capacity - vec->size < size) + return false; + if (ptr) + { + void *newptr = vec_data(vec) + vec->size; + memcpy(newptr, ptr, size); + } + vec->size += size; + return true; +} + void vec_clone(vec_t *dest, vec_t *src) { if (!src || !dest)