src/array_list.c

Wed, 25 Jan 2023 19:19:29 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 25 Jan 2023 19:19:29 +0100
changeset 640
55cc3b373c5e
parent 638
eafb45eefc51
child 641
d402fead3386
permissions
-rw-r--r--

simplify list class - fixes #236

     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 #define CX_ARRAY_SWAP_SBO_SIZE 512
   108 void cx_array_swap(
   109         void *arr,
   110         size_t elem_size,
   111         size_t idx1,
   112         size_t idx2
   113 ) {
   114     // short circuit
   115     if (idx1 == idx2) return;
   117     char sbo_mem[CX_ARRAY_SWAP_SBO_SIZE];
   118     void *tmp;
   120     // decide if we can use the local buffer
   121     if (elem_size > CX_ARRAY_SWAP_SBO_SIZE) {
   122         tmp = malloc(elem_size);
   123         // we don't want to enforce error handling
   124         if (tmp == NULL) abort();
   125     } else {
   126         tmp = sbo_mem;
   127     }
   129     // calculate memory locations
   130     char *left = arr, *right = arr;
   131     left += idx1 * elem_size;
   132     right += idx2 * elem_size;
   134     // three-way swap
   135     memcpy(tmp, left, elem_size);
   136     memcpy(left, right, elem_size);
   137     memcpy(right, tmp, elem_size);
   139     // free dynamic memory, if it was needed
   140     if (tmp != sbo_mem) {
   141         free(tmp);
   142     }
   143 }
   145 // HIGH LEVEL ARRAY LIST FUNCTIONS
   147 typedef struct {
   148     struct cx_list_s base;
   149     void *data;
   150     struct cx_array_reallocator_s reallocator;
   151 } cx_array_list;
   153 static void *cx_arl_realloc(
   154         void *array,
   155         size_t capacity,
   156         size_t elem_size,
   157         struct cx_array_reallocator_s *alloc
   158 ) {
   159     // retrieve the pointer to the list allocator
   160     CxAllocator const *al = alloc->ptr1;
   162     // use the list allocator to reallocate the memory
   163     return cxRealloc(al, array, capacity * elem_size);
   164 }
   166 static void cx_arl_destructor(struct cx_list_s *list) {
   167     cx_array_list *arl = (cx_array_list *) list;
   168     cxFree(list->allocator, arl->data);
   169 }
   171 static size_t cx_arl_insert_array(
   172         struct cx_list_s *list,
   173         size_t index,
   174         void const *array,
   175         size_t n
   176 ) {
   177     // out of bounds and special case check
   178     if (index > list->size || n == 0) return 0;
   180     // get a correctly typed pointer to the list
   181     cx_array_list *arl = (cx_array_list *) list;
   183     // do we need to move some elements?
   184     if (index < list->size) {
   185         char const *first_to_move = (char const *) arl->data;
   186         first_to_move += index * list->itemsize;
   187         size_t elems_to_move = list->size - index;
   188         size_t start_of_moved = index + n;
   190         if (CX_ARRAY_COPY_SUCCESS != cx_array_copy(
   191                 &arl->data,
   192                 &list->size,
   193                 &list->capacity,
   194                 start_of_moved,
   195                 first_to_move,
   196                 list->itemsize,
   197                 elems_to_move,
   198                 &arl->reallocator
   199         )) {
   200             // if moving existing elems is unsuccessful, abort
   201             return 0;
   202         }
   203     }
   205     // note that if we had to move the elements, the following operation
   206     // is guaranteed to succeed, because we have the memory already allocated
   207     // therefore, it is impossible to leave this function with an invalid array
   209     // place the new elements
   210     if (CX_ARRAY_COPY_SUCCESS == cx_array_copy(
   211             &arl->data,
   212             &list->size,
   213             &list->capacity,
   214             index,
   215             array,
   216             list->itemsize,
   217             n,
   218             &arl->reallocator
   219     )) {
   220         return n;
   221     } else {
   222         // array list implementation is "all or nothing"
   223         return 0;
   224     }
   225 }
   227 static int cx_arl_insert_iter(
   228         struct cx_mut_iterator_s *iter,
   229         void const *elem,
   230         int prepend
   231 ) {
   232     struct cx_list_s *list = iter->src_handle;
   233     if (iter->index < list->size) {
   234         int result = 1 != cx_arl_insert_array(
   235                 list,
   236                 iter->index + 1 - prepend,
   237                 elem,
   238                 1
   239         );
   240         if (result == 0 && prepend != 0) {
   241             iter->index++;
   242             iter->elem_handle = ((char *) iter->elem_handle) + list->itemsize;
   243         }
   244         return result;
   245     } else {
   246         int result = 1 != cx_arl_insert_array(list, list->size, elem, 1);
   247         iter->index = list->size;
   248         return result;
   249     }
   250 }
   252 static int cx_arl_remove(
   253         struct cx_list_s *list,
   254         size_t index
   255 ) {
   256     // out-of-bounds check
   257     if (index >= list->size) {
   258         return 1;
   259     }
   261     // short-circuit removal of last element
   262     if (index == list->size - 1) {
   263         list->size--;
   264         return 0;
   265     }
   267     // just move the elements starting at index to the left
   268     cx_array_list *arl = (cx_array_list *) list;
   269     int result = cx_array_copy(
   270             &arl->data,
   271             &list->size,
   272             &list->capacity,
   273             index,
   274             ((char *) arl->data) + (index + 1) * list->itemsize,
   275             list->itemsize,
   276             list->size - index - 1,
   277             &arl->reallocator
   278     );
   279     if (result == 0) {
   280         // decrease the size
   281         list->size--;
   282     }
   283     return result;
   284 }
   286 static void *cx_arl_at(
   287         struct cx_list_s const *list,
   288         size_t index
   289 ) {
   290     if (index < list->size) {
   291         cx_array_list const *arl = (cx_array_list const *) list;
   292         char *space = arl->data;
   293         return space + index * list->itemsize;
   294     } else {
   295         return NULL;
   296     }
   297 }
   299 static size_t cx_arl_find(
   300         struct cx_list_s const *list,
   301         void const *elem
   302 ) {
   303     char *cur = ((cx_array_list const *) list)->data;
   305     for (size_t i = 0; i < list->size; i++) {
   306         if (0 == list->cmpfunc(elem, cur)) {
   307             return i;
   308         }
   309         cur += list->itemsize;
   310     }
   312     return list->size;
   313 }
   315 static void cx_arl_sort(struct cx_list_s *list) {
   316     qsort(((cx_array_list *) list)->data,
   317           list->size,
   318           list->itemsize,
   319           list->cmpfunc
   320     );
   321 }
   323 static int cx_arl_compare(
   324         struct cx_list_s const *list,
   325         struct cx_list_s const *other
   326 ) {
   327     if (list->size == other->size) {
   328         char const *left = ((cx_array_list const *) list)->data;
   329         char const *right = ((cx_array_list const *) other)->data;
   330         for (size_t i = 0; i < list->size; i++) {
   331             int d = list->cmpfunc(left, right);
   332             if (d != 0) {
   333                 return d;
   334             }
   335             left += list->itemsize;
   336             right += other->itemsize;
   337         }
   338         return 0;
   339     } else {
   340         return list->size < other->size ? -1 : 1;
   341     }
   342 }
   344 static void cx_arl_reverse(struct cx_list_s *list) {
   345     if (list->size < 2) return;
   346     void *data = ((cx_array_list const *) list)->data;
   347     size_t half = list->size / 2;
   348     for (size_t i = 0; i < half; i++) {
   349         cx_array_swap(data, list->itemsize, i, list->size - 1 - i);
   350     }
   351 }
   353 static bool cx_arl_iter_valid(void const *it) {
   354     struct cx_iterator_s const *iter = it;
   355     struct cx_list_s const *list = iter->src_handle;
   356     return iter->index < list->size;
   357 }
   359 static void *cx_arl_iter_current(void const *it) {
   360     struct cx_iterator_s const *iter = it;
   361     return iter->elem_handle;
   362 }
   364 static void cx_arl_iter_next(void *it) {
   365     struct cx_iterator_base_s *itbase = it;
   366     if (itbase->remove) {
   367         struct cx_mut_iterator_s *iter = it;
   368         itbase->remove = false;
   369         cx_arl_remove(iter->src_handle, iter->index);
   370     } else {
   371         struct cx_iterator_s *iter = it;
   372         iter->index++;
   373         iter->elem_handle =
   374                 ((char *) iter->elem_handle)
   375                 + ((struct cx_list_s const *) iter->src_handle)->itemsize;
   376     }
   377 }
   379 static bool cx_arl_iter_flag_rm(void *it) {
   380     struct cx_iterator_base_s *iter = it;
   381     if (iter->mutating) {
   382         iter->remove = true;
   383         return true;
   384     } else {
   385         return false;
   386     }
   387 }
   389 static struct cx_iterator_s cx_arl_iterator(
   390         struct cx_list_s const *list,
   391         size_t index
   392 ) {
   393     struct cx_iterator_s iter;
   395     iter.index = index;
   396     iter.src_handle = list;
   397     iter.elem_handle = cx_arl_at(list, index);
   398     iter.base.valid = cx_arl_iter_valid;
   399     iter.base.current = cx_arl_iter_current;
   400     iter.base.next = cx_arl_iter_next;
   401     iter.base.flag_removal = cx_arl_iter_flag_rm;
   402     iter.base.remove = false;
   403     iter.base.mutating = false;
   405     return iter;
   406 }
   408 static cx_list_class cx_array_list_class = {
   409         cx_arl_destructor,
   410         cx_arl_insert_array,
   411         cx_arl_insert_iter,
   412         cx_arl_remove,
   413         cx_arl_at,
   414         cx_arl_find,
   415         cx_arl_sort,
   416         cx_arl_compare,
   417         cx_arl_reverse,
   418         cx_arl_iterator,
   419 };
   421 CxList *cxArrayListCreate(
   422         CxAllocator const *allocator,
   423         CxListComparator comparator,
   424         size_t item_size,
   425         size_t initial_capacity
   426 ) {
   427     cx_array_list *list = cxCalloc(allocator, 1, sizeof(cx_array_list));
   428     if (list == NULL) return NULL;
   430     list->data = cxCalloc(allocator, initial_capacity, item_size);
   431     if (list->data == NULL) {
   432         cxFree(allocator, list);
   433         return NULL;
   434     }
   436     list->base.cl = &cx_array_list_class;
   437     list->base.allocator = allocator;
   438     list->base.cmpfunc = comparator;
   439     list->base.itemsize = item_size;
   440     list->base.capacity = initial_capacity;
   442     // configure the reallocator
   443     list->reallocator.realloc = cx_arl_realloc;
   444     list->reallocator.ptr1 = (void *) allocator;
   446     return (CxList *) list;
   447 }

mercurial