src/array_list.c

Wed, 08 Feb 2023 20:26:09 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 08 Feb 2023 20:26:09 +0100
changeset 647
2e6e9d9f2159
parent 643
5700ba9154ab
child 654
c9d008861178
permissions
-rw-r--r--

implement swap function for list elements - fixes #218

     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 <assert.h>
    31 #include <string.h>
    32 #include <stdint.h>
    34 // LOW LEVEL ARRAY LIST FUNCTIONS
    36 enum cx_array_copy_result cx_array_copy(
    37         void **target,
    38         size_t *size,
    39         size_t *capacity,
    40         size_t index,
    41         void const *src,
    42         size_t elem_size,
    43         size_t elem_count,
    44         struct cx_array_reallocator_s *reallocator
    45 ) {
    46     // assert pointers
    47     assert(target != NULL);
    48     assert(size != NULL);
    49     assert(src != NULL);
    51     // determine capacity
    52     size_t cap = capacity == NULL ? *size : *capacity;
    54     // check if resize is required
    55     size_t minsize = index + elem_count;
    56     size_t newsize = *size < minsize ? minsize : *size;
    57     bool needrealloc = newsize > cap;
    59     // reallocate if possible
    60     if (needrealloc) {
    61         // a reallocator and a capacity variable must be available
    62         if (reallocator == NULL || capacity == NULL) {
    63             return CX_ARRAY_COPY_REALLOC_NOT_SUPPORTED;
    64         }
    66         // check, if we need to repair the src pointer
    67         uintptr_t targetaddr = (uintptr_t) *target;
    68         uintptr_t srcaddr = (uintptr_t) src;
    69         bool repairsrc = targetaddr <= srcaddr
    70                          && srcaddr < targetaddr + cap * elem_size;
    72         // calculate new capacity (next number divisible by 16)
    73         cap = newsize - (newsize % 16) + 16;
    74         assert(cap > newsize);
    76         // perform reallocation
    77         void *newmem = reallocator->realloc(
    78                 *target, cap, elem_size, reallocator
    79         );
    80         if (newmem == NULL) {
    81             return CX_ARRAY_COPY_REALLOC_FAILED;
    82         }
    84         // repair src pointer, if necessary
    85         if (repairsrc) {
    86             src = ((char *) newmem) + (srcaddr - targetaddr);
    87         }
    89         // store new pointer and capacity
    90         *target = newmem;
    91         *capacity = cap;
    92     }
    94     // determine target pointer
    95     char *start = *target;
    96     start += index * elem_size;
    98     // copy elements and set new size
    99     memmove(start, src, elem_count * elem_size);
   100     *size = newsize;
   102     // return successfully
   103     return CX_ARRAY_COPY_SUCCESS;
   104 }
   106 #ifndef CX_ARRAY_SWAP_SBO_SIZE
   107 #define CX_ARRAY_SWAP_SBO_SIZE 512
   108 #endif
   110 void cx_array_swap(
   111         void *arr,
   112         size_t elem_size,
   113         size_t idx1,
   114         size_t idx2
   115 ) {
   116     // short circuit
   117     if (idx1 == idx2) return;
   119     char sbo_mem[CX_ARRAY_SWAP_SBO_SIZE];
   120     void *tmp;
   122     // decide if we can use the local buffer
   123     if (elem_size > CX_ARRAY_SWAP_SBO_SIZE) {
   124         tmp = malloc(elem_size);
   125         // we don't want to enforce error handling
   126         if (tmp == NULL) abort();
   127     } else {
   128         tmp = sbo_mem;
   129     }
   131     // calculate memory locations
   132     char *left = arr, *right = arr;
   133     left += idx1 * elem_size;
   134     right += idx2 * elem_size;
   136     // three-way swap
   137     memcpy(tmp, left, elem_size);
   138     memcpy(left, right, elem_size);
   139     memcpy(right, tmp, elem_size);
   141     // free dynamic memory, if it was needed
   142     if (tmp != sbo_mem) {
   143         free(tmp);
   144     }
   145 }
   147 // HIGH LEVEL ARRAY LIST FUNCTIONS
   149 typedef struct {
   150     struct cx_list_s base;
   151     void *data;
   152     struct cx_array_reallocator_s reallocator;
   153 } cx_array_list;
   155 static void *cx_arl_realloc(
   156         void *array,
   157         size_t capacity,
   158         size_t elem_size,
   159         struct cx_array_reallocator_s *alloc
   160 ) {
   161     // retrieve the pointer to the list allocator
   162     CxAllocator const *al = alloc->ptr1;
   164     // use the list allocator to reallocate the memory
   165     return cxRealloc(al, array, capacity * elem_size);
   166 }
   168 static void cx_arl_destructor(struct cx_list_s *list) {
   169     cx_array_list *arl = (cx_array_list *) list;
   170     cxFree(list->allocator, arl->data);
   171 }
   173 static size_t cx_arl_insert_array(
   174         struct cx_list_s *list,
   175         size_t index,
   176         void const *array,
   177         size_t n
   178 ) {
   179     // out of bounds and special case check
   180     if (index > list->size || n == 0) return 0;
   182     // get a correctly typed pointer to the list
   183     cx_array_list *arl = (cx_array_list *) list;
   185     // do we need to move some elements?
   186     if (index < list->size) {
   187         char const *first_to_move = (char const *) arl->data;
   188         first_to_move += index * list->itemsize;
   189         size_t elems_to_move = list->size - index;
   190         size_t start_of_moved = index + n;
   192         if (CX_ARRAY_COPY_SUCCESS != cx_array_copy(
   193                 &arl->data,
   194                 &list->size,
   195                 &list->capacity,
   196                 start_of_moved,
   197                 first_to_move,
   198                 list->itemsize,
   199                 elems_to_move,
   200                 &arl->reallocator
   201         )) {
   202             // if moving existing elems is unsuccessful, abort
   203             return 0;
   204         }
   205     }
   207     // note that if we had to move the elements, the following operation
   208     // is guaranteed to succeed, because we have the memory already allocated
   209     // therefore, it is impossible to leave this function with an invalid array
   211     // place the new elements
   212     if (CX_ARRAY_COPY_SUCCESS == cx_array_copy(
   213             &arl->data,
   214             &list->size,
   215             &list->capacity,
   216             index,
   217             array,
   218             list->itemsize,
   219             n,
   220             &arl->reallocator
   221     )) {
   222         return n;
   223     } else {
   224         // array list implementation is "all or nothing"
   225         return 0;
   226     }
   227 }
   229 static int cx_arl_insert_element(
   230         struct cx_list_s *list,
   231         size_t index,
   232         void const *element
   233 ) {
   234     return 1 != cx_arl_insert_array(list, index, element, 1);
   235 }
   237 static int cx_arl_insert_iter(
   238         struct cx_mut_iterator_s *iter,
   239         void const *elem,
   240         int prepend
   241 ) {
   242     struct cx_list_s *list = iter->src_handle;
   243     if (iter->index < list->size) {
   244         int result = cx_arl_insert_element(
   245                 list,
   246                 iter->index + 1 - prepend,
   247                 elem
   248         );
   249         if (result == 0 && prepend != 0) {
   250             iter->index++;
   251             iter->elem_handle = ((char *) iter->elem_handle) + list->itemsize;
   252         }
   253         return result;
   254     } else {
   255         int result = cx_arl_insert_element(list, list->size, elem);
   256         iter->index = list->size;
   257         return result;
   258     }
   259 }
   261 static int cx_arl_remove(
   262         struct cx_list_s *list,
   263         size_t index
   264 ) {
   265     // out-of-bounds check
   266     if (index >= list->size) {
   267         return 1;
   268     }
   270     // short-circuit removal of last element
   271     if (index == list->size - 1) {
   272         list->size--;
   273         return 0;
   274     }
   276     // just move the elements starting at index to the left
   277     cx_array_list *arl = (cx_array_list *) list;
   278     int result = cx_array_copy(
   279             &arl->data,
   280             &list->size,
   281             &list->capacity,
   282             index,
   283             ((char *) arl->data) + (index + 1) * list->itemsize,
   284             list->itemsize,
   285             list->size - index - 1,
   286             &arl->reallocator
   287     );
   288     if (result == 0) {
   289         // decrease the size
   290         list->size--;
   291     }
   292     return result;
   293 }
   295 static int cx_arl_swap(
   296         struct cx_list_s *list,
   297         size_t i,
   298         size_t j
   299 ) {
   300     if (i >= list->size || j >= list->size) return 1;
   301     cx_array_list *arl = (cx_array_list *) list;
   302     cx_array_swap(arl->data, list->itemsize, i, j);
   303     return 0;
   304 }
   306 static void *cx_arl_at(
   307         struct cx_list_s const *list,
   308         size_t index
   309 ) {
   310     if (index < list->size) {
   311         cx_array_list const *arl = (cx_array_list const *) list;
   312         char *space = arl->data;
   313         return space + index * list->itemsize;
   314     } else {
   315         return NULL;
   316     }
   317 }
   319 static size_t cx_arl_find(
   320         struct cx_list_s const *list,
   321         void const *elem
   322 ) {
   323     char *cur = ((cx_array_list const *) list)->data;
   325     for (size_t i = 0; i < list->size; i++) {
   326         if (0 == list->cmpfunc(elem, cur)) {
   327             return i;
   328         }
   329         cur += list->itemsize;
   330     }
   332     return list->size;
   333 }
   335 static void cx_arl_sort(struct cx_list_s *list) {
   336     qsort(((cx_array_list *) list)->data,
   337           list->size,
   338           list->itemsize,
   339           list->cmpfunc
   340     );
   341 }
   343 static int cx_arl_compare(
   344         struct cx_list_s const *list,
   345         struct cx_list_s const *other
   346 ) {
   347     if (list->size == other->size) {
   348         char const *left = ((cx_array_list const *) list)->data;
   349         char const *right = ((cx_array_list const *) other)->data;
   350         for (size_t i = 0; i < list->size; i++) {
   351             int d = list->cmpfunc(left, right);
   352             if (d != 0) {
   353                 return d;
   354             }
   355             left += list->itemsize;
   356             right += other->itemsize;
   357         }
   358         return 0;
   359     } else {
   360         return list->size < other->size ? -1 : 1;
   361     }
   362 }
   364 static void cx_arl_reverse(struct cx_list_s *list) {
   365     if (list->size < 2) return;
   366     void *data = ((cx_array_list const *) list)->data;
   367     size_t half = list->size / 2;
   368     for (size_t i = 0; i < half; i++) {
   369         cx_array_swap(data, list->itemsize, i, list->size - 1 - i);
   370     }
   371 }
   373 static bool cx_arl_iter_valid(void const *it) {
   374     struct cx_iterator_s const *iter = it;
   375     struct cx_list_s const *list = iter->src_handle;
   376     return iter->index < list->size;
   377 }
   379 static void *cx_arl_iter_current(void const *it) {
   380     struct cx_iterator_s const *iter = it;
   381     return iter->elem_handle;
   382 }
   384 static void cx_arl_iter_next(void *it) {
   385     struct cx_iterator_base_s *itbase = it;
   386     if (itbase->remove) {
   387         struct cx_mut_iterator_s *iter = it;
   388         itbase->remove = false;
   389         cx_arl_remove(iter->src_handle, iter->index);
   390     } else {
   391         struct cx_iterator_s *iter = it;
   392         iter->index++;
   393         iter->elem_handle =
   394                 ((char *) iter->elem_handle)
   395                 + ((struct cx_list_s const *) iter->src_handle)->itemsize;
   396     }
   397 }
   399 static bool cx_arl_iter_flag_rm(void *it) {
   400     struct cx_iterator_base_s *iter = it;
   401     if (iter->mutating) {
   402         iter->remove = true;
   403         return true;
   404     } else {
   405         return false;
   406     }
   407 }
   409 static struct cx_iterator_s cx_arl_iterator(
   410         struct cx_list_s const *list,
   411         size_t index
   412 ) {
   413     struct cx_iterator_s iter;
   415     iter.index = index;
   416     iter.src_handle = list;
   417     iter.elem_handle = cx_arl_at(list, index);
   418     iter.base.valid = cx_arl_iter_valid;
   419     iter.base.current = cx_arl_iter_current;
   420     iter.base.next = cx_arl_iter_next;
   421     iter.base.flag_removal = cx_arl_iter_flag_rm;
   422     iter.base.remove = false;
   423     iter.base.mutating = false;
   425     return iter;
   426 }
   428 static cx_list_class cx_array_list_class = {
   429         cx_arl_destructor,
   430         cx_arl_insert_element,
   431         cx_arl_insert_array,
   432         cx_arl_insert_iter,
   433         cx_arl_remove,
   434         cx_arl_swap,
   435         cx_arl_at,
   436         cx_arl_find,
   437         cx_arl_sort,
   438         cx_arl_compare,
   439         cx_arl_reverse,
   440         cx_arl_iterator,
   441 };
   443 CxList *cxArrayListCreate(
   444         CxAllocator const *allocator,
   445         CxListComparator comparator,
   446         size_t item_size,
   447         size_t initial_capacity
   448 ) {
   449     cx_array_list *list = cxCalloc(allocator, 1, sizeof(cx_array_list));
   450     if (list == NULL) return NULL;
   452     list->data = cxCalloc(allocator, initial_capacity, item_size);
   453     if (list->data == NULL) {
   454         cxFree(allocator, list);
   455         return NULL;
   456     }
   458     list->base.cl = &cx_array_list_class;
   459     list->base.allocator = allocator;
   460     list->base.cmpfunc = comparator;
   461     list->base.itemsize = item_size;
   462     list->base.capacity = initial_capacity;
   464     // configure the reallocator
   465     list->reallocator.realloc = cx_arl_realloc;
   466     list->reallocator.ptr1 = (void *) allocator;
   468     return (CxList *) list;
   469 }

mercurial