ref: e4299d409e5f62e73346227fc9c10ed63d078000
dir: /libstd/intparse.myr/
use "die.use" use "strcmp.use" use "option.use" use "types.use" use "utf.use" use "fmt.use" pkg std = generic intparsebase : (s : byte[:], base : int -> option(@a::(tcint,tcnum,tctest))) generic intparse : (s : byte[:] -> option(@a::(tcint,tcnum,tctest))) /* FIXME: fix hidden exports */ generic charval : (c : char, base : int -> option(@a::(tcnum,tctest,tcint))) generic doparse : (s : byte[:], isneg : bool, base : int -> option(@a::(tcnum,tctest,tcint))) ;; 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 v = 0 while s.len != 0 (c, s) = striter(s) match charval(c, base) | `Some cv: v *= (base castto(@a::(tcint,tcnum,tctest))) v += cv | `None: -> `None ;; ;; if isneg -> `Some -v else -> `Some v ;; } generic charval = {c, base 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))) -> `None ;; -> `Some v }