Files
spark/src/lib/api/public/StatefulPublisher.h
T

105 lines
3.2 KiB
C++

#pragma once
#include <functional>
#include <set>
#include <unordered_set>
#include <vector>
#include <map>
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) {
// there is an assumption that we are not dealing with that within a
// transaction, add_or_update and erase is called just once a key
if (_has_key(m)) {
_erased.insert(m);
if (_keep_state)
_state_data.erase(m);
else
_state.erase(m);
}
}
void flush() {
_publish(&_added, &_updated, &_erased);
_added.clear();
_updated.clear();
_erased.clear();
}
const std::map<TKey, T> &state_data() const { return _state_data; }
const std::unordered_set<TKey> &keys() { return _state; }
// Given a new state, and the keys of the previous state, returns the newly
// added rows, the changed rows and the deleted keys
static void diff(
const std::map<TKey, T> &new_state,
const std::unordered_set<TKey> &prev_state,
std::vector<T const *> &added,
std::vector<T const *> &updated,
std::vector<TKey> &deleted) {
for (const auto &kv : new_state) {
if (prev_state.find(kv.first) == prev_state.end())
added.push_back(&kv.second);
else
updated.push_back(&kv.second);
}
for (const auto &k : prev_state)
if (new_state.find(k) == new_state.end())
deleted.push_back(k);
}
private:
bool _has_key(TKey k) const {
return _keep_state ? _state_data.find(k) != _state_data.end()
: _state.find(k) != _state.end();
}
};
} // namespace api
} // namespace bts