#include "durable.hpp" namespace durable { void Domain::trim(Reader &reader) { const auto capacity = static_cast(reader.capacity); while (reader.queue.size() > capacity) { reader.queue.erase(reader.queue.begin()); ++reader.lost; } } void Domain::deliver(Reader &reader, const Sample &sample) { reader.queue.push_back(sample); ++reader.received; trim(reader); } void Domain::broadcast(const Sample &sample) { for (auto &item : readers_) { Reader &reader = item.second; if (reader.topic == sample.topic) { deliver(reader, sample); } } } int Domain::open_reader(int id, int topic, int durability, int capacity) { const int result = reader_arguments(id, topic, durability, capacity); if (result != 0) { return result; } if (readers_.find(id) != readers_.end()) { return -17; } Reader reader; reader.id = id; reader.topic = topic; reader.durability = durability; reader.capacity = capacity; reader.received = 0; reader.taken = 0; reader.lost = 0; if (durability == 1) { const auto samples = histories_.replay(topic); for (const Sample &sample : samples) { deliver(reader, sample); } } readers_.emplace(id, std::move(reader)); return 0; } int Domain::close_reader(int id) { auto found = readers_.find(id); if (found == readers_.end()) { return -2; } readers_.erase(found); return 0; } int Domain::set_capacity(int id, int capacity) { auto found = readers_.find(id); if (found == readers_.end()) { return -2; } if (!valid_capacity(capacity)) { return -22; } Reader &reader = found->second; reader.capacity = capacity; trim(reader); return 0; } int Domain::peek(int id, std::vector &out) const { const auto found = readers_.find(id); if (found == readers_.end()) { return -2; } const Reader &reader = found->second; std::vector result; result.reserve(reader.queue.size()); for (const Sample &sample : reader.queue) { result.push_back(sample); } out.swap(result); return 0; } int Domain::take(int id, int count, std::vector &out) { auto found = readers_.find(id); if (found == readers_.end()) { return -2; } if (count < 0 || count > 64) { return -22; } Reader &reader = found->second; const auto amount = std::min(static_cast(count), reader.queue.size()); std::vector result; result.reserve(amount); auto current = reader.queue.begin(); for (std::size_t index = 0; index < amount; ++index) { result.push_back(*current); ++current; } reader.queue.erase(reader.queue.begin(), current); reader.taken += static_cast(amount); out.swap(result); return 0; } int Domain::clear(int id) { auto found = readers_.find(id); if (found == readers_.end()) { return -2; } Reader &reader = found->second; reader.lost += static_cast(reader.queue.size()); reader.queue.clear(); return 0; } }