c1_unity/Assets/Scripts/Common/Network/TCPService/TCPConnection.BufferPool.cs
2023-04-03 11:04:31 +08:00

122 lines
2.5 KiB
C#

using System;
using System.IO;
namespace BF
{
internal partial class TCPConnection
{
private NetSafeQueue<BFNetBuffer> freeBufferPool;
private void InitializeBufferPools()
{
freeBufferPool = new NetSafeQueue<BFNetBuffer>(16);
}
public BFNetBuffer CreateNetBuffer()
{
if (freeBufferPool.Count <= 0)
{
return new BFNetBuffer(64);
}
freeBufferPool.TryDequeue(out var buffer);
return buffer;
}
public void RecycleNetBuffer(BFNetBuffer buffer)
{
if (freeBufferPool.Contains(buffer))
{
return;
}
buffer.Reset();
freeBufferPool.Enqueue(buffer);
}
}
internal class BFNetBuffer
{
private byte[] data;
private int position;
private int length;
/// <summary>
/// 当前位置
/// </summary>
public int Position => position;
/// <summary>
/// 当前数据长度
/// </summary>
public int Length => length;
/// <summary>
/// buffer 总大小
/// </summary>
public int Capacity => data.Length;
public BFNetBuffer(int capacity)
{
data = new byte[capacity];
Reset();
}
public void Reset()
{
position = 0;
length = 0;
}
public byte[] ToArray()
{
byte[] array = new byte[length];
Array.Copy(data, 0, array, 0, length);
return array;
}
public void SetPosition(int position)
{
if (position > length || position < 0)
{
throw new ArgumentOutOfRangeException();
}
this.position = position;
}
public void Write(byte[] data, int index, int size)
{
if (this.Capacity - position < size)
{
Array.Resize(ref this.data, size + position);
}
Array.Copy(data, index, this.data, position, size);
length = position + size;
}
public byte[] Read(int size)
{
if (length - position < size)
{
throw new ArgumentOutOfRangeException();
}
byte[] array = new byte[size];
Array.Copy(data, position, array, 0, size);
return array;
}
}
}