shithub: mc

ref: 928dd90068c3c8a65d7994e2307a5ddcbb44217a
dir: /libstd/option.myr/

View raw version
use "types.use"
use "alloc.use"
use "utf.use"

pkg std =
	type optctx = struct
		/* data passed in */
		opts	: byte[:]
		args	: byte[:][:]

		/* state */
		optidx	: size
		curarg	: byte[:]
		args	: byte[:][:]
	;;

	const optinit	: (opts	: byte[:], opts : byte[:][:] -> optctx*)
	const optnext	: (ctx : optctx* -> char)
;;

const optinit = {opts, args
	var ctx

	ctx = alloc()
	ctx.opts = opts
	ctx.args = args
	ctx.optidx = 0
	ctx.args = [][:]
	nextopt(ctx)
	-> ctx
}

const optnext = {ctx
	var c

	if !ctx.curarg.len
		if !nextopt(ctx)
			-> Badchar
		;;
	;;
	(c, ctx.curarg) = striter(ctx.curarg)
	-> c
}

const nextopt = {ctx
	var i

	for i = ctx.optidx + 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.optidx = i
	ctx.curarg = ctx.args[i]
	-> true
}