bitwise shrub/kav / lib / fmt.kav
 1use <prelude.kav>
 2use <bytes.kav> as bytes
 3use <result.kav> as res
 4use <str.kav> as str
 5use <mem.kav> as mem
 6
 7pub fn size() -> int {
 8    21
 9}
10
11fn count(u: u64, n: int) -> int {
12    if u > 9 then count(u / 10, n + 1) else n
13}
14
15pub fn digits(u: u64) -> int {
16    count(u, 1)
17}
18
19fn fill[n: nat](m: bytes::Bytes[n], i: int, u: u64) -> bytes::Bytes[n] {
20    val m = bytes::set(m, i - 1, (u % 10) as u8 + '0')
21    if u > 9 then fill(m, i - 1, u / 10) else m
22}
23
24pub fn u64[n:nat](m: bytes::Bytes[n], off: int, u: u64) -> (bytes::Bytes[n], int) {
25    val len = digits(u)
26    (fill(m, off + len, u), len)
27}
28
29pub fn int[n: nat](m: bytes::Bytes[n], off: int, x: int) -> (bytes::Bytes[n], int) {
30    if x < 0 then {
31        val m = bytes::set(m, off, '-')
32        val (m, len) = u64(m, off + 1, (0 - x) as u64)
33        (m, len + 1)
34    } else u64(m, off, x as u64)
35}
36
37fn scandigits(s: cstr, i: int, acc: int) -> res::Result[int, int] {
38    val c = mem::load8(mem::add(s as ptr, i)) as int
39    if c == 0 then res::Ok(acc)
40    else if c < '0' then res::Err(0)
41    else if c > '9' then res::Err(0)
42    else scandigits(s, i + 1, acc * 10 + (c - '0'))
43}
44
45/%
46Get a decimal number from s, Err if s isn't one
47
48eg "67" (cstr) -> 67 (int)
49%/
50pub fn scan(s: cstr) -> res::Result[int, int] {
51    if str::len(s) == 0 then res::Err(0)
52    else scandigits(s, 0, 0)
53}