summaryrefslogtreecommitdiffhomepage
path: root/connectionregistry.cpp
blob: 1e48a964578e684d5469c4141aafe8e2d6d384ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "connectionregistry.h"

#include <iostream>
#include <utility>

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<ConnectionRegistry::connection>::iterator ConnectionRegistry::begin(const std::string& id)
{
 return m_ids.at(id).begin();
}

std::unordered_set<ConnectionRegistry::connection>::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);
}