MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
arr.c
1#include "arr/arr.h"
2
3#include <string.h>
4
5/* `data_field` is the address of the array's `T *data`. Copying the pointer
6 * through memcpy reads and writes it without aliasing it as a `void *`. */
7bool arr_reserve_(void *data_field, size_t *capacity, size_t len, size_t add,
8 size_t elem, const Allocator *alloc) {
9 size_t needed;
10 if (ckd_add(&needed, len, add)) return false;
11 if (needed <= *capacity) return true;
12
13 size_t cap = *capacity != 0 ? *capacity : 8;
14 while (cap < needed) {
15 if (ckd_mul(&cap, cap, 2)) {
16 cap = needed;
17 break;
18 }
19 }
20 size_t bytes;
21 if (ckd_mul(&bytes, cap, elem)) return false;
22
23 void *old;
24 memcpy(&old, data_field, sizeof old);
25 void *p = mem_realloc(alloc, old, *capacity * elem, bytes);
26 if (p == NULL) return false;
27 memcpy(data_field, &p, sizeof p);
28 *capacity = cap;
29 return true;
30}
31
32void arr_free_(void *data_field, size_t bytes, const Allocator *alloc) {
33 void *p;
34 memcpy(&p, data_field, sizeof p);
35 if (p != NULL) p = mem_realloc(alloc, p, bytes, 0);
36 memcpy(data_field, &p, sizeof p);
37}
void * mem_realloc(const Allocator *a, void *old, size_t old_size, size_t new_size)
Resize old from old_size to new_size bytes through a.
Definition mem.c:14
Where a module gets its memory.
Definition mem.h:56