2013-12-23 23:01:13 +01:00
|
|
|
/**
|
|
|
|
|
******************************************************************************
|
|
|
|
|
* Xenia : Xbox 360 Emulator Research Project *
|
|
|
|
|
******************************************************************************
|
|
|
|
|
* Copyright 2013 Ben Vanik. All rights reserved. *
|
|
|
|
|
* Released under the BSD license - see LICENSE in the root for more details. *
|
|
|
|
|
******************************************************************************
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
#ifndef ALLOY_DELEGATE_H_
|
|
|
|
|
#define ALLOY_DELEGATE_H_
|
|
|
|
|
|
|
|
|
|
#include <functional>
|
2014-07-10 07:28:51 +02:00
|
|
|
#include <mutex>
|
2014-05-14 07:20:42 +02:00
|
|
|
#include <vector>
|
2013-12-23 23:01:13 +01:00
|
|
|
|
|
|
|
|
#include <alloy/core.h>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace alloy {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// TODO(benvanik): go lockfree, and don't hold the lock while emitting.
|
|
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
|
class Delegate {
|
|
|
|
|
public:
|
|
|
|
|
typedef std::function<void(T&)> listener_t;
|
|
|
|
|
|
|
|
|
|
void AddListener(listener_t const& listener) {
|
2014-07-10 07:28:51 +02:00
|
|
|
std::lock_guard<std::mutex> guard(lock_);
|
2013-12-23 23:01:13 +01:00
|
|
|
listeners_.push_back(listener);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void RemoveListener(listener_t const& listener) {
|
2014-07-10 07:28:51 +02:00
|
|
|
std::lock_guard<std::mutex> guard(lock_);
|
2013-12-23 23:01:13 +01:00
|
|
|
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
|
|
|
|
|
if (it == listener) {
|
|
|
|
|
listeners_.erase(it);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void RemoveAllListeners() {
|
2014-07-10 07:28:51 +02:00
|
|
|
std::lock_guard<std::mutex> guard(lock_);
|
2013-12-23 23:01:13 +01:00
|
|
|
listeners_.clear();
|
|
|
|
|
}
|
|
|
|
|
|
2014-07-10 07:28:51 +02:00
|
|
|
void operator()(T& e) {
|
|
|
|
|
std::lock_guard<std::mutex> guard(lock_);
|
2013-12-23 23:01:13 +01:00
|
|
|
for (auto &listener : listeners_) {
|
|
|
|
|
listener(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private:
|
2014-07-10 07:28:51 +02:00
|
|
|
std::mutex lock_;
|
2013-12-23 23:01:13 +01:00
|
|
|
std::vector<listener_t> listeners_;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} // namespace alloy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#endif // ALLOY_DELEGATE_H_
|