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 <gitster@pobox.com>
Signed-off-by: Taylor Blau <me@ttaylorr.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Taylor Blau
2026-03-29 17:40:58 -04:00
committed by Junio C Hamano
parent bdb2f8a521
commit cd45bf0f3e
2 changed files with 18 additions and 2 deletions

View File

@@ -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)

View File

@@ -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 *);