~sircmpwn/hare

hare/strings/dup.ha -rw-r--r-- 897 bytes
5f07cb9aDrew DeVault iobus: improve pool docs 22 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
37
38
39
40
41
42
43
44
45
use bytes;
use rt;
use types;

// Duplicates a string. Aborts on allocation failure.
export fn dup(s: const str) str = {
	const in = &s: *types::string;
	const id = match (in.data) {
	case null =>
		return ""; // Empty string
	case b: *[*]u8 =>
		yield b;
	};
	let buf: *[*]u8 = match (rt::malloc(in.length + 1)) {
	case null =>
		abort("Out of memory");
	case v: *void =>
		yield v;
	};
	bytes::copy(buf[..in.length + 1z], id[..in.length + 1]);
	let out = types::string {
		data = buf,
		length = in.length,
		capacity = in.length,
	};
	return *(&out: *str);
};

// Duplicates every string of a slice in place, returning the same slice with
// new strings.
export fn dupall(s: []str) void = {
	for (let i = 0z; i < len(s); i += 1) {
		s[i] = strings::dup(s[i]);
	};
};

@test fn dup() void = {
	let s = dup("");
	assert(s == "");
	free(s);

	s = dup("hello");
	assert(s == "hello");
	free(s);
};