getsubopt.c 2.3 KB

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