ladybird/Userland/Libraries/LibC/getsubopt.cpp
Ben Wiederhake 6b7ce19161 Everywhere: Remove unused includes of LibC/stdlib.h
These instances were detected by searching for files that include
stdlib.h, but don't match the regex:

\\b(_abort|abort|abs|aligned_alloc|arc4random|arc4random_buf|arc4random_
uniform|atexit|atof|atoi|atol|atoll|bsearch|calloc|clearenv|div|div_t|ex
it|_Exit|EXIT_FAILURE|EXIT_SUCCESS|free|getenv|getprogname|grantpt|labs|
ldiv|ldiv_t|llabs|lldiv|lldiv_t|malloc|malloc_good_size|malloc_size|mble
n|mbstowcs|mbtowc|mkdtemp|mkstemp|mkstemps|mktemp|posix_memalign|posix_o
penpt|ptsname|ptsname_r|putenv|qsort|qsort_r|rand|RAND_MAX|random|reallo
c|realpath|secure_getenv|serenity_dump_malloc_stats|serenity_setenv|sete
nv|setprogname|srand|srandom|strtod|strtof|strtol|strtold|strtoll|strtou
l|strtoull|system|unlockpt|unsetenv|wcstombs|wctomb)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use anything from the stdlib.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00

53 lines
1.8 KiB
C++

/*
* Copyright (c) 2022, Liav A. <liavalb@hotmail.co.il>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/ScopeGuard.h>
#include <AK/StringView.h>
#include <string.h>
#include <unistd.h>
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsubopt.html
int getsubopt(char** option_array, char* const* tokens, char** option_value)
{
if (**option_array == '\0')
return -1;
auto const* option_ptr = *option_array;
StringView option_string { option_ptr, strlen(option_ptr) };
auto possible_comma_location = option_string.find(',');
char* option_end = const_cast<char*>(option_string.characters_without_null_termination()) + possible_comma_location.value_or(option_string.length());
auto possible_equals_char_location = option_string.find('=');
char* value_start = option_end;
if (possible_equals_char_location.has_value()) {
value_start = const_cast<char*>(option_string.characters_without_null_termination()) + possible_equals_char_location.value();
}
ScopeGuard ensure_end_array_contains_null_char([&]() {
if (*option_end != '\0')
*option_end++ = '\0';
*option_array = option_end;
});
for (int count = 0; tokens[count] != NULL; ++count) {
auto const* token = tokens[count];
StringView token_stringview { token, strlen(token) };
if (!option_string.starts_with(token_stringview))
continue;
if (tokens[count][value_start - *option_array] != '\0')
continue;
*option_value = value_start != option_end ? value_start + 1 : nullptr;
return count;
}
// Note: The current sub-option does not match any option, so prepare to tell this
// to the application.
*option_value = *option_array;
return -1;
}