util/OptionParser: add struct Result

Prepare for option values.
This commit is contained in:
Max Kellermann 2018-01-17 11:00:07 +01:00
parent d588da69e5
commit c45fe3517c
3 changed files with 17 additions and 13 deletions

View File

@ -309,9 +309,8 @@ ParseCommandLine(int argc, char **argv, struct options &options)
// First pass: handle command line options
OptionParser parser(option_defs, argc, argv);
int option_index;
while ((option_index = parser.Next()) >= 0) {
switch (Option(option_index)) {
while (auto o = parser.Next()) {
switch (Option(o.index)) {
case OPTION_KILL:
options.kill = true;
break;

View File

@ -23,7 +23,7 @@
#include <string.h>
inline unsigned
inline OptionParser::Result
OptionParser::IdentifyOption(const char *s) const
{
assert(s != nullptr);
@ -33,18 +33,18 @@ OptionParser::IdentifyOption(const char *s) const
for (const auto &i : options)
if (i.HasLongOption() &&
strcmp(s + 2, i.GetLongOption()) == 0)
return &i - options.data;
return {int(&i - options.data)};
} else if (s[1] != 0 && s[2] == 0) {
const char ch = s[1];
for (const auto &i : options)
if (i.HasShortOption() && ch == i.GetShortOption())
return &i - options.data;
return {int(&i - options.data)};
}
throw FormatRuntimeError("Unknown option: %s", s);
}
int
OptionParser::Result
OptionParser::Next()
{
while (!args.empty()) {
@ -55,5 +55,5 @@ OptionParser::Next()
*remaining_tail++ = arg;
}
return -1;
return {-1};
}

View File

@ -45,17 +45,22 @@ public:
remaining_head(const_cast<const char **>(_argv + 1)),
remaining_tail(remaining_head) {}
struct Result {
int index;
constexpr operator bool() noexcept {
return index >= 0;
}
};
/**
* Parses current command line entry.
* Regardless of result, advances current position to the next
* command line entry.
*
* Throws on error.
*
* @return the index if an option was found, -1 if there are
* no more options
*/
int Next();
Result Next();
/**
* Returns the remaining non-option arguments.
@ -65,7 +70,7 @@ public:
}
private:
unsigned IdentifyOption(const char *s) const;
Result IdentifyOption(const char *s) const;
};
#endif