From cd45bf0f3e4a8105984df55d5dcdb69d972e8048 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Sun, 29 Mar 2026 17:40:58 -0400 Subject: [PATCH] strvec: introduce `strvec_init_alloc()` When the caller knows upfront how many elements will be pushed onto a `strvec`, it is useful to pre-allocate enough space in the array to fit that many elements (and one additional slot to store NULL, indicating the end of the list.) Introduce `strvec_init_alloc()`, which allocates the backing array large enough to hold `alloc` elements and the termination marker without further reallocation. Reimplement `strvec_init()` as a special case of `strvec_init_alloc()`, namely when `alloc` is zero. Helped-by: Junio C Hamano Signed-off-by: Taylor Blau Signed-off-by: Junio C Hamano --- strvec.c | 15 +++++++++++++-- strvec.h | 5 +++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/strvec.c b/strvec.c index f8de79f557..15371980b8 100644 --- a/strvec.c +++ b/strvec.c @@ -6,8 +6,19 @@ const char *empty_strvec[] = { NULL }; void strvec_init(struct strvec *array) { - struct strvec blank = STRVEC_INIT; - memcpy(array, &blank, sizeof(*array)); + strvec_init_alloc(array, 0); +} + +void strvec_init_alloc(struct strvec *array, size_t alloc) +{ + if (!alloc) { + struct strvec blank = STRVEC_INIT; + memcpy(array, &blank, sizeof(*array)); + } else { + CALLOC_ARRAY(array->v, st_add(alloc, 1)); + array->nr = 0; + array->alloc = alloc + 1; + } } void strvec_push_nodup(struct strvec *array, char *value) diff --git a/strvec.h b/strvec.h index f74e061e14..34cb1f939f 100644 --- a/strvec.h +++ b/strvec.h @@ -43,6 +43,11 @@ struct strvec { */ void strvec_init(struct strvec *); +/* + * Initializes an array large enough to store `alloc` elements. + */ +void strvec_init_alloc(struct strvec *, size_t alloc); + /* Push a copy of a string onto the end of the array. */ const char *strvec_push(struct strvec *, const char *);