~sircmpwn/hare

hare/strings/concat.ha -rw-r--r-- 1.3 KiB
1c326effDrew DeVault fnmatch: remove export on internal function 20 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Concatenates two or more strings. The caller must free the return value.
export fn concat(strs: str...) str = {
	let z = 0z;
	for (let i = 0z; i < len(strs); i += 1) {
		z += len(strs[i]);
	};
	let new: []u8 = alloc([], z);
	for (let i = 0z; i < len(strs); i += 1) {
		append(new, toutf8(strs[i])...);
	};
	return fromutf8_unsafe(new[..z]);
};

@test fn concat() void = {
	let s = concat("hello ", "world");
	assert(s == "hello world");
	free(s);

	s = concat("hello", " ", "world");
	assert(s == "hello world");
	free(s);

	s = concat("hello", "", "world");
	assert(s == "helloworld");
	free(s);

	s = concat("", "");
	assert(s == "");
	free(s);

	s = concat();
	assert(s == "");
	free(s);
};

// Joins several strings together by placing a delimiter between them.
export fn join(delim: str, strs: str...) str = {
	let z = 0z;
	for (let i = 0z; i < len(strs); i += 1) {
		z += len(strs[i]);
		if (i + 1 < len(strs)) {
			z += len(delim);
		};
	};
	let new: []u8 = alloc([], z);
	for (let i = 0z; i < len(strs); i += 1) {
		append(new, toutf8(strs[i])...);
		if (i + 1 < len(strs)) {
			append(new, toutf8(delim)...);
		};
	};
	return fromutf8_unsafe(new[..z]);
};

@test fn join() void = {
	let s = join(".", "a", "b", "c");
	assert(s == "a.b.c");
	free(s);

	let s = join("", "a", "b", "c");
	assert(s == "abc");
	free(s);

	let s = join(".");
	assert(s == "");
	free(s);

};