Serenity Operating System
at master 52 lines 1.8 kB view raw
1/* 2 * Copyright (c) 2022, Liav A. <liavalb@hotmail.co.il> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/ScopeGuard.h> 8#include <AK/StringView.h> 9#include <string.h> 10#include <unistd.h> 11 12// https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsubopt.html 13int getsubopt(char** option_array, char* const* tokens, char** option_value) 14{ 15 if (**option_array == '\0') 16 return -1; 17 18 auto const* option_ptr = *option_array; 19 StringView option_string { option_ptr, strlen(option_ptr) }; 20 21 auto possible_comma_location = option_string.find(','); 22 char* option_end = const_cast<char*>(option_string.characters_without_null_termination()) + possible_comma_location.value_or(option_string.length()); 23 24 auto possible_equals_char_location = option_string.find('='); 25 char* value_start = option_end; 26 if (possible_equals_char_location.has_value()) { 27 value_start = const_cast<char*>(option_string.characters_without_null_termination()) + possible_equals_char_location.value(); 28 } 29 30 ScopeGuard ensure_end_array_contains_null_char([&]() { 31 if (*option_end != '\0') 32 *option_end++ = '\0'; 33 *option_array = option_end; 34 }); 35 36 for (int count = 0; tokens[count] != NULL; ++count) { 37 auto const* token = tokens[count]; 38 StringView token_stringview { token, strlen(token) }; 39 if (!option_string.starts_with(token_stringview)) 40 continue; 41 if (tokens[count][value_start - *option_array] != '\0') 42 continue; 43 44 *option_value = value_start != option_end ? value_start + 1 : nullptr; 45 return count; 46 } 47 48 // Note: The current sub-option does not match any option, so prepare to tell this 49 // to the application. 50 *option_value = *option_array; 51 return -1; 52}