~sircmpwn/hare

hare/strings/suffix.ha -rw-r--r-- 1.2 KiB
1c326effDrew DeVault fnmatch: remove export on internal function 19 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
// Returns true if 'in' has the given prefix.
export fn has_prefix(in: str, prefix: str) bool = {
	let a = toutf8(in), b = toutf8(prefix);
	if (len(a) < len(b)) {
		return false;
	};
	for (let i = 0z; i < len(b); i += 1) {
		if (a[i] != b[i]) {
			return false;
		};
	};
	return true;
};

@test fn prefix() void = {
	assert(has_prefix("abcde", "abc"));
	assert(has_prefix("abcde", "abcde"));
	assert(has_prefix("abcde", ""));
	assert(has_prefix("", ""));
	assert(!has_prefix("abcde", "cde"));
	assert(!has_prefix("abcde", "abcdefg"));
	assert(!has_prefix("", "abc"));
};

// Returns true if 'in' has the given prefix.
export fn has_suffix(in: str, suff: str) bool = {
	let a = toutf8(in), b = toutf8(suff);
	if (len(a) < len(b)) {
		return false;
	};
	for (let i = 0z; i < len(b); i += 1) {
		if (a[len(a) - len(b) + i] != b[i]) {
			return false;
		};
	};
	return true;
};

@test fn suffix() void = {
	assert(has_suffix("abcde", "cde"));
	assert(has_suffix("abcde", "abcde"));
	assert(has_suffix("abcde", ""));
	assert(has_suffix("", ""));
	assert(has_suffix("abcde", ""));
	assert(!has_suffix("abcde", "abc"));
	assert(!has_suffix("abcde", "fabcde"));
	assert(!has_suffix("", "abc"));
};