[PATCH 03/16] strvec: introduce `strvec_init_alloc()`
- From
Taylor Blau <me@ttaylorr.com>
- Date
- Mar 29, 2026, 21:40 UTC
- Message-ID
- <aea6aad695336a974df9c90ce7bd02ddcc33582f.1774820449.git.me@ttaylorr.com>
- In-Reply-To
- <cover.1774820449.git.me@ttaylorr.com>
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 <gitster@pobox.com> Signed-off-by: Taylor Blau <me@ttaylorr.com> --- strvec.c | 15 +++++++++++++-- strvec.h | 5 +++++ 2 files changed, 18 insertions(+), 2 deletions(-)
diff --git a/strvec.c b/strvec.c index f8de79f5579..15371980b84 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 f74e061e141..34cb1f939f0 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 *);
-- 2.53.0.729.g817728289e1.dirty