~emersion/mrsh

ref: 9371d6094e78645f0ec0c85b6cd5b6c8ec9638fc mrsh/array.c -rw-r--r-- 650 bytes
9371d609Drew DeVault Implement times, : builtins 3 years ago
                                                                                
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
#include <assert.h>
#include <mrsh/array.h>
#include <stdlib.h>

#define INITIAL_SIZE 32

ssize_t mrsh_array_add(struct mrsh_array *array, void *value) {
	assert(array->len <= array->cap);

	if (array->len == array->cap) {
		size_t new_cap = 2 * array->cap;
		if (new_cap < INITIAL_SIZE) {
			new_cap = INITIAL_SIZE;
		}
		void *new_data = realloc(array->data, new_cap);
		if (new_data == NULL) {
			return -1;
		}
		array->data = new_data;
		array->cap = new_cap;
	}

	size_t i = array->len;
	array->data[i] = value;
	array->len++;
	return i;
}

void mrsh_array_finish(struct mrsh_array *array) {
	free(array->data);
	array->cap = array->len = 0;
}