shithub: mc

ref: 74d91a0021de012908cfdb35fb61a1473a376130
dir: /lib/std/cmp.myr/

View raw version
use "extremum"
use "types"
use "utf"
use "chartype"

pkg std =
	type order = union
		`Before
		`Equal
		`After
	;;

	generic numcmp		: (a : @a, b : @a -> order) :: numeric @a
	const strcmp		: (a : byte[:], b : byte[:] -> order)
	const strncmp		: (a : byte[:], b : byte[:], n : size -> order)
	const strcasecmp	: (a : byte[:], b : byte[:] -> order)
;;

extern const put : (str : byte[:], args : ... -> int64)

generic numcmp = {a, b
	if a < b
		-> `Before
	elif a == b
		-> `Equal
	else
		-> `After
	;;
}

const strcmp = {a, b
	var l

	l = min(a.len, b.len)
	for var i = 0; i < l; i++
		if a[i] < b[i]
			-> `Before
		elif a[i] > b[i]
			-> `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 strcasecmp = {a, b
	var ca, cb

	while a.len > 0 && b.len > 0
		(ca, a) = std.charstep(a)
		(cb, b) = std.charstep(b)
		ca = toupper(ca)
		cb = toupper(cb)
		if ca < cb
			-> `Before
		elif ca > cb
			-> `After
		;;
	;;
	if a.len < b.len
		-> `Before
	elif a.len > b.len
		-> `After
	else
		-> `Equal
	;;
}