]> git.ipfire.org Git - people/ms/strongswan.git/blobdiff - src/libstrongswan/collections/array.c
array: Add an insert/create function for value based arrays
[people/ms/strongswan.git] / src / libstrongswan / collections / array.c
index 642bbb349a1960596469e45c1916fb724068e067..a45a68aafeb3a35659e070bbd69dd5cee3b498ab 100644 (file)
@@ -141,7 +141,7 @@ static void remove_tail(array_t *array, int idx)
        /* move all items after idx one down */
        memmove(array->data + get_size(array, idx + array->head),
                        array->data + get_size(array, idx + array->head + 1),
-                       get_size(array, array->count - idx));
+                       get_size(array, array->count - 1 - idx));
        array->count--;
        array->tail++;
 }
@@ -168,7 +168,7 @@ array_t *array_create(u_int esize, u_int8_t reserve)
        );
        if (array->tail)
        {
-               array->data = malloc(array->tail * array->esize);
+               array->data = malloc(get_size(array, array->tail));
        }
        return array;
 }
@@ -277,6 +277,16 @@ void array_insert_create(array_t **array, int idx, void *ptr)
        array_insert(*array, idx, ptr);
 }
 
+void array_insert_create_value(array_t **array, u_int esize,
+                                                          int idx, void *val)
+{
+       if (*array == NULL)
+       {
+               *array = array_create(esize, 0);
+       }
+       array_insert(*array, idx, val);
+}
+
 void array_insert_enumerator(array_t *array, int idx, enumerator_t *enumerator)
 {
        void *ptr;
@@ -361,16 +371,16 @@ bool array_remove(array_t *array, int idx, void *data)
        {
                return FALSE;
        }
+       if (idx < 0)
+       {
+               idx = array_count(array) - 1;
+       }
        if (idx > array_count(array) / 2)
        {
                remove_tail(array, idx);
        }
        else
        {
-               if (idx < 0)
-               {
-                       idx = array_count(array) - 1;
-               }
                remove_head(array, idx);
        }
        if (array->head + array->tail > ARRAY_MAX_UNUSED)
@@ -391,7 +401,7 @@ typedef struct {
 
 #ifdef HAVE_QSORT_R_GNU
 static int compare_elements(const void *a, const void *b, void *arg)
-#elif  HAVE_QSORT_R_BSD
+#elif defined(HAVE_QSORT_R_BSD)
 static int compare_elements(void *arg, const void *a, const void *b)
 #else /* !HAVE_QSORT_R */
 static int compare_elements(const void *a, const void *b)
@@ -427,7 +437,7 @@ void array_sort(array_t *array, int (*cmp)(const void*,const void*,void*),
 #ifdef HAVE_QSORT_R_GNU
                qsort_r(start, array->count, get_size(array, 1), compare_elements,
                                &data);
-#elif  HAVE_QSORT_R_BSD
+#elif defined(HAVE_QSORT_R_BSD)
                qsort_r(start, array->count, get_size(array, 1), &data,
                                compare_elements);
 #else /* !HAVE_QSORT_R */