getsubopt.cpp 1.7 KB

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