Skip to content

Commit

Permalink
LibC: Convert getopt and getopt_long to new StringView usage
Browse files Browse the repository at this point in the history
  • Loading branch information
sin-ack authored and awesomekling committed Jul 12, 2022
1 parent 828060e commit e3da0ad
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions Userland/Libraries/LibC/getopt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ class OptionParser {
void shift_argv();
bool find_next_option();

StringView current_arg() const
{
auto const* arg_ptr = m_argv[m_arg_index];
if (arg_ptr == NULL)
return {};
return { arg_ptr, strlen(arg_ptr) };
}

size_t m_argc { 0 };
char* const* m_argv { nullptr };
StringView m_short_options;
Expand Down Expand Up @@ -98,7 +106,7 @@ int OptionParser::getopt()
int res = -1;

bool found_an_option = find_next_option();
StringView arg = m_argv[m_arg_index];
auto arg = current_arg();

if (!found_an_option) {
res = -1;
Expand Down Expand Up @@ -154,7 +162,7 @@ bool OptionParser::lookup_short_option(char option, int& needs_value) const

int OptionParser::handle_short_option()
{
StringView arg = m_argv[m_arg_index];
StringView arg = current_arg();
VERIFY(arg.starts_with('-'));

if (s_index_into_multioption_argument == 0) {
Expand Down Expand Up @@ -237,7 +245,7 @@ option const* OptionParser::lookup_long_option(char* raw) const

int OptionParser::handle_long_option()
{
VERIFY(StringView(m_argv[m_arg_index]).starts_with("--"));
VERIFY(current_arg().starts_with("--"sv));

// We cannot set optopt to anything sensible for long options, so set it to 0.
optopt = 0;
Expand Down Expand Up @@ -311,7 +319,7 @@ void OptionParser::shift_argv()
bool OptionParser::find_next_option()
{
for (m_arg_index = optind; m_arg_index < m_argc && m_argv[m_arg_index]; m_arg_index++) {
StringView arg = m_argv[m_arg_index];
StringView arg = current_arg();
// Anything that doesn't start with a "-" is not an option.
if (!arg.starts_with('-')) {
if (m_stop_on_first_non_option)
Expand Down

0 comments on commit e3da0ad

Please sign in to comment.