10 void array_init(Array
*arr
) {
11 array_init_sized(arr
, sizeof(void*));
14 void array_init_sized(Array
*arr
, size_t elem_size
) {
15 memset(arr
, 0, sizeof *arr
);
16 arr
->elem_size
= elem_size
;
19 bool array_reserve(Array
*arr
, size_t count
) {
20 if (count
< ARRAY_SIZE
)
22 if (arr
->count
< count
) {
23 count
= MAX(count
, arr
->count
*2);
24 char *items
= realloc(arr
->items
, count
* arr
->elem_size
);
33 void array_release(Array
*arr
) {
37 array_init_sized(arr
, arr
->elem_size
);
40 void array_release_full(Array
*arr
) {
43 for (size_t i
= 0; i
< arr
->len
; i
++)
44 free(array_get_ptr(arr
, i
));
48 void array_clear(Array
*arr
) {
51 memset(arr
->items
, 0, arr
->count
* arr
->elem_size
);
54 void *array_get(Array
*arr
, size_t idx
) {
55 if (idx
>= arr
->len
) {
59 return arr
->items
+ (idx
* arr
->elem_size
);
62 void *array_get_ptr(Array
*arr
, size_t idx
) {
63 if (arr
->elem_size
!= sizeof(void*)) {
67 void **ptr
= array_get(arr
, idx
);
68 return ptr
? *ptr
: NULL
;
71 bool array_set(Array
*arr
, size_t idx
, void *item
) {
72 if (idx
>= arr
->len
) {
77 memcpy(arr
->items
+ (idx
* arr
->elem_size
), item
, arr
->elem_size
);
79 memset(arr
->items
+ (idx
* arr
->elem_size
), 0, arr
->elem_size
);
83 bool array_set_ptr(Array
*arr
, size_t idx
, void *item
) {
84 if (arr
->elem_size
!= sizeof(void*)) {
88 return array_set(arr
, idx
, &item
);
91 bool array_add(Array
*arr
, void *item
) {
92 if (!array_reserve(arr
, arr
->len
+1))
94 if (!array_set(arr
, arr
->len
++, item
)) {
101 bool array_add_ptr(Array
*arr
, void *item
) {
102 if (!array_reserve(arr
, arr
->len
+1))
104 if (!array_set_ptr(arr
, arr
->len
++, item
)) {
111 bool array_remove(Array
*arr
, size_t idx
) {
112 if (idx
>= arr
->len
) {
116 char *dest
= arr
->items
+ idx
* arr
->elem_size
;
117 char *src
= arr
->items
+ (idx
+ 1) * arr
->elem_size
;
118 memmove(dest
, src
, (arr
->len
- idx
) * arr
->elem_size
);
123 size_t array_length(Array
*arr
) {
127 size_t array_capacity(Array
*arr
) {
131 bool array_truncate(Array
*arr
, size_t len
) {
132 if (len
<= arr
->len
) {
139 bool array_resize(Array
*arr
, size_t len
) {
140 if (len
<= arr
->count
) {
147 void array_sort(Array
*arr
, int (*compar
)(const void*, const void*)) {
148 qsort(arr
->items
, arr
->len
, arr
->elem_size
, compar
);