CompletionHandler.h [plain text]
#pragma once
#include <wtf/Function.h>
namespace WTF {
template<typename> class CompletionHandler;
template <typename Out, typename... In>
class CompletionHandler<Out(In...)> {
public:
CompletionHandler() = default;
template<typename CallableType, class = typename std::enable_if<std::is_rvalue_reference<CallableType&&>::value>::type>
CompletionHandler(CallableType&& callable)
: m_function(WTFMove(callable))
{
}
CompletionHandler(CompletionHandler&&) = default;
CompletionHandler& operator=(CompletionHandler&&) = default;
~CompletionHandler()
{
ASSERT_WITH_MESSAGE(!m_function, "Completion handler should always be called");
}
explicit operator bool() const { return !!m_function; }
Out operator()(In... in)
{
ASSERT_WITH_MESSAGE(m_function, "Completion handler should not be called more than once");
return std::exchange(m_function, nullptr)(std::forward<In>(in)...);
}
private:
Function<Out(In...)> m_function;
};
class CompletionHandlerCallingScope {
public:
CompletionHandlerCallingScope() = default;
CompletionHandlerCallingScope(CompletionHandler<void()>&& completionHandler)
: m_completionHandler(WTFMove(completionHandler))
{ }
~CompletionHandlerCallingScope()
{
if (m_completionHandler)
m_completionHandler();
}
CompletionHandlerCallingScope(CompletionHandlerCallingScope&&) = default;
CompletionHandlerCallingScope& operator=(CompletionHandlerCallingScope&&) = default;
CompletionHandler<void()> release() { return WTFMove(m_completionHandler); }
private:
CompletionHandler<void()> m_completionHandler;
};
}
using WTF::CompletionHandler;
using WTF::CompletionHandlerCallingScope;