summaryrefslogtreecommitdiff
path: root/src/util/util.c
blob: 05701c6257073784d271ba54332b9ed214e2f6bb (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <kalmia.h>
#include <stdint.h>
#include <stdio.h>


void *kai_expand_array(void **array, size_t *count, size_t element_size)
{
	size_t new_count = *count + 1;
	size_t new_size = element_size * new_count;
	/* cast to uint8_t so we can do pointer arithmetic */
	uint8_t *new_array = realloc(*array, new_size);
	if (new_array == NULL) {
		fprintf(stderr, "[kalmia] ERROR: failed to add %ul bytes to %ul-byte array!\n", 
			element_size, element_size * *count);
		return NULL;
	}

	void *new_element = new_array + (*count * element_size);

	*array = new_array;
	*count = new_count;
	return new_element;
}


size_t kai_text_to_reals(ka_real_t *dest, const char *str, size_t count)
{
	char *nptr = (char*) str;
	char *end;

	size_t result = count;

	for (int i=0; i<count; i++) {
		dest[i] = KA_STR_TO_REAL(nptr, &end);
		if (nptr == end) {
			result -= 1;
		}
		nptr = end;
	}

	return result;
}


size_t kai_text_to_longs(long *dest, const char *str, size_t count)
{
	char *nptr = (char*) str;
	char *end;

	size_t result = count;

	for (int i=0; i<count; i++) {
		dest[i] = strtol(nptr, &end, 10);
		if (nptr == end) {
			result -= 1;
		}
		nptr = end;
	}

	return result;
}