~sircmpwn/hare

hare/strings/index.ha -rw-r--r-- 770 bytes
1c326effDrew DeVault fnmatch: remove export on internal function 21 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
use bytes;

// Returns the index of the first occurance of 'needle' in the 'haystack', or
// void if not present. The index returned is the rune-wise index, not the
// byte-wise index.
export fn index(haystack: str, needle: (str | rune)) (size | void) = {
	match (needle) {
	case r: rune =>
		return index_rune(haystack, r);
	case s: str =>
		abort(); // TODO
	};
};

fn index_rune(s: str, r: rune) (size | void) = {
	let iter = iter(s);
	for (let i = 0z; true; i += 1) {
		match (next(&iter)) {
		case n: rune =>
			if (r == n) {
				return i;
			};
		case void =>
			break;
		};
	};
};

@test fn index() void = {
	assert(index("hello world", 'w') as size == 6);
	assert(index("こんにちは", 'ち') as size == 3);
	assert(index("こんにちは", 'q') is void);
};