WIP: safer callbacks

This commit is contained in:
Michele Caini 2016-06-23 18:53:10 +02:00
parent f7a131c8c5
commit ffec57ec93
2 changed files with 20 additions and 13 deletions

View File

@ -12,8 +12,10 @@ namespace uvw {
class Check final: public Resource<Check> { class Check final: public Resource<Check> {
static void startCallback(uv_check_t* h) { static Check* startCallback(uv_check_t* h) {
static_cast<Check*>(h->data)->startCb(UVWError{}); Check *check = static_cast<Check*>(h->data);
check->startCb(UVWError{});
return check;
} }
explicit Check(std::shared_ptr<Loop> ref) explicit Check(std::shared_ptr<Loop> ref)
@ -29,12 +31,14 @@ public:
} }
void start(std::function<void(UVWError)> cb) noexcept { void start(std::function<void(UVWError)> cb) noexcept {
using UVCB = UVCallback<uv_check_t*>;
auto func = UVCB::get<Check, &startCallback>(this);
startCb = std::move(cb); startCb = std::move(cb);
get<uv_check_t>()->data = this; auto err = uv_check_start(get<uv_check_t>(), func);
auto err = uv_check_start(get<uv_check_t>(), &startCallback);
if(err) { if(err) {
startCb(UVWError{err}); startCb(UVWError{err});
reset();
} }
} }

View File

@ -14,8 +14,10 @@ namespace uvw {
class Timer final: public Resource<Timer> { class Timer final: public Resource<Timer> {
static void proto(uv_timer_t* h) { static Timer* startCallback(uv_timer_t* h) {
static_cast<Timer*>(h->data)->callback(UVWError{}); Timer *timer = static_cast<Timer*>(h->data);
timer->startCb(UVWError{});
return timer;
} }
explicit Timer(std::shared_ptr<Loop> ref) explicit Timer(std::shared_ptr<Loop> ref)
@ -26,20 +28,21 @@ class Timer final: public Resource<Timer> {
public: public:
using Time = std::chrono::duration<uint64_t, std::milli>; using Time = std::chrono::duration<uint64_t, std::milli>;
using Callback = std::function<void(UVWError)>;
template<typename... Args> template<typename... Args>
static std::shared_ptr<Timer> create(Args&&... args) { static std::shared_ptr<Timer> create(Args&&... args) {
return std::shared_ptr<Timer>{new Timer{std::forward<Args>(args)...}}; return std::shared_ptr<Timer>{new Timer{std::forward<Args>(args)...}};
} }
void start(const Time &timeout, const Time &rep, Callback cb) noexcept { void start(const Time &timeout, const Time &rep, std::function<void(UVWError)> cb) noexcept {
callback = std::move(cb); using UVCB = UVCallback<uv_timer_t*>;
get<uv_timer_t>()->data = this; auto func = UVCB::get<Timer, &startCallback>(this);
auto err = uv_timer_start(get<uv_timer_t>(), &proto, timeout.count(), rep.count()); startCb = std::move(cb);
auto err = uv_timer_start(get<uv_timer_t>(), func, timeout.count(), rep.count());
if(err) { if(err) {
callback(UVWError{err}); startCb(UVWError{err});
reset();
} }
} }
@ -51,7 +54,7 @@ public:
explicit operator bool() { return initialized; } explicit operator bool() { return initialized; }
private: private:
Callback callback; std::function<void(UVWError)> startCb;
bool initialized; bool initialized;
}; };