10 void array_init(Array
*arr
) {
11 array_init_sized(arr
, sizeof(void*));
14 void array_init_from(Array
*arr
, Array
*from
) {
15 array_init_sized(arr
, from
->elem_size
);
18 void array_init_sized(Array
*arr
, size_t elem_size
) {
19 memset(arr
, 0, sizeof *arr
);
20 arr
->elem_size
= elem_size
;
23 bool array_reserve(Array
*arr
, size_t count
) {
24 if (count
< ARRAY_SIZE
)
26 if (arr
->count
< count
) {
27 count
= MAX(count
, arr
->count
*2);
28 char *items
= realloc(arr
->items
, count
* arr
->elem_size
);
37 void array_release(Array
*arr
) {
41 array_init_sized(arr
, arr
->elem_size
);
44 void array_release_full(Array
*arr
) {
47 for (size_t i
= 0; i
< arr
->len
; i
++)
48 free(array_get_ptr(arr
, i
));
52 void array_clear(Array
*arr
) {
55 memset(arr
->items
, 0, arr
->count
* arr
->elem_size
);
58 void *array_get(Array
*arr
, size_t idx
) {
59 if (idx
>= arr
->len
) {
63 return arr
->items
+ (idx
* arr
->elem_size
);
66 void *array_get_ptr(Array
*arr
, size_t idx
) {
67 if (arr
->elem_size
!= sizeof(void*)) {
71 void **ptr
= array_get(arr
, idx
);
72 return ptr
? *ptr
: NULL
;
75 bool array_set(Array
*arr
, size_t idx
, void *item
) {
76 if (idx
>= arr
->len
) {
81 memcpy(arr
->items
+ (idx
* arr
->elem_size
), item
, arr
->elem_size
);
83 memset(arr
->items
+ (idx
* arr
->elem_size
), 0, arr
->elem_size
);
87 bool array_set_ptr(Array
*arr
, size_t idx
, void *item
) {
88 if (arr
->elem_size
!= sizeof(void*)) {
92 return array_set(arr
, idx
, &item
);
95 bool array_add(Array
*arr
, void *item
) {
96 if (!array_reserve(arr
, arr
->len
+1))
98 if (!array_set(arr
, arr
->len
++, item
)) {
105 bool array_add_ptr(Array
*arr
, void *item
) {
106 if (!array_reserve(arr
, arr
->len
+1))
108 if (!array_set_ptr(arr
, arr
->len
++, item
)) {
115 bool array_remove(Array
*arr
, size_t idx
) {
116 if (idx
>= arr
->len
) {
120 char *dest
= arr
->items
+ idx
* arr
->elem_size
;
121 char *src
= arr
->items
+ (idx
+ 1) * arr
->elem_size
;
122 memmove(dest
, src
, (arr
->len
- idx
- 1) * arr
->elem_size
);
127 size_t array_length(Array
*arr
) {
131 size_t array_capacity(Array
*arr
) {
135 bool array_truncate(Array
*arr
, size_t len
) {
136 if (len
<= arr
->len
) {
143 bool array_resize(Array
*arr
, size_t len
) {
144 if (len
<= arr
->count
) {
151 void array_sort(Array
*arr
, int (*compar
)(const void*, const void*)) {
152 qsort(arr
->items
, arr
->len
, arr
->elem_size
, compar
);
155 bool array_push(Array
*arr
, void *item
) {
156 return array_add(arr
, item
);
159 void *array_pop(Array
*arr
) {
160 void *item
= array_peek(arr
);
167 void *array_peek(Array
*arr
) {
170 return array_get(arr
, arr
->len
- 1);