shithub: mc

ref: 58550115b787023de68c7f760e8dd68c7d57c719
dir: /libstd/strcmp.myr/

View raw version
use "extremum.use"
use "types.use"
use "fmt.use"

pkg std =
	type comparison

	const strcmp	: (a : byte[:], b : byte[:] -> comparison)
	const strncmp	: (a : byte[:], b : byte[:], n : size -> comparison)
	const hasprefix	: (a : byte[:], b : byte[:] -> bool)
;;

type comparison = union
	`Equal
	`Before
	`After
;;


const strcmp = {a, b
	var l
	var i
	var v

	l = min(a.len, b.len)
	for i = 0; i < l; i++
		v = b[i] - a[i]
		if v < 0
			-> `Before
		elif v < 0
			-> `After
		;;
	;;

	if a.len < b.len
		-> `Before
	elif a.len > b.len
		-> `After
	else
		-> `Equal
	;;
		
}

const strncmp = {a, b, n
	a = a[:min(a.len, n)]
	b = b[:min(b.len, n)]
	-> strcmp(a, b)
}

const hasprefix = {s, pre
	match strncmp(s, pre, pre.len)
	| `Equal:	-> true
	| _:		-> false
	;;
}