summaryrefslogtreecommitdiff
path: root/lib/std/strfind.myr
blob: 7a94a4f4b60692b41fb222de007abbdd3b0917a4 (plain)
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
use "types"
use "option"

pkg std =
	const strfind	: (haystack : byte[:], needle : byte[:] -> option(size))
	const strrfind	: (haystack : byte[:], needle : byte[:] -> option(size))
	const strhas	: (haystack : byte[:], needle : byte[:]	-> bool)
;;

const strfind = {haystack, needle
	if needle.len > haystack.len
		-> `std.None
	elif needle.len == 0 && haystack.len == 0
		-> `std.Some 0
	;;
	for var i = 0; i <= haystack.len - needle.len; i++
		for var j = 0; j < needle.len; j++
			if haystack[i + j] != needle[j]
				goto next
			;;
		;;
		-> `std.Some i
:next
	;;
	-> `std.None
}

const strrfind = {haystack, needle
	if needle.len > haystack.len
		-> `std.None
	elif needle.len == 0 && haystack.len == 0
		-> `std.Some 0
	;;
	for var i = haystack.len - haystack.len; i > 0; i --
		for var j = 0; j < needle.len; j++
			if haystack[i + j] != needle[j]
				goto next
			;;
		;;
		-> `std.Some i
:next
	;;
	-> `std.None
}

const strhas = {haystack, needle
	match strfind(haystack, needle)
	| `Some _:	-> true
	| `None:	-> false
	;;
}