forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetPacketPool.cs
More file actions
85 lines (78 loc) · 2.61 KB
/
NetPacketPool.cs
File metadata and controls
85 lines (78 loc) · 2.61 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
using System;
using System.Threading;
namespace LiteNetLib
{
internal sealed class NetPacketPool
{
private readonly NetPacket[] _pool = new NetPacket[NetConstants.PacketPoolSize];
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
private int _count;
public NetPacket GetWithData(PacketProperty property, byte[] data, int start, int length)
{
var packet = GetWithProperty(property, length);
Buffer.BlockCopy(data, start, packet.RawData, NetPacket.GetHeaderSize(property), length);
return packet;
}
public NetPacket GetPacket(int size, bool clear)
{
NetPacket packet = null;
if (size <= NetConstants.MaxPacketSize)
{
_lock.EnterUpgradeableReadLock();
if (_count > 0)
{
_lock.EnterWriteLock();
_count--;
packet = _pool[_count];
_pool[_count] = null;
_lock.ExitWriteLock();
}
_lock.ExitUpgradeableReadLock();
}
if (packet == null)
{
//allocate new packet
packet = new NetPacket(size);
}
else
{
//reallocate packet data if packet not fits
if (!packet.Realloc(size) && clear)
{
//clear in not reallocated
Array.Clear(packet.RawData, 0, size);
}
}
return packet;
}
//Get packet with size
public NetPacket GetWithProperty(PacketProperty property, int size)
{
size += NetPacket.GetHeaderSize(property);
NetPacket packet = GetPacket(size, true);
packet.Property = property;
return packet;
}
public void Recycle(NetPacket packet)
{
if (packet.Size > NetConstants.MaxPacketSize)
{
//Dont pool big packets. Save memory
return;
}
//Clean fragmented flag
packet.RawData[0] = 0;
_lock.EnterUpgradeableReadLock();
if (_count == NetConstants.PacketPoolSize)
{
_lock.ExitUpgradeableReadLock();
return;
}
_lock.EnterWriteLock();
_pool[_count] = packet;
_count++;
_lock.ExitWriteLock();
_lock.ExitUpgradeableReadLock();
}
}
}