basic/strv: add function to insert items at position

This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2018-02-01 12:50:18 +01:00
parent 7b1aaf6633
commit 6e888894fc
3 changed files with 43 additions and 4 deletions

View File

@ -446,7 +446,7 @@ int strv_push_pair(char ***l, char *a, char *b) {
return 0;
}
int strv_push_prepend(char ***l, char *value) {
int strv_insert(char ***l, unsigned position, char *value) {
char **c;
unsigned n, m, i;
@ -454,6 +454,7 @@ int strv_push_prepend(char ***l, char *value) {
return 0;
n = strv_length(*l);
position = MIN(position, n);
/* increase and check for overflow */
m = n + 2;
@ -464,10 +465,12 @@ int strv_push_prepend(char ***l, char *value) {
if (!c)
return -ENOMEM;
for (i = 0; i < n; i++)
for (i = 0; i < position; i++)
c[i] = (*l)[i];
c[position] = value;
for (i = position; i < n; i++)
c[i+1] = (*l)[i];
c[0] = value;
c[n+1] = NULL;
free(*l);

View File

@ -54,7 +54,12 @@ int strv_extendf(char ***l, const char *format, ...) _printf_(2,0);
int strv_extend_front(char ***l, const char *value);
int strv_push(char ***l, char *value);
int strv_push_pair(char ***l, char *a, char *b);
int strv_push_prepend(char ***l, char *value);
int strv_insert(char ***l, unsigned position, char *value);
static inline int strv_push_prepend(char ***l, char *value) {
return strv_insert(l, 0, value);
}
int strv_consume(char ***l, char *value);
int strv_consume_pair(char ***l, char *a, char *b);
int strv_consume_prepend(char ***l, char *value);

View File

@ -447,6 +447,36 @@ static void test_strv_from_stdarg_alloca(void) {
test_strv_from_stdarg_alloca_one(STRV_MAKE_EMPTY, NULL);
}
static void test_strv_insert(void) {
_cleanup_strv_free_ char **a = NULL;
assert_se(strv_insert(&a, 0, strdup("first")) == 0);
assert_se(streq(a[0], "first"));
assert_se(!a[1]);
assert_se(strv_insert(&a, 0, NULL) == 0);
assert_se(streq(a[0], "first"));
assert_se(!a[1]);
assert_se(strv_insert(&a, 1, strdup("two")) == 0);
assert_se(streq(a[0], "first"));
assert_se(streq(a[1], "two"));
assert_se(!a[2]);
assert_se(strv_insert(&a, 4, strdup("tri")) == 0);
assert_se(streq(a[0], "first"));
assert_se(streq(a[1], "two"));
assert_se(streq(a[2], "tri"));
assert_se(!a[3]);
assert_se(strv_insert(&a, 1, strdup("duo")) == 0);
assert_se(streq(a[0], "first"));
assert_se(streq(a[1], "duo"));
assert_se(streq(a[2], "two"));
assert_se(streq(a[3], "tri"));
assert_se(!a[4]);
}
static void test_strv_push_prepend(void) {
_cleanup_strv_free_ char **a = NULL;
@ -723,6 +753,7 @@ int main(int argc, char *argv[]) {
test_strv_extend();
test_strv_extendf();
test_strv_from_stdarg_alloca();
test_strv_insert();
test_strv_push_prepend();
test_strv_push();
test_strv_equal();