shithub: mc

ref: 5d16f2c900fc1bc0b461878f5c936b969b7bee7d
dir: /lib/std/strfind.myr/

View raw version
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
	-> strfindin(haystack, needle, 0, haystack.len, 1)
}

const strrfind = {haystack, needle
	-> strfindin(haystack, needle, haystack.len - 1, -1, -1)
}

const strfindin = {haystack, needle, start, end, inc
	if haystack.len == 0 && needle.len == 0
		-> `std.Some 0
	;;
	for var i = start; i != end; i += inc
		/* 
		if we knew the direction we could terminate early,
		but we allow the start and end to be passed in.
		*/
		if i + needle.len > haystack.len
			continue
		;;
		for var j = 0; j < needle.len; j++
			if haystack[i + j] != needle[j]
				goto nextiter
			;;
		;;
		-> `Some i
:nextiter
	;;
	-> `None
}

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