rework GetClient to use new ForEachClient, return shared_ptr

this simplifies a lot of functions, and removes a lot of potential
errors when using the function. You now only check whether the return
value is null, and if it's not, you have a valid, reference-counted,
client pointer.
This commit is contained in:
Lion Kortlepel
2022-11-13 13:36:04 +01:00
parent 844b64f5d9
commit 2f85c708c5
5 changed files with 51 additions and 63 deletions

View File

@@ -136,20 +136,14 @@ int TClient::SecondsSinceLastPing() {
return int(seconds);
}
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClientWeak([&](std::weak_ptr<TClient> CPtr) -> bool {
ReadLock Lock(Server.GetClientMutex());
try {
auto C = CPtr.lock();
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
} catch (const std::exception&) {
// ignore
std::shared_ptr<TClient> GetClient(TServer& Server, int ID) {
std::shared_ptr<TClient> Result {};
Server.ForEachClient([&](const auto& Client) {
if (Client->GetID() == ID) {
Result = Client;
return Break;
}
return true;
return Continue;
});
return MaybeClient;
return Result;
}