-
-
Notifications
You must be signed in to change notification settings - Fork 203
/
resource.hpp
66 lines (54 loc) · 1.59 KB
/
resource.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef UVW_RESOURCE_INCLUDE_H
#define UVW_RESOURCE_INCLUDE_H
#include <memory>
#include <utility>
#include "config.h"
#include "emitter.h"
#include "uv_type.hpp"
namespace uvw {
/**
* @brief Common class for almost all the resources available in `uvw`.
*
* This is the base class for handles and requests.
*/
template<typename T, typename U, typename... E>
class resource: public uv_type<U>, public emitter<T, E...>, public std::enable_shared_from_this<T> {
protected:
int leak_if(int err) noexcept {
if(err == 0) {
self_ptr = this->shared_from_this();
}
return err;
}
void self_reset() noexcept {
self_ptr.reset();
}
bool has_self() const noexcept {
return static_cast<bool>(self_ptr);
}
public:
explicit resource(loop::token token, std::shared_ptr<loop> ref)
: uv_type<U>{token, std::move(ref)} {
this->raw()->data = this;
}
/**
* @brief Gets user-defined data. `uvw` won't use this field in any case.
* @return User-defined data if any, an invalid pointer otherwise.
*/
template<typename R = void>
std::shared_ptr<R> data() const {
return std::static_pointer_cast<R>(user_data);
}
/**
* @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) {
user_data = std::move(udata);
}
private:
std::shared_ptr<void> user_data{nullptr};
std::shared_ptr<void> self_ptr{nullptr};
};
} // namespace uvw
#endif // UVW_RESOURCE_INCLUDE_H