File: concat.ha

package info (click to toggle)
hare 0.25.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,948 kB
  • sloc: asm: 1,264; makefile: 123; sh: 114; lisp: 101
file content (80 lines) | stat: -rw-r--r-- 1,685 bytes parent folder | download
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
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

// Concatenates multiple strings. The caller must free the return value.
export fn concat(strs: str...) (str | nomem) = {
	let z = 0z;
	for (let s .. strs) {
		z += len(s);
	};

	let new: []u8 = alloc([], z)?;
	for (let s .. strs) {
		static append(new, toutf8(s)...)!;
	};
	return fromutf8_unsafe(new);
};

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

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

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

	let s = concat("", "")!;
	defer free(s);
	assert(s == "");

	let s = concat()!;
	defer free(s);
	assert(s == "");

	let s = concat("hello")!;
	defer free(s);
	assert(s == "hello");
};

// Joins several strings together by placing a delimiter between them. The
// caller must free the return value.
export fn join(delim: str, strs: str...) (str | nomem) = {
	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) {
		static append(new, toutf8(strs[i])...)!;
		if (i + 1 < len(strs)) {
			static append(new, toutf8(delim)...)!;
		};
	};
	return fromutf8_unsafe(new);
};

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

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

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

	let s = join(".", "a")!;
	defer free(s);
	assert(s == "a");
};