From 941fb1349b5a9320c5ae283de1a295de148cd87e Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Tue, 9 Jul 2019 13:58:44 +0200 Subject: [PATCH] added cache::each (close #275) --- src/entt/resource/cache.hpp | 35 +++++++++++++++++++++++++++++++++ test/entt/resource/resource.cpp | 26 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/src/entt/resource/cache.hpp b/src/entt/resource/cache.hpp index 4fc9c85fa..ecf5fc09e 100644 --- a/src/entt/resource/cache.hpp +++ b/src/entt/resource/cache.hpp @@ -195,6 +195,41 @@ public: } } + /** + * @brief Iterates all resources. + * + * The function object is invoked for each element. It is provided with + * either the resource identifier, the resource handle or both of them.
+ * The signature of the function must be equivalent to one of the following + * forms: + * + * @code{.cpp} + * void(const resource_type); + * void(resource_handle); + * void(const resource_type, resource_handle); + * @endcode + * + * @tparam Func Type of the function object to invoke. + * @param func A valid function object. + */ + template + void each(Func func) const { + auto begin = resources.begin(); + auto end = resources.end(); + + while(begin != end) { + auto curr = begin++; + + if constexpr(std::is_invocable_v) { + func(curr->first); + } else if constexpr(std::is_invocable_v>) { + func(resource_handle{ curr->second }); + } else { + func(curr->first, resource_handle{ curr->second }); + } + } + } + private: container_type resources; }; diff --git a/test/entt/resource/resource.cpp b/test/entt/resource/resource.cpp index aff0c8491..9c6f24e05 100644 --- a/test/entt/resource/resource.cpp +++ b/test/entt/resource/resource.cpp @@ -108,3 +108,29 @@ TEST(Resource, MutableHandle) { ASSERT_EQ(cache.handle(hs)->value, 4); } + +TEST(Resource, Each) { + entt::resource_cache cache; + cache.load("resource"_hs, 0); + + cache.each([](entt::resource_handle res) { + ++res->value; + }); + + ASSERT_FALSE(cache.empty()); + ASSERT_EQ(cache.handle("resource"_hs)->value, 1); + + cache.each([](auto id, auto res) { + ASSERT_EQ(id, "resource"_hs); + ++res->value; + }); + + ASSERT_FALSE(cache.empty()); + ASSERT_EQ(cache.handle("resource"_hs)->value, 2); + + cache.each([&cache](entt::resource_cache::resource_type id) { + cache.discard(id); + }); + + ASSERT_TRUE(cache.empty()); +}