added user-data to the resource

This commit is contained in:
Michele Caini 2016-10-25 18:18:20 +02:00
parent 07aceb1fb8
commit b2ab5187cd
3 changed files with 34 additions and 3 deletions

View File

@ -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<uvw::TcpHandle>();
The line above will create and initialize a tcp handle, thus a shared pointer to that resource will be returned.<br/>
The line above will create and initialize a tcp handle, then a shared pointer to that resource will be returned.<br/>
Users should check if pointers have been correctly initialized: in case of errors, they won't be.<br/>
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.<br/>
Users can set and get them through the `data` member function as it follows:
resource->data(std::make_shared<int>(42));
auto data = std::static_pointer_cast<int>(resource->data());
`uvw` expects a `std::shared_pointer<void>` 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.<br/>
To know what are the handles that are still alive and bound to a given loop, just do the following:

View File

@ -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<void> 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<void> uData) {
userData = std::move(uData);
}
private:
std::shared_ptr<void> userData{nullptr};
std::shared_ptr<void> ptr{nullptr};
std::shared_ptr<Loop> pLoop;
U resource;

View File

@ -1,3 +1,4 @@
#include <memory>
#include <type_traits>
#include <gtest/gtest.h>
#include <uvw.hpp>
@ -14,7 +15,12 @@ TEST(Resource, Basics) {
ASSERT_FALSE(std::is_move_assignable<uvw::AsyncHandle>::value);
auto loop = uvw::Loop::getDefault();
auto handle = loop->resource<uvw::AsyncHandle>();
auto resource = loop->resource<uvw::AsyncHandle>();
ASSERT_NO_THROW(handle->loop());
ASSERT_NO_THROW(resource->loop());
auto data = std::make_shared<int>(42);
ASSERT_NO_THROW(resource->data(data));
ASSERT_EQ(*std::static_pointer_cast<int>(resource->data()), 42);
}