From b2ab5187cda0dc586af36b8ee5ec98f0219ad084 Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Tue, 25 Oct 2016 18:18:20 +0200 Subject: [PATCH] added user-data to the resource --- README.md | 10 +++++++++- src/uvw/resource.hpp | 17 +++++++++++++++++ test/uvw/resource.cpp | 10 ++++++++-- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5b41bdaa..505c62e5 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ In order to create a resource and to bind it to the given loop, just do the foll auto tcp = loop.resource(); -The line above will create and initialize a tcp handle, thus a shared pointer to that resource will be returned.
+The line above will create and initialize a tcp handle, then a shared pointer to that resource will be returned.
Users should check if pointers have been correctly initialized: in case of errors, they won't be.
Another way to create a resource is: @@ -156,6 +156,14 @@ Another way to create a resource is: Pretty annoying indeed. Using a loop is the recommended approach. +The resources also accept arbitrary user-data that won't be touched in any case.
+Users can set and get them through the `data` member function as it follows: + + resource->data(std::make_shared(42)); + auto data = std::static_pointer_cast(resource->data()); + +`uvw` expects a `std::shared_pointer` and returns it, thus any kind of data is welcome. + Remember from the previous section that a handle will keep itself alive until one invokes the `close` member method on it.
To know what are the handles that are still alive and bound to a given loop, just do the following: diff --git a/src/uvw/resource.hpp b/src/uvw/resource.hpp index 3803f863..decd14b6 100644 --- a/src/uvw/resource.hpp +++ b/src/uvw/resource.hpp @@ -85,7 +85,24 @@ public: */ Loop& loop() const noexcept { return *pLoop; } + /** + * @brief Gets user-defined data. `uvw` won't use this field in any case. + * @return User-defined data if any, an invalid pointer otherwise. + */ + std::shared_ptr data() const { + return userData; + } + + /** + * @brief Sets arbitrary data. `uvw` won't use this field in any case. + * @param uData User-defined arbitrary data. + */ + void data(std::shared_ptr uData) { + userData = std::move(uData); + } + private: + std::shared_ptr userData{nullptr}; std::shared_ptr ptr{nullptr}; std::shared_ptr pLoop; U resource; diff --git a/test/uvw/resource.cpp b/test/uvw/resource.cpp index 2a66d221..8878f4bb 100644 --- a/test/uvw/resource.cpp +++ b/test/uvw/resource.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -14,7 +15,12 @@ TEST(Resource, Basics) { ASSERT_FALSE(std::is_move_assignable::value); auto loop = uvw::Loop::getDefault(); - auto handle = loop->resource(); + auto resource = loop->resource(); - ASSERT_NO_THROW(handle->loop()); + ASSERT_NO_THROW(resource->loop()); + + auto data = std::make_shared(42); + + ASSERT_NO_THROW(resource->data(data)); + ASSERT_EQ(*std::static_pointer_cast(resource->data()), 42); }