diff --git a/src/CommandLine.cxx b/src/CommandLine.cxx index b3b54e735..8f29720ff 100644 --- a/src/CommandLine.cxx +++ b/src/CommandLine.cxx @@ -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; diff --git a/src/util/OptionParser.cxx b/src/util/OptionParser.cxx index 3c96e7f2c..b48873777 100644 --- a/src/util/OptionParser.cxx +++ b/src/util/OptionParser.cxx @@ -23,7 +23,7 @@ #include -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}; } diff --git a/src/util/OptionParser.hxx b/src/util/OptionParser.hxx index 17a1cc7e1..a7176a4c3 100644 --- a/src/util/OptionParser.hxx +++ b/src/util/OptionParser.hxx @@ -45,17 +45,22 @@ public: remaining_head(const_cast(_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