-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.c
40 lines (36 loc) · 1.27 KB
/
array.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#define ARRAY_RAW_DATA(array) ((int*)(array) - 2)
#define ARRAY_CAPACITY(array) (ARRAY_RAW_DATA(array)[0])
#define ARRAY_OCCUPIED(array) (ARRAY_RAW_DATA(array)[1])
void* array_hold(void* array, int count, int item_size) {
if (array == NULL) {
int raw_size = (sizeof(int) * 2) + (item_size * count);
int* base = (int*)malloc(raw_size);
base[0] = count; // capacity
base[1] = count; // occupied
return base + 2;
} else if (ARRAY_OCCUPIED(array) + count <= ARRAY_CAPACITY(array)) {
ARRAY_OCCUPIED(array) += count;
return array;
} else {
int needed_size = ARRAY_OCCUPIED(array) + count;
int double_curr = ARRAY_CAPACITY(array) * 2;
int capacity = needed_size > double_curr ? needed_size : double_curr;
int occupied = needed_size;
int raw_size = sizeof(int) * 2 + item_size * capacity;
int* base = (int*)realloc(ARRAY_RAW_DATA(array), raw_size);
base[0] = capacity;
base[1] = occupied;
return base + 2;
}
}
int array_length(void* array) {
return (array != NULL) ? ARRAY_OCCUPIED(array) : 0;
}
void array_free(void* array) {
if (array != NULL) {
free(ARRAY_RAW_DATA(array));
}
}