getsubopt.c 2.3 KB

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