using System; using System.IO; namespace BF { internal partial class TCPConnection { private NetSafeQueue freeBufferPool; private void InitializeBufferPools() { freeBufferPool = new NetSafeQueue(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; /// /// 当前位置 /// public int Position => position; /// /// 当前数据长度 /// public int Length => length; /// /// buffer 总大小 /// 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; } } }