77 lines
2.3 KiB
C++
77 lines
2.3 KiB
C++
#pragma once
|
|
|
|
#include <vector>
|
|
#include <set>
|
|
#include <unordered_set>
|
|
#include <functional>
|
|
|
|
namespace bts {
|
|
namespace api {
|
|
|
|
template <class T, class TKey>
|
|
class StatefulPublisher {
|
|
const bool _keep_state;
|
|
std::vector<T> _added;
|
|
std::vector<T> _updated;
|
|
std::set<TKey> _erased;
|
|
std::unordered_set<TKey> _state;
|
|
std::map<TKey,T> _state_data;
|
|
typedef std::function<void(std::vector<T>*, std::vector<T>*, std::set<TKey>*)> PublishFn;
|
|
const PublishFn _publish;
|
|
typedef std::function<TKey(T)> KeyFn;
|
|
const KeyFn _key;
|
|
public:
|
|
StatefulPublisher(const PublishFn& fn, const KeyFn& key,bool keep_state=false) :
|
|
_keep_state(keep_state), _added(), _updated(), _erased(), _state(), _state_data(), _publish(fn), _key(key)
|
|
{ }
|
|
|
|
void add_or_update(const T& m) {
|
|
auto key = _key(m);
|
|
if (!_has_key(key)) {
|
|
_added.push_back(m);
|
|
if(_keep_state)
|
|
_state_data[key]=m;
|
|
else
|
|
_state.insert(key);
|
|
}
|
|
else {
|
|
// If an item has already been added update to new value
|
|
auto match = [this,&key](const T& item) { return _key(item) == key; };
|
|
auto add_iter = std::find_if(_added.begin(), _added.end(), match);
|
|
if (add_iter != _added.end()) {
|
|
*add_iter = m;
|
|
}
|
|
else {
|
|
auto update_iter = std::find_if(_updated.begin(), _updated.end(), match);
|
|
if (update_iter == _updated.end()) {
|
|
_updated.push_back(m);
|
|
}
|
|
else {
|
|
*update_iter = m;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
void erase(TKey m) {
|
|
if (_has_key(m)) {
|
|
_erased.insert(m);
|
|
}
|
|
}
|
|
void flush() {
|
|
_publish(&_added, &_updated, &_erased);
|
|
_added.clear();
|
|
_updated.clear();
|
|
_erased.clear();
|
|
}
|
|
const std::map<TKey,T>& state_data() const{
|
|
return _state_data;
|
|
}
|
|
private:
|
|
bool _has_key(TKey k) const{
|
|
return _keep_state ? _state_data.find(k) != _state_data.end() :
|
|
_state.find(k) != _state.end();
|
|
|
|
}
|
|
};
|
|
|
|
}}//namespace
|