#include "watch.hpp" #include namespace watch { namespace { struct Lease { Port& port; int fd; ~Lease() { if (fd >= 0) port.close(fd); } int take() { int value = fd; fd = -1; return value; } }; } Service::Service(Port& port) : port_(port), current_(-1) {} Service::~Service() { stop(); } std::vector Service::normalize(const std::vector& requests) { std::map latest; std::vector order; for (const auto& request : requests) { if (!latest.count(request.key)) order.push_back(request.key); latest[request.key] = request.mask; } std::vector result; for (int key : order) result.push_back(Request{key, latest.at(key)}); return result; } int Service::reload(const std::vector& requests) { if (requests.size() > 16) return invalid; Lease next{port_, port_.open()}; if (next.fd < 0) return next.fd; for (const auto& request : requests) { const int rc = port_.add(next.fd, request.key, request.mask); if (rc < 0) return rc; } const auto normalized = normalize(requests); stop(); current_ = next.take(); configuration_ = normalized; return 0; } int Service::stop() { Lease previous{port_, current_}; current_ = -1; configuration_.clear(); current_watches_.clear(); return 0; } int Service::read(std::size_t capacity, std::vector& output) { return port_.read(current_, capacity, output); } int Service::active() const { return current_; } std::vector Service::configuration() const { return configuration_; } void Service::forget() { current_ = -1; configuration_.clear(); current_watches_.clear(); } }