From 6f80025fe67cc3cf68ca700967e6920285fbd9da Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Sat, 6 Jun 2015 15:40:16 +0200 Subject: [PATCH] list utils: implementation of first_of --- src/common/list_utils.h | 18 ++++++++++++++++++ tests/unit/common/list_utils.cpp | 15 +++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/common/list_utils.h b/src/common/list_utils.h index 0a8cedaf1..eb6592e25 100644 --- a/src/common/list_utils.h +++ b/src/common/list_utils.h @@ -14,6 +14,8 @@ #ifndef MTX_COMMON_LIST_UTILS_H #define MTX_COMMON_LIST_UTILS_H +#include + namespace mtx { template @@ -73,6 +75,22 @@ none_of(std::function pred, return !any_of(pred, val, rest...); } +template +boost::optional +first_of(std::function pred, + T const &val) { + return pred(val) ? val : boost::optional{}; +} + +template +boost::optional +first_of(std::function pred, + T const &val, + Trest... rest) { + return pred(val) ? val : first_of(pred, rest...); +} + } #endif // MTX_COMMON_LIST_UTILS_H diff --git a/tests/unit/common/list_utils.cpp b/tests/unit/common/list_utils.cpp index 37732cab7..38b707c2b 100644 --- a/tests/unit/common/list_utils.cpp +++ b/tests/unit/common/list_utils.cpp @@ -6,6 +6,21 @@ namespace { +TEST(ListUtils, first_of) { + EXPECT_FALSE(mtx::first_of([](int val) { return val > 43; }, 42)); + + EXPECT_TRUE(!!mtx::first_of([](int val) { return val > 43; }, 48)); + EXPECT_TRUE(!!mtx::first_of([](int val) { return val > 43; }, 42, 54)); + EXPECT_TRUE(!!mtx::first_of([](int val) { return val > 43; }, 42, 41, 40, 39, 38, 12345)); + + EXPECT_EQ(48, mtx::first_of([](int val) { return val > 43; }, 48)); + EXPECT_EQ(54, mtx::first_of([](int val) { return val > 43; }, 42, 54).get()); + EXPECT_EQ(12345, mtx::first_of([](int val) { return val > 43; }, 42, 41, 40, 39, 38, 12345).get()); + + EXPECT_TRUE(!!mtx::first_of([](void *p) { return !!p; }, static_cast(nullptr), reinterpret_cast(0x12345))); + EXPECT_EQ(reinterpret_cast(0x12345), mtx::first_of([](void *p) { return !!p; }, static_cast(nullptr), reinterpret_cast(0x12345))); +} + TEST(ListUtils, included_in) { EXPECT_TRUE(mtx::included_in(42, 42)); EXPECT_TRUE(mtx::included_in(42, 54, 42, 48));