-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_set.h
63 lines (50 loc) · 1.43 KB
/
client_set.h
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
#pragma once
#include <unordered_set>
#include <tuple>
#include <string>
#include <mutex>
#include <vector>
using Client = std::tuple<std::string, int>;
namespace std {
template <>
struct hash<Client> {
size_t operator()(const Client& client) const {
return hash<string>()(get<0>(client)) * 31 +
hash<int>()(get<1>(client));
}
};
}
class ClientSet {
public:
using scoped_lock = std::lock_guard<std::mutex>;
ClientSet() {
}
~ClientSet() {
}
bool addClient(const std::string& address, int port) {
return addClient(std::tie(address, port));
}
bool addClient(const Client& client) {
scoped_lock lock(clientsMutex);
return clients.insert(client).second;
}
bool removeClient(const std::string& address, int port) {
return removeClient(std::tie(address, port));
}
bool removeClient(const Client& client) {
scoped_lock lock(clientsMutex);
return clients.erase(client) > 0;
}
std::vector<Client> getClientList() const {
scoped_lock lock(clientsMutex);
std::vector<Client> result;
result.reserve(clients.size());
for (auto i = clients.begin(), ni = clients.end(); i != ni; i++) {
result.push_back(*i);
}
return result;
}
private:
mutable std::mutex clientsMutex;
std::unordered_set<Client> clients;
};