Subject: Re: [RFC PATCH 02/14] strvec: introduce `strvec_init_alloc()`

From: Junio C Hamano <[email-masked]>
Date: Thu, 26 Feb 2026 12:58:48 -0800

Junio C Hamano <[email-masked]> writes:

> Taylor Blau <[email-masked]> writes:
>
>> 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.
>>
>> Signed-off-by: Taylor Blau <[email-masked]>
>> ---
>>  strvec.c | 7 +++++++
>>  strvec.h | 5 +++++
>>  2 files changed, 12 insertions(+)
>>
>> diff --git a/strvec.c b/strvec.c
>> index f8de79f5579..f7f32a53b56 100644
>> --- a/strvec.c
>> +++ b/strvec.c
>> @@ -10,6 +10,13 @@ void strvec_init(struct strvec *array)
>>  	memcpy(array, &blank, sizeof(*array));
>>  }
>>  
>> +void strvec_init_alloc(struct strvec *array, size_t alloc)
>> +{
>> +	CALLOC_ARRAY(array->v, st_add(alloc, 1));
>> +	array->nr = 0;
>> +	array->alloc = alloc + 1;
>> +}
>
> It is not satisifying that strvec_init() does *not* become a thin
> wrapper around this that says "my initial allocation is for zero
> elements", but that cannot be done easily as a strvec that begins as
> an empty one has a small optimization to avoid one-slot allocation
> only to store NULL.  So, ... OK.

Actually, we should do the same optimization if a caller explicitly
asks

	strvec_init_alloc(&array, 0);

So perhaps we could do this if we wanted to encapsulate the tricky
bits in a single place for maintainability.

 strvec.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git c/strvec.c w/strvec.c
index f8de79f557..cbe72e9411 100644
--- c/strvec.c
+++ w/strvec.c
@@ -4,10 +4,21 @@
 
 const char *empty_strvec[] = { NULL };
 
+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_init(struct strvec *array)
 {
-	struct strvec blank = STRVEC_INIT;
-	memcpy(array, &blank, sizeof(*array));
+	strvec_init(array, 0);
 }
 
 void strvec_push_nodup(struct strvec *array, char *value)