getsubopt.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, 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. /* Experimentally off - libc_hidden_proto(memchr) */
  20. /* Experimentally off - libc_hidden_proto(strncmp) */
  21. /* Experimentally off - 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
  29. getsubopt (char **optionp, char *const *tokens, char **valuep)
  30. {
  31. char *endp, *vstart;
  32. int cnt;
  33. if (**optionp == '\0')
  34. return -1;
  35. /* Find end of next token. */
  36. endp = strchrnul (*optionp, ',');
  37. /* Find start of value. */
  38. vstart = memchr (*optionp, '=', endp - *optionp);
  39. if (vstart == NULL)
  40. vstart = endp;
  41. /* Try to match the characters between *OPTIONP and VSTART against
  42. one of the TOKENS. */
  43. for (cnt = 0; tokens[cnt] != NULL; ++cnt)
  44. if (strncmp (*optionp, tokens[cnt], vstart - *optionp) == 0
  45. && tokens[cnt][vstart - *optionp] == '\0')
  46. {
  47. /* We found the current option in TOKENS. */
  48. *valuep = vstart != endp ? vstart + 1 : NULL;
  49. if (*endp != '\0')
  50. *endp++ = '\0';
  51. *optionp = endp;
  52. return cnt;
  53. }
  54. /* The current suboption does not match any option. */
  55. *valuep = *optionp;
  56. if (*endp != '\0')
  57. *endp++ = '\0';
  58. *optionp = endp;
  59. return -1;
  60. }