]> code.citadel.org Git - citadel.git/blobdiff - libcitadel/lib/array.c
Saving my place while we try something...
[citadel.git] / libcitadel / lib / array.c
index 444a3470a48b4e194e4a9977566778026936351f..1adc1fde8f39f078464b3fdbb486e4930028bfd1 100644 (file)
@@ -61,12 +61,18 @@ void array_append(Array *arr, void *new_element) {
                arr->num_alloc = 1;
                arr->num_elements = 0;
                arr->the_elements = malloc(arr->element_size * arr->num_alloc);
+               if (arr->the_elements == NULL) {
+                       abort();
+               }
        }
 
        ++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));
+               if (arr->the_elements == NULL) {
+                       abort();
+               }
        }
 
        memcpy((arr->the_elements + ( (arr->num_elements-1) * arr->element_size )), new_element, arr->element_size);
@@ -87,3 +93,39 @@ void *array_get_element_at(Array *arr, int index) {
 int array_len(Array *arr) {
        return arr->num_elements;
 }
+
+
+/*
+ * Sort an array.  We already know the element size and number of elements, so all we need is
+ * a sort function, which we will pass along to qsort().
+ */
+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;
+       }
+
+       if (index < 0) {                                // If the supplied index is invalid, 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
+       );
+}