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