u/string_list: Add contains function

This commit is contained in:
Christoph Haag 2021-12-06 13:53:09 +01:00
parent 07ddac523c
commit 20f265d9ae
3 changed files with 43 additions and 0 deletions

View file

@ -98,6 +98,12 @@ u_string_list_append_unique(struct u_string_list *usl, const char *str)
}
}
bool
u_string_list_contains(struct u_string_list *usl, const char *str)
{
return usl->list.contains(str);
}
void
u_string_list_destroy(struct u_string_list **list_ptr)
{

View file

@ -84,6 +84,19 @@ u_string_list_append(struct u_string_list *usl, const char *str);
int
u_string_list_append_unique(struct u_string_list *usl, const char *str);
/*!
* @brief Check if the string is in the list.
*
* (Comparing string contents, not just pointers)
*
* @param usl self pointer
* @param str a non-null, null-terminated string.
*
* @return true if the string is in the list.
*/
bool
u_string_list_contains(struct u_string_list *usl, const char *str);
/*!
* @brief Destroy a string list.
*

View file

@ -107,6 +107,30 @@ public:
push_back(elt);
}
}
/*!
* @brief Check if the string is in the list.
*
* (Comparing string contents, not just pointers)
*
* @param str a non-null, null-terminated string.
*
* @return true if the string is in the list.
*/
bool
contains(const char *str)
{
if (str == nullptr) {
throw std::invalid_argument("Cannot pass a null pointer");
}
std::string needle{str};
auto it = std::find_if(vec.begin(), vec.end(), [needle](const char *elt) { return needle == elt; });
if (it != vec.end()) {
return true;
}
return false;
}
/*!
* @brief Append a new string to the list if it doesn't match any existing string.
*