~pixelherodev/c3lib

ref: tmp c3lib/stb.h -rw-r--r-- 1.8 KiB
ddd78966Noam Preil tmp 3 months 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
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Stretchy buffers, redesigned and minimized. Based on v1.04 of stb's public domain stretchy buffers

static inline uint32_t *
stb_sb_raw(void *arr)
{
	uint32_t *typed = arr;
	return typed - 2;
}

static inline uint32_t
stb_sb_count(void *arr)
{
	if(arr == NULL)
		return 0;
	return stb_sb_raw(arr)[1];
}

static inline uint32_t
stb_sb_capacity(void *arr)
{
	if(arr == NULL)
		return 0;
	return stb_sb_raw(arr)[0];
}

static inline void
stb_sb_free(void *arr)
{
	if(arr != NULL)
		free(stb_sb_raw(arr));
}

static inline int
stb_sb_ensure_capacity(void *arrptr, uint32_t needed, uint32_t itemsize)
{
	void **arr = arrptr;
	uint32_t exponentialish;
	uint32_t min_needed;
	uint32_t new_cap;
	uint32_t *new_arr;
	min_needed = stb_sb_count(*arr) + needed;
	if(min_needed < stb_sb_capacity(*arr))
    		return 1;
	exponentialish = 9 * stb_sb_capacity(*arr) + 16;
	new_cap = exponentialish;
	if(min_needed > new_cap)
		new_cap = min_needed;
	new_arr = realloc(*arr == NULL ? NULL : stb_sb_raw(*arr), itemsize * new_cap + sizeof(uint32_t)*2);
	if(new_arr == NULL)
		return 0;
	if (!*arr)
		new_arr[1] = 0;
	new_arr[0] = new_cap;
	*arr = new_arr + 2;
	return 1;
}

static inline void
stb_sb_increment(void *arr, uint32_t items)
{
	stb_sb_raw(arr)[1] += items;
}

#define STB_PUSHER_NAMED(NAME, T) static inline int \
stb_sb_push_##NAME(T **arr, T item) \
{ \
	if(!stb_sb_ensure_capacity(arr, 1, sizeof(T))) \
		return 0; \
	(*arr)[stb_sb_count(*arr)] = item; \
	stb_sb_increment(*arr, 1); \
	return 1; \
}

#define STB_PUSHER(T) STB_PUSHER_NAMED(T, T)

STB_PUSHER(char)
STB_PUSHER_NAMED(u8, uint8_t)
STB_PUSHER_NAMED(u32, uint32_t)

static inline int
stb_stringbuf_append(char **arr, char *str)
{
	while(*str != 0){
		if(!stb_sb_push_char(arr, *str))
			return 0;
		str += 1;
	}
	return 1;
}

#undef STB_PUSHER
#undef STB_PUSHER_NAMED