48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
#pragma once
|
|
|
|
#include <vector>
|
|
#include <set>
|
|
#include <functional>
|
|
|
|
namespace bts {
|
|
namespace api {
|
|
|
|
template <class T, class TKey>
|
|
class StatefulPublisher {
|
|
std::vector<T> _added;
|
|
std::vector<T> _updated;
|
|
std::set<TKey> _erased;
|
|
std::set<TKey> _state;
|
|
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) :
|
|
_added(), _updated(), _erased(), _state(), _publish(fn), _key(key)
|
|
{ }
|
|
|
|
void add_or_update(const T& m) {
|
|
auto key = _key(m);
|
|
if (_state.find(key) == _state.end()) {
|
|
_added.push_back(m);
|
|
_state.insert(key);
|
|
}
|
|
else {
|
|
_updated.push_back(m);
|
|
}
|
|
}
|
|
void erase(TKey m) {
|
|
if (_state.find(m) != _state.end()) {
|
|
_erased.insert(m);
|
|
}
|
|
}
|
|
void flush() {
|
|
_publish(&_added, &_updated, &_erased);
|
|
_added.clear();
|
|
_updated.clear();
|
|
_erased.clear();
|
|
}
|
|
};
|
|
|
|
}}//namespace
|