3
0

compare_string_array.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  4. */
  5. #include "libbb.h"
  6. /* returns the array index of the string */
  7. /* (index of first match is returned, or -1) */
  8. int FAST_FUNC index_in_str_array(const char *const string_array[], const char *key)
  9. {
  10. int i;
  11. for (i = 0; string_array[i] != 0; i++) {
  12. if (strcmp(string_array[i], key) == 0) {
  13. return i;
  14. }
  15. }
  16. return -1;
  17. }
  18. int FAST_FUNC index_in_strings(const char *strings, const char *key)
  19. {
  20. int idx = 0;
  21. while (*strings) {
  22. if (strcmp(strings, key) == 0) {
  23. return idx;
  24. }
  25. strings += strlen(strings) + 1; /* skip NUL */
  26. idx++;
  27. }
  28. return -1;
  29. }
  30. /* returns the array index of the string, even if it matches only a beginning */
  31. /* (index of first match is returned, or -1) */
  32. #ifdef UNUSED
  33. int FAST_FUNC index_in_substr_array(const char *const string_array[], const char *key)
  34. {
  35. int i;
  36. int len = strlen(key);
  37. if (len) {
  38. for (i = 0; string_array[i] != 0; i++) {
  39. if (strncmp(string_array[i], key, len) == 0) {
  40. return i;
  41. }
  42. }
  43. }
  44. return -1;
  45. }
  46. #endif
  47. int FAST_FUNC index_in_substrings(const char *strings, const char *key)
  48. {
  49. int matched_idx = -1;
  50. const int len = strlen(key);
  51. if (len) {
  52. int idx = 0;
  53. while (*strings) {
  54. if (strncmp(strings, key, len) == 0) {
  55. if (strings[len] == '\0')
  56. return idx; /* exact match */
  57. if (matched_idx >= 0)
  58. return -1; /* ambiguous match */
  59. matched_idx = idx;
  60. }
  61. strings += strlen(strings) + 1; /* skip NUL */
  62. idx++;
  63. }
  64. }
  65. return matched_idx;
  66. }
  67. const char* FAST_FUNC nth_string(const char *strings, int n)
  68. {
  69. while (n) {
  70. n--;
  71. strings += strlen(strings) + 1;
  72. }
  73. return strings;
  74. }
  75. #ifdef UNUSED_SO_FAR /* only brctl.c needs it yet */
  76. /* Returns 0 for no, 1 for yes or a negative value on error. */
  77. smallint FAST_FUNC yesno(const char *str)
  78. {
  79. static const char no_yes[] ALIGN1 =
  80. "0\0" "off\0" "no\0"
  81. "1\0" "on\0" "yes\0";
  82. int ret = index_in_substrings(no_yes, str);
  83. return ret / 3;
  84. }
  85. #endif