about summary refs log blame commit diff stats
path: root/linux/apps/parse-int.mu
blob: 0f8c71d15a0f4e35c0fff6285f4cf925a53e0537 (plain) (tree)
1
2
3
4
5
6
7
8
9


                                        
                                   



                 
                                                           
                                        
                                                          



                               
                                                         
            
pre { line-height: 125%; } td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-col
# parse a decimal int at the commandline
#
# To run:
#   $ ./translate apps/parse-int.mu
#   $ ./a.elf 123
#   $ echo $?
#   123

fn main _args: (addr array addr array byte) -> _/ebx: int {
  # if no args, print a message and exit
  var args/esi: (addr array addr array byte) <- copy _args
  var n/ecx: int <- length args
  compare n, 1
  {
    break-if->
    print-string 0/screen, "usage: parse-int <integer>\n"
    return 1
  }
  # otherwise parse the first arg as an integer
  var in/ecx: (addr addr array byte) <- index args, 1
  var out/eax: int <- parse-int *in
  return out
}

fn parse-int _in: (addr array byte) -> _/eax: int {
  var in/esi: (addr array byte) <- copy _in
  var len/edx: int <- length in
  var i/ecx: int <- copy 0
  var result/edi: int <- copy 0
  {
    compare i, len
    break-if->=
    # result *= 10
    var ten/eax: int <- copy 0xa
    result <- multiply ten
    # c = in[i]
    var tmp/ebx: (addr byte) <- index in, i
    var c/eax: byte <- copy-byte *tmp
    #
    var g/eax: grapheme <- copy c
    var digit/eax: int <- to-decimal-digit g
    result <- add digit
    i <- increment
    loop
  }
  return result
}