chiark / gitweb /
basic/strv: add function to insert items at position
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Thu, 1 Feb 2018 11:50:18 +0000 (12:50 +0100)
committerSven Eden <yamakuzure@gmx.net>
Wed, 30 May 2018 05:58:48 +0000 (07:58 +0200)
src/basic/strv.c
src/basic/strv.h

index f3bb6965abc8a1f9208b33a6903aec60d403dead..85c55041ed8fd4e585e3487d9e51751a8ec6c66c 100644 (file)
@@ -452,7 +452,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;
 
@@ -460,6 +460,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;
@@ -470,10 +471,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);
index 489be2f7749430bfeb42a87ada95a3015d02acf6..2ef6d325d5fcdde6fe9275981760bfb792d5c205 100644 (file)
@@ -58,7 +58,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);
 #if 0 /// UNNEEDED by elogind
 int strv_consume_pair(char ***l, char *a, char *b);