Wayland compositor (wlroots)
git clone https://git.lucas.co/cce-compositor.git
scenefx/util/array.c (943B)
1 #include "util/array.h"
2 #include <assert.h>
3 #include <string.h>
4
5 void array_remove_at(struct wl_array *arr, size_t offset, size_t size) {
6 assert(arr->size >= offset + size);
7
8 char *data = arr->data;
9 memmove(&data[offset], &data[offset + size], arr->size - offset - size);
10 arr->size -= size;
11 }
12
13 bool array_realloc(struct wl_array *arr, size_t size) {
14 // If the size is less than 1/4th of the allocation size, we shrink it.
15 // 1/4th is picked to provide hysteresis, without which an array with size
16 // arr->alloc would constantly reallocate if an element is added and then
17 // removed continuously.
18 size_t alloc;
19 if (arr->alloc > 0 && size > arr->alloc / 4) {
20 alloc = arr->alloc;
21 } else {
22 alloc = 16;
23 }
24
25 while (alloc < size) {
26 alloc *= 2;
27 }
28
29 if (alloc == arr->alloc) {
30 return true;
31 }
32
33 void *data = realloc(arr->data, alloc);
34 if (data == NULL) {
35 return false;
36 }
37 arr->data = data;
38 arr->alloc = alloc;
39 return true;
40 }