Merge branch 'rj/strvec-splice-fix'

Correct strvec_splice() that misbehaved when the strvec is empty.

* rj/strvec-splice-fix:
  strvec: `strvec_splice()` to a statically initialized vector
This commit is contained in:
Junio C Hamano
2024-12-15 17:54:29 -08:00
2 changed files with 17 additions and 4 deletions

View File

@@ -61,16 +61,19 @@ void strvec_splice(struct strvec *array, size_t idx, size_t len,
{ {
if (idx + len > array->nr) if (idx + len > array->nr)
BUG("range outside of array boundary"); BUG("range outside of array boundary");
if (replacement_len > len) if (replacement_len > len) {
if (array->v == empty_strvec)
array->v = NULL;
ALLOC_GROW(array->v, array->nr + (replacement_len - len) + 1, ALLOC_GROW(array->v, array->nr + (replacement_len - len) + 1,
array->alloc); array->alloc);
array->v[array->nr + (replacement_len - len)] = NULL;
}
for (size_t i = 0; i < len; i++) for (size_t i = 0; i < len; i++)
free((char *)array->v[idx + i]); free((char *)array->v[idx + i]);
if (replacement_len != len) { if ((replacement_len != len) && array->nr)
memmove(array->v + idx + replacement_len, array->v + idx + len, memmove(array->v + idx + replacement_len, array->v + idx + len,
(array->nr - idx - len + 1) * sizeof(char *)); (array->nr - idx - len + 1) * sizeof(char *));
array->nr += (replacement_len - len); array->nr += replacement_len - len;
}
for (size_t i = 0; i < replacement_len; i++) for (size_t i = 0; i < replacement_len; i++)
array->v[idx + i] = xstrdup(replacement[i]); array->v[idx + i] = xstrdup(replacement[i]);
} }

View File

@@ -88,6 +88,16 @@ void test_strvec__pushv(void)
strvec_clear(&vec); strvec_clear(&vec);
} }
void test_strvec__splice_just_initialized_strvec(void)
{
struct strvec vec = STRVEC_INIT;
const char *replacement[] = { "foo" };
strvec_splice(&vec, 0, 0, replacement, ARRAY_SIZE(replacement));
check_strvec(&vec, "foo", NULL);
strvec_clear(&vec);
}
void test_strvec__splice_with_same_size_replacement(void) void test_strvec__splice_with_same_size_replacement(void)
{ {
struct strvec vec = STRVEC_INIT; struct strvec vec = STRVEC_INIT;