Fri, 05 May 2023 19:07:56 +0200
fix cx_linked_list_sort() not working for empty lists
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>
33 // LOW LEVEL ARRAY LIST FUNCTIONS
35 enum cx_array_copy_result cx_array_copy(
36 void **target,
37 size_t *size,
38 size_t *capacity,
39 size_t index,
40 void const *src,
41 size_t elem_size,
42 size_t elem_count,
43 struct cx_array_reallocator_s *reallocator
44 ) {
45 // assert pointers
46 assert(target != NULL);
47 assert(size != NULL);
48 assert(src != NULL);
50 // determine capacity
51 size_t cap = capacity == NULL ? *size : *capacity;
53 // check if resize is required
54 size_t minsize = index + elem_count;
55 size_t newsize = *size < minsize ? minsize : *size;
56 bool needrealloc = newsize > cap;
58 // reallocate if possible
59 if (needrealloc) {
60 // a reallocator and a capacity variable must be available
61 if (reallocator == NULL || capacity == NULL) {
62 return CX_ARRAY_COPY_REALLOC_NOT_SUPPORTED;
63 }
65 // check, if we need to repair the src pointer
66 uintptr_t targetaddr = (uintptr_t) *target;
67 uintptr_t srcaddr = (uintptr_t) src;
68 bool repairsrc = targetaddr <= srcaddr
69 && srcaddr < targetaddr + cap * elem_size;
71 // calculate new capacity (next number divisible by 16)
72 cap = newsize - (newsize % 16) + 16;
73 assert(cap > newsize);
75 // perform reallocation
76 void *newmem = reallocator->realloc(
77 *target, cap, elem_size, reallocator
78 );
79 if (newmem == NULL) {
80 return CX_ARRAY_COPY_REALLOC_FAILED;
81 }
83 // repair src pointer, if necessary
84 if (repairsrc) {
85 src = ((char *) newmem) + (srcaddr - targetaddr);
86 }
88 // store new pointer and capacity
89 *target = newmem;
90 *capacity = cap;
91 }
93 // determine target pointer
94 char *start = *target;
95 start += index * elem_size;
97 // copy elements and set new size
98 memmove(start, src, elem_count * elem_size);
99 *size = newsize;
101 // return successfully
102 return CX_ARRAY_COPY_SUCCESS;
103 }
105 #ifndef CX_ARRAY_SWAP_SBO_SIZE
106 #define CX_ARRAY_SWAP_SBO_SIZE 512
107 #endif
109 void cx_array_swap(
110 void *arr,
111 size_t elem_size,
112 size_t idx1,
113 size_t idx2
114 ) {
115 assert(arr != NULL);
117 // short circuit
118 if (idx1 == idx2) return;
120 char sbo_mem[CX_ARRAY_SWAP_SBO_SIZE];
121 void *tmp;
123 // decide if we can use the local buffer
124 if (elem_size > CX_ARRAY_SWAP_SBO_SIZE) {
125 tmp = malloc(elem_size);
126 // we don't want to enforce error handling
127 if (tmp == NULL) abort();
128 } else {
129 tmp = sbo_mem;
130 }
132 // calculate memory locations
133 char *left = arr, *right = arr;
134 left += idx1 * elem_size;
135 right += idx2 * elem_size;
137 // three-way swap
138 memcpy(tmp, left, elem_size);
139 memcpy(left, right, elem_size);
140 memcpy(right, tmp, elem_size);
142 // free dynamic memory, if it was needed
143 if (tmp != sbo_mem) {
144 free(tmp);
145 }
146 }
148 // HIGH LEVEL ARRAY LIST FUNCTIONS
150 typedef struct {
151 struct cx_list_s base;
152 void *data;
153 size_t capacity;
154 struct cx_array_reallocator_s reallocator;
155 } cx_array_list;
157 static void *cx_arl_realloc(
158 void *array,
159 size_t capacity,
160 size_t elem_size,
161 struct cx_array_reallocator_s *alloc
162 ) {
163 // retrieve the pointer to the list allocator
164 CxAllocator const *al = alloc->ptr1;
166 // use the list allocator to reallocate the memory
167 return cxRealloc(al, array, capacity * elem_size);
168 }
170 static void cx_arl_destructor(struct cx_list_s *list) {
171 cx_array_list *arl = (cx_array_list *) list;
172 cxFree(list->allocator, arl->data);
173 }
175 static size_t cx_arl_insert_array(
176 struct cx_list_s *list,
177 size_t index,
178 void const *array,
179 size_t n
180 ) {
181 // out of bounds and special case check
182 if (index > list->size || n == 0) return 0;
184 // get a correctly typed pointer to the list
185 cx_array_list *arl = (cx_array_list *) list;
187 // do we need to move some elements?
188 if (index < list->size) {
189 char const *first_to_move = (char const *) arl->data;
190 first_to_move += index * list->item_size;
191 size_t elems_to_move = list->size - index;
192 size_t start_of_moved = index + n;
194 if (CX_ARRAY_COPY_SUCCESS != cx_array_copy(
195 &arl->data,
196 &list->size,
197 &arl->capacity,
198 start_of_moved,
199 first_to_move,
200 list->item_size,
201 elems_to_move,
202 &arl->reallocator
203 )) {
204 // if moving existing elems is unsuccessful, abort
205 return 0;
206 }
207 }
209 // note that if we had to move the elements, the following operation
210 // is guaranteed to succeed, because we have the memory already allocated
211 // therefore, it is impossible to leave this function with an invalid array
213 // place the new elements
214 if (CX_ARRAY_COPY_SUCCESS == cx_array_copy(
215 &arl->data,
216 &list->size,
217 &arl->capacity,
218 index,
219 array,
220 list->item_size,
221 n,
222 &arl->reallocator
223 )) {
224 return n;
225 } else {
226 // array list implementation is "all or nothing"
227 return 0;
228 }
229 }
231 static int cx_arl_insert_element(
232 struct cx_list_s *list,
233 size_t index,
234 void const *element
235 ) {
236 return 1 != cx_arl_insert_array(list, index, element, 1);
237 }
239 static int cx_arl_insert_iter(
240 struct cx_mut_iterator_s *iter,
241 void const *elem,
242 int prepend
243 ) {
244 struct cx_list_s *list = iter->src_handle;
245 if (iter->index < list->size) {
246 int result = cx_arl_insert_element(
247 list,
248 iter->index + 1 - prepend,
249 elem
250 );
251 if (result == 0 && prepend != 0) {
252 iter->index++;
253 iter->elem_handle = ((char *) iter->elem_handle) + list->item_size;
254 }
255 return result;
256 } else {
257 int result = cx_arl_insert_element(list, list->size, elem);
258 iter->index = list->size;
259 return result;
260 }
261 }
263 static int cx_arl_remove(
264 struct cx_list_s *list,
265 size_t index
266 ) {
267 cx_array_list *arl = (cx_array_list *) list;
269 // out-of-bounds check
270 if (index >= list->size) {
271 return 1;
272 }
274 // content destruction
275 cx_invoke_destructor(list, ((char *) arl->data) + index * list->item_size);
277 // short-circuit removal of last element
278 if (index == list->size - 1) {
279 list->size--;
280 return 0;
281 }
283 // just move the elements starting at index to the left
284 int result = cx_array_copy(
285 &arl->data,
286 &list->size,
287 &arl->capacity,
288 index,
289 ((char *) arl->data) + (index + 1) * list->item_size,
290 list->item_size,
291 list->size - index - 1,
292 &arl->reallocator
293 );
294 if (result == 0) {
295 // decrease the size
296 list->size--;
297 }
298 return result;
299 }
301 static void cx_arl_clear(struct cx_list_s *list) {
302 if (list->size == 0) return;
304 cx_array_list *arl = (cx_array_list *) list;
305 char *ptr = arl->data;
307 if (list->simple_destructor) {
308 for (size_t i = 0; i < list->size; i++) {
309 cx_invoke_simple_destructor(list, ptr);
310 ptr += list->item_size;
311 }
312 }
313 if (list->advanced_destructor) {
314 for (size_t i = 0; i < list->size; i++) {
315 cx_invoke_advanced_destructor(list, ptr);
316 ptr += list->item_size;
317 }
318 }
320 memset(arl->data, 0, list->size * list->item_size);
321 list->size = 0;
322 }
324 static int cx_arl_swap(
325 struct cx_list_s *list,
326 size_t i,
327 size_t j
328 ) {
329 if (i >= list->size || j >= list->size) return 1;
330 cx_array_list *arl = (cx_array_list *) list;
331 cx_array_swap(arl->data, list->item_size, i, j);
332 return 0;
333 }
335 static void *cx_arl_at(
336 struct cx_list_s const *list,
337 size_t index
338 ) {
339 if (index < list->size) {
340 cx_array_list const *arl = (cx_array_list const *) list;
341 char *space = arl->data;
342 return space + index * list->item_size;
343 } else {
344 return NULL;
345 }
346 }
348 static ssize_t cx_arl_find(
349 struct cx_list_s const *list,
350 void const *elem
351 ) {
352 assert(list->cmpfunc != NULL);
353 assert(list->size < SIZE_MAX / 2);
354 char *cur = ((cx_array_list const *) list)->data;
356 for (ssize_t i = 0; i < (ssize_t) list->size; i++) {
357 if (0 == list->cmpfunc(elem, cur)) {
358 return i;
359 }
360 cur += list->item_size;
361 }
363 return -1;
364 }
366 static void cx_arl_sort(struct cx_list_s *list) {
367 assert(list->cmpfunc != NULL);
368 qsort(((cx_array_list *) list)->data,
369 list->size,
370 list->item_size,
371 list->cmpfunc
372 );
373 }
375 static int cx_arl_compare(
376 struct cx_list_s const *list,
377 struct cx_list_s const *other
378 ) {
379 assert(list->cmpfunc != NULL);
380 if (list->size == other->size) {
381 char const *left = ((cx_array_list const *) list)->data;
382 char const *right = ((cx_array_list const *) other)->data;
383 for (size_t i = 0; i < list->size; i++) {
384 int d = list->cmpfunc(left, right);
385 if (d != 0) {
386 return d;
387 }
388 left += list->item_size;
389 right += other->item_size;
390 }
391 return 0;
392 } else {
393 return list->size < other->size ? -1 : 1;
394 }
395 }
397 static void cx_arl_reverse(struct cx_list_s *list) {
398 if (list->size < 2) return;
399 void *data = ((cx_array_list const *) list)->data;
400 size_t half = list->size / 2;
401 for (size_t i = 0; i < half; i++) {
402 cx_array_swap(data, list->item_size, i, list->size - 1 - i);
403 }
404 }
406 static bool cx_arl_iter_valid(void const *it) {
407 struct cx_iterator_s const *iter = it;
408 struct cx_list_s const *list = iter->src_handle;
409 return iter->index < list->size;
410 }
412 static void *cx_arl_iter_current(void const *it) {
413 struct cx_iterator_s const *iter = it;
414 return iter->elem_handle;
415 }
417 static void cx_arl_iter_next(void *it) {
418 struct cx_iterator_base_s *itbase = it;
419 if (itbase->remove) {
420 struct cx_mut_iterator_s *iter = it;
421 itbase->remove = false;
422 cx_arl_remove(iter->src_handle, iter->index);
423 } else {
424 struct cx_iterator_s *iter = it;
425 iter->index++;
426 iter->elem_handle =
427 ((char *) iter->elem_handle)
428 + ((struct cx_list_s const *) iter->src_handle)->item_size;
429 }
430 }
432 static void cx_arl_iter_prev(void *it) {
433 struct cx_iterator_base_s *itbase = it;
434 struct cx_mut_iterator_s *iter = it;
435 cx_array_list *const list = iter->src_handle;
436 if (itbase->remove) {
437 itbase->remove = false;
438 cx_arl_remove(iter->src_handle, iter->index);
439 }
440 iter->index--;
441 if (iter->index < list->base.size) {
442 iter->elem_handle = ((char *) list->data)
443 + iter->index * list->base.item_size;
444 }
445 }
447 static bool cx_arl_iter_flag_rm(void *it) {
448 struct cx_iterator_base_s *iter = it;
449 if (iter->mutating) {
450 iter->remove = true;
451 return true;
452 } else {
453 return false;
454 }
455 }
457 static struct cx_iterator_s cx_arl_iterator(
458 struct cx_list_s const *list,
459 size_t index,
460 bool backwards
461 ) {
462 struct cx_iterator_s iter;
464 iter.index = index;
465 iter.src_handle = list;
466 iter.elem_handle = cx_arl_at(list, index);
467 iter.base.valid = cx_arl_iter_valid;
468 iter.base.current = cx_arl_iter_current;
469 iter.base.next = backwards ? cx_arl_iter_prev : cx_arl_iter_next;
470 iter.base.flag_removal = cx_arl_iter_flag_rm;
471 iter.base.remove = false;
472 iter.base.mutating = false;
474 return iter;
475 }
477 static cx_list_class cx_array_list_class = {
478 cx_arl_destructor,
479 cx_arl_insert_element,
480 cx_arl_insert_array,
481 cx_arl_insert_iter,
482 cx_arl_remove,
483 cx_arl_clear,
484 cx_arl_swap,
485 cx_arl_at,
486 cx_arl_find,
487 cx_arl_sort,
488 cx_arl_compare,
489 cx_arl_reverse,
490 cx_arl_iterator,
491 };
493 CxList *cxArrayListCreate(
494 CxAllocator const *allocator,
495 cx_compare_func comparator,
496 size_t item_size,
497 size_t initial_capacity
498 ) {
499 if (allocator == NULL) {
500 allocator = cxDefaultAllocator;
501 }
503 cx_array_list *list = cxCalloc(allocator, 1, sizeof(cx_array_list));
504 if (list == NULL) return NULL;
506 list->base.cl = &cx_array_list_class;
507 list->base.allocator = allocator;
508 list->base.cmpfunc = comparator;
509 list->capacity = initial_capacity;
511 if (item_size > 0) {
512 list->base.item_size = item_size;
513 } else {
514 item_size = sizeof(void *);
515 cxListStorePointers((CxList *) list);
516 }
518 // allocate the array after the real item_size is known
519 list->data = cxCalloc(allocator, initial_capacity, item_size);
520 if (list->data == NULL) {
521 cxFree(allocator, list);
522 return NULL;
523 }
525 // configure the reallocator
526 list->reallocator.realloc = cx_arl_realloc;
527 list->reallocator.ptr1 = (void *) allocator;
529 return (CxList *) list;
530 }