ref: 5262bed1d0a0f153c7c4103d059ac9e7f955bc11
dir: /libstd/option.myr/
use "types.use"
use "alloc.use"
use "utf.use"
use "die.use"
pkg std =
type optctx = struct
/* data passed in */
opts : byte[:]
args : byte[:][:]
/* state */
argidx : size
curarg : byte[:]
arglist : byte[:][:]
;;
const optinit : (opts : byte[:], opts : byte[:][:] -> optctx*)
const optnext : (ctx : optctx* -> char)
const optarg : (ctx : optctx* -> byte[:])
;;
const optinit = {opts, args
var ctx
ctx = alloc()
ctx.opts = opts
ctx.args = args
ctx.argidx = 0
ctx.arglist = [][:]
nextopt(ctx)
-> ctx
}
const optnext = {ctx
var c
if !ctx.curarg.len
if !nextopt(ctx)
-> Badchar
;;
;;
(c, ctx.curarg) = striter(ctx.curarg)
-> c
}
const optarg = {ctx
var arg
if ctx.curarg.len > 0
arg = ctx.curarg
ctx.curarg = ctx.curarg[ctx.curarg.len:]
elif ctx.argidx > ctx.args.len
arg = ctx.args[ctx.argidx + 1]
ctx.argidx++
nextopt(ctx)
else
die("Arg needed")
;;
-> arg
}
const nextopt = {ctx
var i
for i = ctx.argidx + 1; i < ctx.args.len; i++
if decode(ctx.args[i]) == '-'
goto foundopt
else
/* FIXME: implement slappend */
/* ctx.args = slappend(ctx.args, ctx.args[i]) */
;;
;;
-> false
:foundopt
ctx.argidx = i
ctx.curarg = ctx.args[i][1:]
-> true
}