forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetPeerCollection.cs
More file actions
115 lines (104 loc) · 3.06 KB
/
NetPeerCollection.cs
File metadata and controls
115 lines (104 loc) · 3.06 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace LiteNetLib
{
internal sealed class IPEndPointComparer : IEqualityComparer<IPEndPoint>
{
public bool Equals(IPEndPoint x, IPEndPoint y)
{
return x.Equals(y);
}
public int GetHashCode(IPEndPoint obj)
{
return obj.GetHashCode();
}
}
internal sealed class NetPeerCollection
{
private readonly Dictionary<IPEndPoint, NetPeer> _peersDict;
private readonly ReaderWriterLockSlim _lock;
public int Count;
public volatile NetPeer HeadPeer;
public NetPeerCollection()
{
_peersDict = new Dictionary<IPEndPoint, NetPeer>(new IPEndPointComparer());
_lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
public bool TryGetValue(IPEndPoint endPoint, out NetPeer peer)
{
_lock.EnterReadLock();
bool result = _peersDict.TryGetValue(endPoint, out peer);
_lock.ExitReadLock();
return result;
}
public void Clear()
{
_lock.EnterWriteLock();
HeadPeer = null;
_peersDict.Clear();
Count = 0;
_lock.ExitWriteLock();
}
public bool TryAdd(NetPeer peer)
{
_lock.EnterUpgradeableReadLock();
if (_peersDict.ContainsKey(peer.EndPoint))
{
_lock.ExitUpgradeableReadLock();
return false;
}
_lock.EnterWriteLock();
peer.NextPeer = HeadPeer;
if (HeadPeer != null)
{
HeadPeer.PrevPeer = peer;
}
HeadPeer = peer;
_peersDict.Add(peer.EndPoint, peer);
Count++;
_lock.ExitWriteLock();
_lock.ExitUpgradeableReadLock();
return true;
}
public void RemovePeers(List<NetPeer> peersList)
{
if (peersList.Count == 0)
return;
_lock.EnterWriteLock();
for (int i = 0; i < peersList.Count; i++)
{
RemovePeerInternal(peersList[i]);
}
_lock.ExitWriteLock();
}
public void RemovePeer(NetPeer peer)
{
_lock.EnterWriteLock();
RemovePeerInternal(peer);
_lock.ExitWriteLock();
}
private void RemovePeerInternal(NetPeer peer)
{
if (!_peersDict.Remove(peer.EndPoint))
{
return;
}
if (peer == HeadPeer)
{
HeadPeer = peer.NextPeer;
}
if (peer.PrevPeer != null)
{
peer.PrevPeer.NextPeer = peer.NextPeer;
peer.PrevPeer = null;
}
if (peer.NextPeer != null)
{
peer.NextPeer.PrevPeer = peer.PrevPeer;
peer.NextPeer = null;
}
Count--;
}
}
}