parse-sublevel-options.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include "util/debug.h"
  6. #include "util/parse-sublevel-options.h"
  7. static int parse_one_sublevel_option(const char *str,
  8. struct sublevel_option *opts)
  9. {
  10. struct sublevel_option *opt = opts;
  11. char *vstr, *s = strdup(str);
  12. int v = 1;
  13. if (!s) {
  14. pr_err("no memory\n");
  15. return -1;
  16. }
  17. vstr = strchr(s, '=');
  18. if (vstr)
  19. *vstr++ = 0;
  20. while (opt->name) {
  21. if (!strcmp(s, opt->name))
  22. break;
  23. opt++;
  24. }
  25. if (!opt->name) {
  26. pr_err("Unknown option name '%s'\n", s);
  27. free(s);
  28. return -1;
  29. }
  30. if (vstr)
  31. v = atoi(vstr);
  32. *opt->value_ptr = v;
  33. free(s);
  34. return 0;
  35. }
  36. /* parse options like --foo a=<n>,b,c... */
  37. int perf_parse_sublevel_options(const char *str, struct sublevel_option *opts)
  38. {
  39. char *s = strdup(str);
  40. char *p = NULL;
  41. int ret;
  42. if (!s) {
  43. pr_err("no memory\n");
  44. return -1;
  45. }
  46. p = strtok(s, ",");
  47. while (p) {
  48. ret = parse_one_sublevel_option(p, opts);
  49. if (ret) {
  50. free(s);
  51. return ret;
  52. }
  53. p = strtok(NULL, ",");
  54. }
  55. free(s);
  56. return 0;
  57. }