From 727e176e30cf05ee2d88c28bb44bb0364d8e4e72 Mon Sep 17 00:00:00 2001 From: Joseph Hunkeler Date: Fri, 31 Jan 2025 11:23:50 -0500 Subject: Implements function strlist_contains --- src/lib/core/include/strlist.h | 1 + src/lib/core/strlist.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) (limited to 'src') diff --git a/src/lib/core/include/strlist.h b/src/lib/core/include/strlist.h index cdbfc01..18c60eb 100644 --- a/src/lib/core/include/strlist.h +++ b/src/lib/core/include/strlist.h @@ -40,6 +40,7 @@ void strlist_set(struct StrList **pStrList, size_t index, char *value); size_t strlist_count(struct StrList *pStrList); void strlist_reverse(struct StrList *pStrList); void strlist_sort(struct StrList *pStrList, unsigned int mode); +int strlist_contains(struct StrList *pStrList, const char *value, size_t *index_of); int strlist_append_file(struct StrList *pStrList, char *path, ReaderFn *readerFn); void strlist_append_strlist(struct StrList *pStrList1, struct StrList *pStrList2); void strlist_append(struct StrList **pStrList, char *str); diff --git a/src/lib/core/strlist.c b/src/lib/core/strlist.c index ec7b3f4..704cf9c 100644 --- a/src/lib/core/strlist.c +++ b/src/lib/core/strlist.c @@ -129,6 +129,48 @@ fatal: return retval; } +/** + * Is `value` present in `pStrList`? + * The caller should test for success before using the value `index_of` + * + * ```c + * const char *needle = "world!"; + * + * struct StrList *haystack = strlist_init(); + * strlist_append(&haystack, "hello"); + * strlist_append(&haystack, "world!"); + * + * size_t index_of_item; + * if (strlist_contains(haystack, needle, &index_of_item)) { + * const char *item = strlist_item(haystack, index_of_item); + * // index_of_item == 1 + * // item is "world!" + * } else { + * fprintf(stderr, "%s not found\n", needle); + * } + * ``` + * + * @param pStrList pointer to `StrList` + * @param index_of (result) index of string in `pStrList`, if found + * @param value string to search for in `pStrList` + * @return 1 found + * @return 0 not found + */ +int strlist_contains(struct StrList *pStrList, const char *value, size_t *index_of) { + if (pStrList == NULL) { + return 0; + } + + for (size_t i = 0; i < strlist_count(pStrList); i++) { + const char *item = strlist_item(pStrList, i); + if (!strcmp(item, value)) { + *index_of = i; + return 1; + } + } + return 0; +} + /** * Append the contents of `pStrList2` to `pStrList1` * @param pStrList1 `StrList` -- cgit