From 22f2ae73417c3214e403932ea51a5dc59674c7b3 Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Sat, 14 Jul 2018 18:21:46 +0200 Subject: [PATCH] Add methods _all_of_p, _any_of_p and _none_of_p. --- m-algo.h | 30 ++++++++++++++++++++++++++++++ tests/test-malgo.c | 25 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/m-algo.h b/m-algo.h index 7f8ae946..1553b54e 100644 --- a/m-algo.h +++ b/m-algo.h @@ -199,6 +199,36 @@ M_GET_CLEAR type_oplist (tmp); \ } \ \ + static inline bool \ + M_C(name, _any_of_p) (container_t l, bool (*f)(type_t const) ) \ + { \ + for M_EACH(item, l, cont_oplist) { \ + if (f(*item)) \ + return true; \ + } \ + return false; \ + } \ + \ + static inline bool \ + M_C(name, _all_of_p) (container_t l, bool (*f)(type_t const) ) \ + { \ + for M_EACH(item, l, cont_oplist) { \ + if (!f(*item)) \ + return false; \ + } \ + return true; \ + } \ + \ + static inline bool \ + M_C(name, _none_of_p) (container_t l, bool (*f)(type_t const) ) \ + { \ + for M_EACH(item, l, cont_oplist) { \ + if (f(*item)) \ + return false; \ + } \ + return true; \ + } \ + \ M_IF_METHOD(CMP, type_oplist)( \ static inline type_t * \ M_C(name, _min) (const container_t l) \ diff --git a/tests/test-malgo.c b/tests/test-malgo.c index af868303..8d2ecbfa 100644 --- a/tests/test-malgo.c +++ b/tests/test-malgo.c @@ -71,6 +71,21 @@ static void func_reduce(int *d, int n) *d += n; } +static bool func_test_42(int d) +{ + return d == 42; +} + +static bool func_test_101(int d) +{ + return d == 101; +} + +static bool func_test_pos(int d) +{ + return d >= 0; +} + static void test_list(void) { list_int_t l; @@ -85,6 +100,16 @@ static void test_list(void) assert( algo_list_count(l, 17) == 2); assert( algo_list_count(l, -1) == 0); + assert (algo_list_all_of_p(l, func_test_42) == false); + assert (algo_list_any_of_p(l, func_test_42) == true); + assert (algo_list_none_of_p(l, func_test_42) == false); + assert (algo_list_all_of_p(l, func_test_101) == false); + assert (algo_list_any_of_p(l, func_test_101) == false); + assert (algo_list_none_of_p(l, func_test_101) == true); + assert (algo_list_all_of_p(l, func_test_pos) == true); + assert (algo_list_any_of_p(l, func_test_pos) == true); + assert (algo_list_none_of_p(l, func_test_pos) == false); + #define f(x) assert((x) >= 0 && (x) < 100); ALGO_MAP(l, LIST_OPLIST(list_int), f); #define g(y, x) assert((x) >= 0 && (x) < y);