返回归档

RELOG / ARTICLE

环形缓冲区

修订说明(2026-11):旧示例没有检查剩余空间,跨边界复制时也遗漏了源和目标偏移量。下面补齐边界条件。

TCP 是字节流,接收缓冲区可用来暂存尚未解析的字节,再按应用层包头处理“半包”和一次收到多个包的情况。

如果出现了半包的情况,缓冲区内已经处理过的数据不需要了再处理了,但未被解析的数据需要一次array.copy使未读数据前移,等待下次接收形成完整数据。

环形缓冲区相比于普通缓冲区可以去掉未读数据前移这一步。

环形缓冲区的实现

upgraded/ringbuffer at main · thisred/upgraded (github.com)

环形缓冲区有很多实现,其中我觉得最好的一种就是:记录读总数和写总数,写总数减去读总数就是未读消息长度。写下标和读下标可通过取余得到。

环形缓冲区的写入

向环形缓冲区写入可分为两种情况:

  • 若 WriteIndex + count <= Capacity,写入连续的一段。
  • 否则先写到数组末尾,再从数组开头继续写。写入前必须确认 count <= RemainingLength,不能覆盖尚未读取的数据。

环形缓冲区的读取

从读下标读取时也可能跨越数组末尾,需要分两段复制;读取长度不能超过 DataLength。下面示例假定调用方用同一线程访问,或者自行做好同步。

using System;

public class RingBuffer
{
    private readonly int _capacity;

    /// <summary>
    /// 读总数
    /// </summary>
    private uint _readCount;

    /// <summary>
    /// 写总数
    /// </summary>
    private uint _writeCount;

    /// <summary>
    /// 构造函数,初始化缓冲区,设置缓冲区大小
    /// </summary>
    /// <param name="size">缓冲区大小,必须为2的幂</param>
    public RingBuffer(int size = 8192) : this(new byte[size])
    {
    }


    private RingBuffer(byte[] buffer)
    {
        if (buffer.Length == 0 || (buffer.Length & (buffer.Length - 1)) != 0)
            throw new Exception("数组长度必须为2的幂");

        Array = buffer;
        Capacity = buffer.Length;
        _readCount = 0;
        _writeCount = 0;
    }

    /// <summary>
    /// 缓冲区大小,必须为2的幂
    /// </summary>
    public int Capacity
    {
        get => _capacity;
        private init
        {
            _capacity = value;
            _bufferSizeMask = value - 1;
        }
    }

    private readonly int _bufferSizeMask;

    public byte[] Array { get; }

    /// <summary>
    /// 写下标
    /// </summary>
    public int WriteIndex => (int)(_writeCount & (uint)_bufferSizeMask);

    /// <summary>
    /// 读下标
    /// </summary>
    public int ReadIndex => (int)(_readCount & (uint)_bufferSizeMask);

    /// <summary>
    /// 缓冲区未读数据长度
    /// </summary>
    public int DataLength => unchecked((int)(_writeCount - _readCount));

    /// <summary>
    /// 剩余空间
    /// </summary>
    public int RemainingLength => Capacity - DataLength;

    /// <summary>
    /// 向环形缓冲区中写给定数组
    /// </summary>
    /// <param name="srcBytes">要写入缓冲区的数组</param>
    /// <param name="srcOffset">给定数组的偏移量</param>
    /// <param name="count">写入长度</param>
    public void Write(byte[] srcBytes, int srcOffset, int count)
    {
        if (srcBytes == null) throw new ArgumentNullException(nameof(srcBytes));
        if (srcOffset < 0 || count < 0 || srcOffset > srcBytes.Length - count)
            throw new ArgumentOutOfRangeException();
        if (count > RemainingLength) throw new InvalidOperationException("缓冲区空间不足");

        int first = Math.Min(count, Capacity - WriteIndex);
        System.Buffer.BlockCopy(srcBytes, srcOffset, Array, WriteIndex, first);
        System.Buffer.BlockCopy(srcBytes, srcOffset + first, Array, 0, count - first);

        _writeCount += (uint)count;
    }

    /// <summary>
    ///     读取数据到目标字节数组
    /// </summary>
    /// <param name="destination">目标字节数组</param>
    /// <param name="dstOffset">目标字节数组偏移量</param>
    /// <param name="count">读取长度</param>
    /// <returns>读取长度</returns>
    public void ReadBytes(byte[] destination, int dstOffset, int count)
    {
        if (destination == null) throw new ArgumentNullException(nameof(destination));
        if (dstOffset < 0 || count < 0 || dstOffset > destination.Length - count)
            throw new ArgumentOutOfRangeException();
        if (count > DataLength) throw new InvalidOperationException("可读数据不足");

        int first = Math.Min(count, Capacity - ReadIndex);
        System.Buffer.BlockCopy(Array, ReadIndex, destination, dstOffset, first);
        System.Buffer.BlockCopy(Array, 0, destination, dstOffset + first, count - first);

        _readCount += (uint)count;
    }
}

大致实现就是这样,每次有消息过来就写在缓冲区里,增加写总数,读取就增加读总数,写总数减去读总数就是未读消息大小。

其他

用 uint 计数并按模 2³² 相减,在始终维持 0 <= DataLength <= Capacity 的前提下,计数回绕后仍可得到未读长度。这个简单实现不提供并发读写保证。

缓冲区大小必须为2的幂是因为,写下标和读下标可直接用与运算得到下标值,避免了使用%取余。

读到这里,感谢你。

回到顶部