Added a delete element method to the array class in libcitadel.
authorArt Cancro <ajc@citadel.org>
Sat, 31 Jul 2021 19:59:54 +0000 (15:59 -0400)
committerArt Cancro <ajc@citadel.org>
Sat, 31 Jul 2021 19:59:54 +0000 (15:59 -0400)
libcitadel/lib/array.c
libcitadel/lib/libcitadel.h

index c8f433f5d5c3bdf2a070a060a56936854d8468ae..a8adb292d84ba950fbfabd59a3146f97637622ee 100644 (file)
@@ -65,7 +65,7 @@ void array_append(Array *arr, void *new_element) {
 
        ++arr->num_elements;
        if (arr->num_elements > arr->num_alloc) {
-               arr->num_alloc = arr->num_alloc * 2;
+               arr->num_alloc = arr->num_alloc * 2;            // whenever we exceed the buffer size, we double it.
                arr->the_elements = realloc(arr->the_elements, (arr->element_size * arr->num_alloc));
        }
 
@@ -96,3 +96,26 @@ int array_len(Array *arr) {
 void array_sort(Array *arr, int (*compar)(const void *, const void *)) {
        qsort(arr->the_elements, arr->num_elements, arr->element_size, compar);
 }
+
+
+/*
+ * Delete an element from an array
+ */
+void array_delete_element_at(Array *arr, int index) {
+
+       if (index >= arr->num_elements) {               // If the supplied index is out of bounds, return quietly.
+               return;
+       }
+
+       --arr->num_elements;
+
+       if (index == arr->num_elements) {               // If we deleted the element at the end, there's no more to be done.
+               return;
+       }
+
+       memcpy(
+               (arr->the_elements + (index * arr->element_size)),
+               arr->the_elements + ((index+1) * arr->element_size),
+               (arr->num_elements - index) * arr->element_size
+       );
+}
index 955918b94db4dec52b03f0217ee4f707d7f6ddeb..67183fcfe59f90e6664e49b15339d6250fa2ce04 100644 (file)
@@ -452,6 +452,7 @@ void array_append(Array *arr, void *new_element);
 void *array_get_element_at(Array *arr, int index);
 int array_len(Array *arr);
 void array_sort(Array *arr, int (*compar)(const void *, const void *));
+void array_delete_element_at(Array *arr, int index);
 
 
 /* vCard stuff */