getsubopt.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Parse comma separate list into words.
  2. Copyright (C) 1996, 1997, 1999, 2004 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. /* Parse comma separated suboption from *OPTIONP and match against
  19. strings in TOKENS. If found return index and set *VALUEP to
  20. optional value introduced by an equal sign. If the suboption is
  21. not part of TOKENS return in *VALUEP beginning of unknown
  22. suboption. On exit *OPTIONP is set to the beginning of the next
  23. token or at the terminating NUL character. */
  24. int
  25. getsubopt (char **optionp, char *const *tokens, char **valuep)
  26. {
  27. char *endp, *vstart;
  28. int cnt;
  29. if (**optionp == '\0')
  30. return -1;
  31. /* Find end of next token. */
  32. endp = strchrnul (*optionp, ',');
  33. /* Find start of value. */
  34. vstart = memchr (*optionp, '=', endp - *optionp);
  35. if (vstart == NULL)
  36. vstart = endp;
  37. /* Try to match the characters between *OPTIONP and VSTART against
  38. one of the TOKENS. */
  39. for (cnt = 0; tokens[cnt] != NULL; ++cnt)
  40. if (strncmp (*optionp, tokens[cnt], vstart - *optionp) == 0
  41. && tokens[cnt][vstart - *optionp] == '\0')
  42. {
  43. /* We found the current option in TOKENS. */
  44. *valuep = vstart != endp ? vstart + 1 : NULL;
  45. if (*endp != '\0')
  46. *endp++ = '\0';
  47. *optionp = endp;
  48. return cnt;
  49. }
  50. /* The current suboption does not match any option. */
  51. *valuep = *optionp;
  52. if (*endp != '\0')
  53. *endp++ = '\0';
  54. *optionp = endp;
  55. return -1;
  56. }