/* * This file is part of aasdk library project. * Copyright (C) 2018 f1x.studio (Michal Szwaj) * * aasdk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * aasdk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with aasdk. If not, see . */ #pragma once #include #include #include #include namespace aasdk { namespace io { template class PromiseLink: public std::enable_shared_from_this> { public: typedef std::shared_ptr> Pointer; typedef std::function TransformFunctor; PromiseLink(typename Promise::Pointer promise, TransformFunctor transformFunctor) : promise_(std::move(promise)) , transformFunctor_(std::make_shared(std::move(transformFunctor))) { } static void forward(Promise& source, typename Promise::Pointer destination, TransformFunctor transformFunctor = [](SourceResolveArgumentType&& argument) { return std::move(argument); }) { auto link = std::make_shared>(std::forward::Pointer>(destination), std::forward(transformFunctor)); source.then(link->getResolveHandler(), link->getRejectHandler()); } private: using std::enable_shared_from_this>::shared_from_this; void resolve(SourceResolveArgumentType argument) { if(transformFunctor_ != nullptr) { promise_->resolve((*transformFunctor_)(std::move(argument))); transformFunctor_.reset(); } } void reject(const error::Error& e) { promise_->reject(e); } typename Promise::ResolveHandler getResolveHandler() { return std::bind(&PromiseLink::resolve, this->shared_from_this(), std::placeholders::_1); } typename Promise::RejectHandler getRejectHandler() { return std::bind(&PromiseLink::reject, this->shared_from_this(), std::placeholders::_1); } typename Promise::Pointer promise_; std::shared_ptr transformFunctor_; }; template<> class PromiseLink: public std::enable_shared_from_this> { public: typedef std::shared_ptr> Pointer; PromiseLink(typename Promise::Pointer promise) : promise_(std::move(promise)) { } static void forward(Promise& source, typename Promise::Pointer destination) { auto link = std::make_shared>(std::forward::Pointer>(destination)); source.then(link->getResolveHandler(), link->getRejectHandler()); } private: using std::enable_shared_from_this>::shared_from_this; void resolve() { promise_->resolve(); } void reject(const error::Error& e) { promise_->reject(e); } Promise::ResolveHandler getResolveHandler() { return std::bind(&PromiseLink::resolve, this->shared_from_this()); } Promise::RejectHandler getRejectHandler() { return std::bind(&PromiseLink::reject, this->shared_from_this(), std::placeholders::_1); } typename Promise::Pointer promise_; }; } }