~sircmpwn/hare

hare/rt/ensure.ha -rw-r--r-- 767 bytes
ea90e6dfEyal Sawady unix::umask: don't return an error 10 hours 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
export type slice = struct {
	data: nullable *void,
	length: size,
	capacity: size,
};

export fn ensure(s: *slice, membsz: size) void = {
	let cap = s.capacity;
	if (cap >= s.length) {
		return;
	};
	for (cap < s.length) {
		assert(cap >= s.capacity, "slice out of memory (overflow)");
		if (cap == 0) {
			cap = s.length;
		} else {
			cap *= 2;
		};
	};
	s.capacity = cap;
	const data = realloc(s.data, s.capacity * membsz);
	assert(data != null || s.capacity * membsz == 0);
	s.data = data;
};

export fn unensure(s: *slice, membsz: size) void = {
	let cap = s.capacity;
	for (cap > s.length) {
		cap /= 2;
	};
	cap *= 2;
	s.capacity = cap;
	const data = realloc(s.data, s.capacity * membsz);
	assert(data != null || s.capacity * membsz == 0);
	s.data = data;
};