File: ensure.ha

package info (click to toggle)
hare 0.26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,352 kB
  • sloc: asm: 1,374; makefile: 123; sh: 117; lisp: 101
file content (49 lines) | stat: -rw-r--r-- 943 bytes parent folder | download | duplicates (4)
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
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

export type slice = struct {
	data: nullable *opaque,
	length: size,
	capacity: size,
};

export fn ensure(s: *slice, membsz: size) bool = {
	let cap = s.capacity;
	if (cap >= s.length) {
		return true;
	};
	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;
	let data = realloc(s.data, s.capacity * membsz);
	if (data == null) {
		if (s.capacity * membsz == 0) {
			s.data = null;
			return true;
		} else {
			return false;
		};
	};
	s.data = data;
	return true;
};

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

	if (data != null || s.capacity * membsz == 0) {
		s.data = data;
	};
};