getsubopt.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Parse comma separate list into words.
  2. Copyright (C) 1996-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #if !_LIBC
  19. /* This code is written for inclusion in gnu-libc, and uses names in
  20. the namespace reserved for libc. If we're compiling in gnulib,
  21. define those names to be the normal ones instead. */
  22. # include "strchrnul.h"
  23. # undef __strchrnul
  24. # define __strchrnul strchrnul
  25. #endif
  26. /* Parse comma separated suboption from *OPTIONP and match against
  27. strings in TOKENS. If found return index and set *VALUEP to
  28. optional value introduced by an equal sign. If the suboption is
  29. not part of TOKENS return in *VALUEP beginning of unknown
  30. suboption. On exit *OPTIONP is set to the beginning of the next
  31. token or at the terminating NUL character. */
  32. int
  33. getsubopt (char **optionp, char *const *tokens, char **valuep)
  34. {
  35. char *endp, *vstart;
  36. int cnt;
  37. if (**optionp == '\0')
  38. return -1;
  39. /* Find end of next token. */
  40. endp = __strchrnul (*optionp, ',');
  41. /* Find start of value. */
  42. vstart = memchr (*optionp, '=', endp - *optionp);
  43. if (vstart == NULL)
  44. vstart = endp;
  45. /* Try to match the characters between *OPTIONP and VSTART against
  46. one of the TOKENS. */
  47. for (cnt = 0; tokens[cnt] != NULL; ++cnt)
  48. if (strncmp (*optionp, tokens[cnt], vstart - *optionp) == 0
  49. && tokens[cnt][vstart - *optionp] == '\0')
  50. {
  51. /* We found the current option in TOKENS. */
  52. *valuep = vstart != endp ? vstart + 1 : NULL;
  53. if (*endp != '\0')
  54. *endp++ = '\0';
  55. *optionp = endp;
  56. return cnt;
  57. }
  58. /* The current suboption does not match any option. */
  59. *valuep = *optionp;
  60. if (*endp != '\0')
  61. *endp++ = '\0';
  62. *optionp = endp;
  63. return -1;
  64. }