summaryrefslogtreecommitdiff
path: root/libstd/intparse.myr
blob: 4180f8c4a9daca951c7cb1dbdbe189b004903a34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use "chartype.use"
use "die.use"
use "hasprefix.use"
use "option.use"
use "types.use"
use "utf.use"

pkg std =
	generic intparsebase	: (s : byte[:], base : int -> option(@a::(integral,numeric)))
	generic intparse	: (s : byte[:]	-> option(@a::(integral,numeric)))
;;

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
	var isneg 

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

	-> doparse(s, isneg, base)
}

generic doparse = {s, isneg, base
	var c
	var v
	var cv : int32
	
	v = 0
	while s.len != 0
		(c, s) = striter(s)
		if c == '_'
			continue
		;;
		cv = charval(c, base)
		if cv >= 0
			v *= (base castto(@a::(integral,numeric)))
			v += cv castto(@a::(integral,numeric))
		else
			-> `None
		;;
	;;

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