From 789e5555ab4c44a1ae779eccf6ccf8340602cf22 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Thu, 26 Jan 2023 20:46:30 +0100 Subject: Websockets: Notify other clients of changes --- connectionregistry.cpp | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 connectionregistry.cpp (limited to 'connectionregistry.cpp') diff --git a/connectionregistry.cpp b/connectionregistry.cpp new file mode 100644 index 0000000..1e48a96 --- /dev/null +++ b/connectionregistry.cpp @@ -0,0 +1,95 @@ +#include "connectionregistry.h" + +#include +#include + +void ConnectionRegistry::setId(ConnectionRegistry::connection c, const std::string& id) +{ + if (!m_connections.at(c).empty()) { + auto& connections_set{m_ids.at(id)}; + connections_set.erase(c); + if (connections_set.empty()) + m_ids.erase(id); + } + + m_connections.at(c) = id; + + if (!id.empty()) { + if (!m_ids.contains(id)) + m_ids[id] = {}; + m_ids.at(id).insert(c); + } + +} + +void ConnectionRegistry::addConnection(ConnectionRegistry::connection c) +{ + if (m_connections.contains(c)) + throw std::runtime_error("ConnectionRegistry::addConnection: connection already exists"); + + m_connections.emplace(c, ""); + + std::cout << "Info: Added connection, now " << m_connections.size() << std::endl; +} + +void ConnectionRegistry::delConnection(ConnectionRegistry::connection c) +{ + if (!m_connections.contains(c)) + throw std::runtime_error("ConnectionRegistry::delConnection: connection doesn't exist"); + + std::string id {m_connections.at(c)}; + + m_connections.erase(c); + + if (!id.empty()) { + auto& connections_set{m_ids.at(id)}; + connections_set.erase(c); + if (connections_set.empty()) + m_ids.erase(id); + } + + std::cout << "Info: Deleted connection, now " << m_connections.size() << std::endl; +} + +std::unordered_set::iterator ConnectionRegistry::begin(const std::string& id) +{ + return m_ids.at(id).begin(); +} + +std::unordered_set::iterator ConnectionRegistry::end(const std::string& id) +{ + return m_ids.at(id).end(); +} + +void ConnectionRegistry::dump() +{ + std::cout << "Connection Registry:" << std::endl; + + std::cout << "Connections: " << std::endl; + for (auto& i: m_connections) { + std::cout << " " << i.first << ": " << i.second << std::endl; + } + + std::cout << "IDs: " << std::endl; + for (auto& i: m_ids) { + std::cout << " " << i.first << ":"; + + for (auto& j: i.second) { + std::cout << " " << j; + } + std::cout << std::endl; + } +} + +ConnectionRegistry::RegistryGuard::RegistryGuard(ConnectionRegistry& registry, ConnectionRegistry::connection c): + m_registry{registry}, + m_connection{c} +{ + m_registry.addConnection(m_connection); +} + +ConnectionRegistry::RegistryGuard::~RegistryGuard() +{ + m_registry.delConnection(m_connection); +} + -- cgit v1.2.3