tdesktop/Telegram/SourceFiles/rpl/lifetime.h

91 lines
2.2 KiB
C
Raw Normal View History

/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "base/unique_function.h"
2019-04-17 09:40:54 +00:00
#include <vector>
namespace rpl {
namespace details {
template <typename Type>
inline Type take(Type &value) {
return std::exchange(value, Type{});
}
} // namespace details
class lifetime {
public:
lifetime() = default;
lifetime(lifetime &&other);
lifetime &operator=(lifetime &&other);
2019-04-17 09:40:54 +00:00
~lifetime() { destroy(); }
template <typename Destroy, typename = decltype(std::declval<Destroy>()())>
lifetime(Destroy &&destroy);
explicit operator bool() const { return !_callbacks.empty(); }
template <typename Destroy, typename = decltype(std::declval<Destroy>()())>
void add(Destroy &&destroy);
void add(lifetime &&other);
void destroy();
template <typename Type, typename... Args>
Type *make_state(Args&& ...args) {
2019-04-17 09:40:54 +00:00
const auto result = new Type(std::forward<Args>(args)...);
add([=] {
static_assert(sizeof(Type) > 0, "Can't delete unknown type.");
2017-11-21 11:59:18 +00:00
delete result;
});
return result;
}
private:
2019-04-17 09:40:54 +00:00
std::vector<base::unique_function<void()>> _callbacks;
};
inline lifetime::lifetime(lifetime &&other)
: _callbacks(details::take(other._callbacks)) {
}
inline lifetime &lifetime::operator=(lifetime &&other) {
std::swap(_callbacks, other._callbacks);
other.destroy();
return *this;
}
template <typename Destroy, typename>
inline lifetime::lifetime(Destroy &&destroy) {
_callbacks.emplace_back(std::forward<Destroy>(destroy));
}
template <typename Destroy, typename>
inline void lifetime::add(Destroy &&destroy) {
2019-04-17 09:40:54 +00:00
_callbacks.emplace_back(std::forward<Destroy>(destroy));
}
inline void lifetime::add(lifetime &&other) {
auto callbacks = details::take(other._callbacks);
_callbacks.insert(
2019-04-17 09:40:54 +00:00
_callbacks.end(),
std::make_move_iterator(callbacks.begin()),
std::make_move_iterator(callbacks.end()));
}
inline void lifetime::destroy() {
2019-04-17 09:40:54 +00:00
auto callbacks = details::take(_callbacks);
for (auto i = callbacks.rbegin(), e = callbacks.rend(); i != e; ++i) {
(*i)();
}
}
} // namespace rpl