getopt() but smaller
2024-11-07 02:17https://dotat.at/@/2024-11-06-getopt.html
The other day I learned about the Rust crate lexopt which describes itself as,
A pathologically simple command line argument parser.
Most argument parsers are declarative: you tell them what to parse, and they do it. This one provides you with a stream of options and values and lets you figure out the rest.
For "pathologically simple" I still rather like getopt(3) despite its lack of support for long options. Aaron S Cohen wrote getopt in around 1979, and it was released into the public domain by AT&T in 1985. A very useful 50-ish lines of code! It still has almost everything required by POSIX nearly four decades later.
But the description of lexopt
made me think getopt()
could be
simpler. The insight is that the string of options that you have to
pass to getopt()
is redundant with respect to the code that deals
with the return values from getopt()
. What if you just get rid of
the options string?
I thought I would try it. Turns out, not much is lost in getting rid of the options string, and a few things are gained.
My new code is half the size or less of getopt()
, and has more
functionality. I'm going to show how how this was done, because it's
short (ish), not because it is interesting. Then I'll try to tease out
a lesson or two.
( Read more... )