src/array_list.c

Wed, 24 Jan 2024 22:19:05 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 24 Jan 2024 22:19:05 +0100
changeset 817
949908c97474
parent 807
c8d692131b1e
child 818
2be8fe3d5a2d
permissions
-rw-r--r--

add cx_array_default_reallocator

     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2021 Mike Becker, Olaf Wintermann All rights reserved.
     5  *
     6  * Redistribution and use in source and binary forms, with or without
     7  * modification, are permitted provided that the following conditions are met:
     8  *
     9  *   1. Redistributions of source code must retain the above copyright
    10  *      notice, this list of conditions and the following disclaimer.
    11  *
    12  *   2. Redistributions in binary form must reproduce the above copyright
    13  *      notice, this list of conditions and the following disclaimer in the
    14  *      documentation and/or other materials provided with the distribution.
    15  *
    16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    26  * POSSIBILITY OF SUCH DAMAGE.
    27  */
    29 #include "cx/array_list.h"
    30 #include "cx/compare.h"
    31 #include <assert.h>
    32 #include <string.h>
    34 // Default array reallocator
    36 static void *cx_array_default_realloc(
    37         void *array,
    38         size_t capacity,
    39         size_t elem_size,
    40         __attribute__((__unused__)) struct cx_array_reallocator_s *alloc
    41 ) {
    42     return realloc(array, capacity * elem_size);
    43 }
    45 struct cx_array_reallocator_s cx_array_default_reallocator = {
    46         cx_array_default_realloc, NULL, NULL, 0, 0
    47 };
    49 // LOW LEVEL ARRAY LIST FUNCTIONS
    51 enum cx_array_copy_result cx_array_copy(
    52         void **target,
    53         size_t *size,
    54         size_t *capacity,
    55         size_t index,
    56         void const *src,
    57         size_t elem_size,
    58         size_t elem_count,
    59         struct cx_array_reallocator_s *reallocator
    60 ) {
    61     // assert pointers
    62     assert(target != NULL);
    63     assert(size != NULL);
    64     assert(src != NULL);
    66     // determine capacity
    67     size_t cap = capacity == NULL ? *size : *capacity;
    69     // check if resize is required
    70     size_t minsize = index + elem_count;
    71     size_t newsize = *size < minsize ? minsize : *size;
    72     bool needrealloc = newsize > cap;
    74     // reallocate if possible
    75     if (needrealloc) {
    76         // a reallocator and a capacity variable must be available
    77         if (reallocator == NULL || capacity == NULL) {
    78             return CX_ARRAY_COPY_REALLOC_NOT_SUPPORTED;
    79         }
    81         // check, if we need to repair the src pointer
    82         uintptr_t targetaddr = (uintptr_t) *target;
    83         uintptr_t srcaddr = (uintptr_t) src;
    84         bool repairsrc = targetaddr <= srcaddr
    85                          && srcaddr < targetaddr + cap * elem_size;
    87         // calculate new capacity (next number divisible by 16)
    88         cap = newsize - (newsize % 16) + 16;
    89         assert(cap > newsize);
    91         // perform reallocation
    92         void *newmem = reallocator->realloc(
    93                 *target, cap, elem_size, reallocator
    94         );
    95         if (newmem == NULL) {
    96             return CX_ARRAY_COPY_REALLOC_FAILED;
    97         }
    99         // repair src pointer, if necessary
   100         if (repairsrc) {
   101             src = ((char *) newmem) + (srcaddr - targetaddr);
   102         }
   104         // store new pointer and capacity
   105         *target = newmem;
   106         *capacity = cap;
   107     }
   109     // determine target pointer
   110     char *start = *target;
   111     start += index * elem_size;
   113     // copy elements and set new size
   114     memmove(start, src, elem_count * elem_size);
   115     *size = newsize;
   117     // return successfully
   118     return CX_ARRAY_COPY_SUCCESS;
   119 }
   121 #ifndef CX_ARRAY_SWAP_SBO_SIZE
   122 #define CX_ARRAY_SWAP_SBO_SIZE 128
   123 #endif
   124 unsigned cx_array_swap_sbo_size = CX_ARRAY_SWAP_SBO_SIZE;
   126 void cx_array_swap(
   127         void *arr,
   128         size_t elem_size,
   129         size_t idx1,
   130         size_t idx2
   131 ) {
   132     assert(arr != NULL);
   134     // short circuit
   135     if (idx1 == idx2) return;
   137     char sbo_mem[CX_ARRAY_SWAP_SBO_SIZE];
   138     void *tmp;
   140     // decide if we can use the local buffer
   141     if (elem_size > CX_ARRAY_SWAP_SBO_SIZE) {
   142         tmp = malloc(elem_size);
   143         // we don't want to enforce error handling
   144         if (tmp == NULL) abort();
   145     } else {
   146         tmp = sbo_mem;
   147     }
   149     // calculate memory locations
   150     char *left = arr, *right = arr;
   151     left += idx1 * elem_size;
   152     right += idx2 * elem_size;
   154     // three-way swap
   155     memcpy(tmp, left, elem_size);
   156     memcpy(left, right, elem_size);
   157     memcpy(right, tmp, elem_size);
   159     // free dynamic memory, if it was needed
   160     if (tmp != sbo_mem) {
   161         free(tmp);
   162     }
   163 }
   165 // HIGH LEVEL ARRAY LIST FUNCTIONS
   167 typedef struct {
   168     struct cx_list_s base;
   169     void *data;
   170     size_t capacity;
   171     struct cx_array_reallocator_s reallocator;
   172 } cx_array_list;
   174 static void *cx_arl_realloc(
   175         void *array,
   176         size_t capacity,
   177         size_t elem_size,
   178         struct cx_array_reallocator_s *alloc
   179 ) {
   180     // retrieve the pointer to the list allocator
   181     CxAllocator const *al = alloc->ptr1;
   183     // use the list allocator to reallocate the memory
   184     return cxRealloc(al, array, capacity * elem_size);
   185 }
   187 static void cx_arl_destructor(struct cx_list_s *list) {
   188     cx_array_list *arl = (cx_array_list *) list;
   190     char *ptr = arl->data;
   192     if (list->simple_destructor) {
   193         for (size_t i = 0; i < list->size; i++) {
   194             cx_invoke_simple_destructor(list, ptr);
   195             ptr += list->item_size;
   196         }
   197     }
   198     if (list->advanced_destructor) {
   199         for (size_t i = 0; i < list->size; i++) {
   200             cx_invoke_advanced_destructor(list, ptr);
   201             ptr += list->item_size;
   202         }
   203     }
   205     cxFree(list->allocator, arl->data);
   206     cxFree(list->allocator, list);
   207 }
   209 static size_t cx_arl_insert_array(
   210         struct cx_list_s *list,
   211         size_t index,
   212         void const *array,
   213         size_t n
   214 ) {
   215     // out of bounds and special case check
   216     if (index > list->size || n == 0) return 0;
   218     // get a correctly typed pointer to the list
   219     cx_array_list *arl = (cx_array_list *) list;
   221     // do we need to move some elements?
   222     if (index < list->size) {
   223         char const *first_to_move = (char const *) arl->data;
   224         first_to_move += index * list->item_size;
   225         size_t elems_to_move = list->size - index;
   226         size_t start_of_moved = index + n;
   228         if (CX_ARRAY_COPY_SUCCESS != cx_array_copy(
   229                 &arl->data,
   230                 &list->size,
   231                 &arl->capacity,
   232                 start_of_moved,
   233                 first_to_move,
   234                 list->item_size,
   235                 elems_to_move,
   236                 &arl->reallocator
   237         )) {
   238             // if moving existing elems is unsuccessful, abort
   239             return 0;
   240         }
   241     }
   243     // note that if we had to move the elements, the following operation
   244     // is guaranteed to succeed, because we have the memory already allocated
   245     // therefore, it is impossible to leave this function with an invalid array
   247     // place the new elements
   248     if (CX_ARRAY_COPY_SUCCESS == cx_array_copy(
   249             &arl->data,
   250             &list->size,
   251             &arl->capacity,
   252             index,
   253             array,
   254             list->item_size,
   255             n,
   256             &arl->reallocator
   257     )) {
   258         return n;
   259     } else {
   260         // array list implementation is "all or nothing"
   261         return 0;
   262     }
   263 }
   265 static int cx_arl_insert_element(
   266         struct cx_list_s *list,
   267         size_t index,
   268         void const *element
   269 ) {
   270     return 1 != cx_arl_insert_array(list, index, element, 1);
   271 }
   273 static int cx_arl_insert_iter(
   274         struct cx_mut_iterator_s *iter,
   275         void const *elem,
   276         int prepend
   277 ) {
   278     struct cx_list_s *list = iter->src_handle;
   279     if (iter->index < list->size) {
   280         int result = cx_arl_insert_element(
   281                 list,
   282                 iter->index + 1 - prepend,
   283                 elem
   284         );
   285         if (result == 0 && prepend != 0) {
   286             iter->index++;
   287             iter->elem_handle = ((char *) iter->elem_handle) + list->item_size;
   288         }
   289         return result;
   290     } else {
   291         int result = cx_arl_insert_element(list, list->size, elem);
   292         iter->index = list->size;
   293         return result;
   294     }
   295 }
   297 static int cx_arl_remove(
   298         struct cx_list_s *list,
   299         size_t index
   300 ) {
   301     cx_array_list *arl = (cx_array_list *) list;
   303     // out-of-bounds check
   304     if (index >= list->size) {
   305         return 1;
   306     }
   308     // content destruction
   309     cx_invoke_destructor(list, ((char *) arl->data) + index * list->item_size);
   311     // short-circuit removal of last element
   312     if (index == list->size - 1) {
   313         list->size--;
   314         return 0;
   315     }
   317     // just move the elements starting at index to the left
   318     int result = cx_array_copy(
   319             &arl->data,
   320             &list->size,
   321             &arl->capacity,
   322             index,
   323             ((char *) arl->data) + (index + 1) * list->item_size,
   324             list->item_size,
   325             list->size - index - 1,
   326             &arl->reallocator
   327     );
   328     if (result == 0) {
   329         // decrease the size
   330         list->size--;
   331     }
   332     return result;
   333 }
   335 static void cx_arl_clear(struct cx_list_s *list) {
   336     if (list->size == 0) return;
   338     cx_array_list *arl = (cx_array_list *) list;
   339     char *ptr = arl->data;
   341     if (list->simple_destructor) {
   342         for (size_t i = 0; i < list->size; i++) {
   343             cx_invoke_simple_destructor(list, ptr);
   344             ptr += list->item_size;
   345         }
   346     }
   347     if (list->advanced_destructor) {
   348         for (size_t i = 0; i < list->size; i++) {
   349             cx_invoke_advanced_destructor(list, ptr);
   350             ptr += list->item_size;
   351         }
   352     }
   354     memset(arl->data, 0, list->size * list->item_size);
   355     list->size = 0;
   356 }
   358 static int cx_arl_swap(
   359         struct cx_list_s *list,
   360         size_t i,
   361         size_t j
   362 ) {
   363     if (i >= list->size || j >= list->size) return 1;
   364     cx_array_list *arl = (cx_array_list *) list;
   365     cx_array_swap(arl->data, list->item_size, i, j);
   366     return 0;
   367 }
   369 static void *cx_arl_at(
   370         struct cx_list_s const *list,
   371         size_t index
   372 ) {
   373     if (index < list->size) {
   374         cx_array_list const *arl = (cx_array_list const *) list;
   375         char *space = arl->data;
   376         return space + index * list->item_size;
   377     } else {
   378         return NULL;
   379     }
   380 }
   382 static ssize_t cx_arl_find_remove(
   383         struct cx_list_s *list,
   384         void const *elem,
   385         bool remove
   386 ) {
   387     assert(list->cmpfunc != NULL);
   388     assert(list->size < SIZE_MAX / 2);
   389     char *cur = ((cx_array_list const *) list)->data;
   391     for (ssize_t i = 0; i < (ssize_t) list->size; i++) {
   392         if (0 == list->cmpfunc(elem, cur)) {
   393             if (remove) {
   394                 if (0 == cx_arl_remove(list, i)) {
   395                     return i;
   396                 } else {
   397                     return -1;
   398                 }
   399             } else {
   400                 return i;
   401             }
   402         }
   403         cur += list->item_size;
   404     }
   406     return -1;
   407 }
   409 static void cx_arl_sort(struct cx_list_s *list) {
   410     assert(list->cmpfunc != NULL);
   411     qsort(((cx_array_list *) list)->data,
   412           list->size,
   413           list->item_size,
   414           list->cmpfunc
   415     );
   416 }
   418 static int cx_arl_compare(
   419         struct cx_list_s const *list,
   420         struct cx_list_s const *other
   421 ) {
   422     assert(list->cmpfunc != NULL);
   423     if (list->size == other->size) {
   424         char const *left = ((cx_array_list const *) list)->data;
   425         char const *right = ((cx_array_list const *) other)->data;
   426         for (size_t i = 0; i < list->size; i++) {
   427             int d = list->cmpfunc(left, right);
   428             if (d != 0) {
   429                 return d;
   430             }
   431             left += list->item_size;
   432             right += other->item_size;
   433         }
   434         return 0;
   435     } else {
   436         return list->size < other->size ? -1 : 1;
   437     }
   438 }
   440 static void cx_arl_reverse(struct cx_list_s *list) {
   441     if (list->size < 2) return;
   442     void *data = ((cx_array_list const *) list)->data;
   443     size_t half = list->size / 2;
   444     for (size_t i = 0; i < half; i++) {
   445         cx_array_swap(data, list->item_size, i, list->size - 1 - i);
   446     }
   447 }
   449 static bool cx_arl_iter_valid(void const *it) {
   450     struct cx_iterator_s const *iter = it;
   451     struct cx_list_s const *list = iter->src_handle;
   452     return iter->index < list->size;
   453 }
   455 static void *cx_arl_iter_current(void const *it) {
   456     struct cx_iterator_s const *iter = it;
   457     return iter->elem_handle;
   458 }
   460 static void cx_arl_iter_next(void *it) {
   461     struct cx_iterator_base_s *itbase = it;
   462     if (itbase->remove) {
   463         struct cx_mut_iterator_s *iter = it;
   464         itbase->remove = false;
   465         cx_arl_remove(iter->src_handle, iter->index);
   466     } else {
   467         struct cx_iterator_s *iter = it;
   468         iter->index++;
   469         iter->elem_handle =
   470                 ((char *) iter->elem_handle)
   471                 + ((struct cx_list_s const *) iter->src_handle)->item_size;
   472     }
   473 }
   475 static void cx_arl_iter_prev(void *it) {
   476     struct cx_iterator_base_s *itbase = it;
   477     struct cx_mut_iterator_s *iter = it;
   478     cx_array_list *const list = iter->src_handle;
   479     if (itbase->remove) {
   480         itbase->remove = false;
   481         cx_arl_remove(iter->src_handle, iter->index);
   482     }
   483     iter->index--;
   484     if (iter->index < list->base.size) {
   485         iter->elem_handle = ((char *) list->data)
   486                             + iter->index * list->base.item_size;
   487     }
   488 }
   490 static bool cx_arl_iter_flag_rm(void *it) {
   491     struct cx_iterator_base_s *iter = it;
   492     if (iter->mutating) {
   493         iter->remove = true;
   494         return true;
   495     } else {
   496         return false;
   497     }
   498 }
   500 static struct cx_iterator_s cx_arl_iterator(
   501         struct cx_list_s const *list,
   502         size_t index,
   503         bool backwards
   504 ) {
   505     struct cx_iterator_s iter;
   507     iter.index = index;
   508     iter.src_handle = list;
   509     iter.elem_handle = cx_arl_at(list, index);
   510     iter.base.valid = cx_arl_iter_valid;
   511     iter.base.current = cx_arl_iter_current;
   512     iter.base.next = backwards ? cx_arl_iter_prev : cx_arl_iter_next;
   513     iter.base.flag_removal = cx_arl_iter_flag_rm;
   514     iter.base.remove = false;
   515     iter.base.mutating = false;
   517     return iter;
   518 }
   520 static cx_list_class cx_array_list_class = {
   521         cx_arl_destructor,
   522         cx_arl_insert_element,
   523         cx_arl_insert_array,
   524         cx_arl_insert_iter,
   525         cx_arl_remove,
   526         cx_arl_clear,
   527         cx_arl_swap,
   528         cx_arl_at,
   529         cx_arl_find_remove,
   530         cx_arl_sort,
   531         cx_arl_compare,
   532         cx_arl_reverse,
   533         cx_arl_iterator,
   534 };
   536 CxList *cxArrayListCreate(
   537         CxAllocator const *allocator,
   538         cx_compare_func comparator,
   539         size_t item_size,
   540         size_t initial_capacity
   541 ) {
   542     if (allocator == NULL) {
   543         allocator = cxDefaultAllocator;
   544     }
   546     cx_array_list *list = cxCalloc(allocator, 1, sizeof(cx_array_list));
   547     if (list == NULL) return NULL;
   549     list->base.cl = &cx_array_list_class;
   550     list->base.allocator = allocator;
   551     list->capacity = initial_capacity;
   553     if (item_size > 0) {
   554         list->base.item_size = item_size;
   555         list->base.cmpfunc = comparator;
   556     } else {
   557         item_size = sizeof(void *);
   558         list->base.cmpfunc = comparator == NULL ? cx_cmp_ptr : comparator;
   559         cxListStorePointers((CxList *) list);
   560     }
   562     // allocate the array after the real item_size is known
   563     list->data = cxCalloc(allocator, initial_capacity, item_size);
   564     if (list->data == NULL) {
   565         cxFree(allocator, list);
   566         return NULL;
   567     }
   569     // configure the reallocator
   570     list->reallocator.realloc = cx_arl_realloc;
   571     list->reallocator.ptr1 = (void *) allocator;
   573     return (CxList *) list;
   574 }

mercurial