shithub: mc

ref: 4a7d019d03fa6c267d27ffb9d90e2472bad4bcbf
dir: /libstd/intparse.myr/

View raw version
use "die.use"
use "strcmp.use"
use "types.use"
use "utf.use"
use "fmt.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 doparse
;;

generic intparse = {s
	var isneg 

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

	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, isneg, 10)
	;;
}

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

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

	-> doparse(s, isneg, base)
}

generic doparse = {s, isneg, base -> @a::(tcint,tcnum,tctest)
	var v : @a::(tcint,tcnum,tctest)
	var c
	
	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)))
		fatal(1, "Character %c out of range", c)
	;;
	-> v
}