shithub: mc

ref: 7ea39f801622858865e2fb06768a9f44f81b5bf8
dir: /libstd/intparse.myr/

View raw version
use "die.use"
use "strcmp.use"
use "types.use"
use "utf.use"

pkg std =
	generic intparsebase	: (s : byte[:], base : int -> @a::(tcint,tcnum,tctest))
	generic intparse	: (s : byte[:]	-> @a::(tcint,tcnum,tctest))

	/* FIXME: fix hidden exports */
	generic charval
;;

generic intparse = {s
	var isneg 

	isneg = 0
	if hasprefix(s, "-")
		s = s[1:]
		isneg = 1
	;;

	if hasprefix(s, "0x")
		-> doparse(s[2:], isneg, 16)
	elif hasprefix(s, "0o")
		-> doparse(s[2:], isneg, 8)
	elif hasprefix(s, "0b")
		-> doparse(s[2:], isneg, 2)
	else
		-> doparse(s[2:], isneg, 10)
	;;
}

generic intparsebase = {s, base -> @a::(tcint,tcnum,tctest)
	var isneg 

	isneg = 0
	if hasprefix(s, "-")
		s = s[1:]
		isneg = 1
	;;

	-> doparse(s, isneg, base)
}

generic doparse = {s, isneg, base -> @a::(tcint,tcnum,tctest)
	var v : @a::(tcint,tcnum,tctest)
	var c
	
	assert(base <= 36, "Base for parsing values is too big")
	v = 0
	while s.len != 0
		(c, s) = striter(s)
		v *= base castto(@a::(tcint,tcnum,tctest))
		v += charval(c, base)
	;;

	if isneg
		-> v
	else
		-> -v
	;;
}

generic charval = {c, base -> @a :: (tcint,tcnum,tctest)
	var v = -1

	if c >= '0' && c <= '9'
		v =  (c - '0') castto(@a::(tcint,tcnum,tctest))
	elif c >= 'a' && c <= 'z'
		v =  (c - 'a') castto(@a::(tcint,tcnum,tctest))
	elif c >= 'A' && c <= 'Z'
		v =  (c - 'A') castto(@a::(tcint,tcnum,tctest))
	;;

	if v < 0 || v > (base castto(@a::(tcint,tcnum,tctest)))
		die("Character out of range for base when parsing integer")
	;;
	-> v
}