https://www.cnblogs.com/java-ssl-xy/p/7868531.html

https://blog.csdn.net/chen19870707/article/details/39899743?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

若x是2的n次幂

x&(x-1)  等价于 x%2  ----x对2取模

y%(x-1) 等价于 y%x  ----y对x取模

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TollStationCaptureAlgorithm.Server
{
    class FifoCache
    {
        public const uint _size = 4194304;//缓存大小 2^22
        private byte[] _buffer;//缓存
        public DateTime _lastPutTime;//上次存入缓存的时间
        private uint _in;//in 节点
        private uint _out;//out 节点

        public FifoCache()
        {
            _buffer = new byte[_size];
            _in = 0;
            _out = 0;
        }

        public uint Put(byte[] buf)
        {
            return Put(buf, (uint)buf.Length);
        }

        public uint Put(byte[] buf, uint len)
        {
            return Put(buf, 0, len);
        }

        public uint Put(byte[] buf, int start, uint len)
        {
            lock (this)
            {
                _lastPutTime = DateTime.Now;
                len = (uint)Math.Min(len, _size - _in + _out);
                uint l = (uint)Math.Min(len, _size - (_in & (_size - 1)));//_in & (_size - 1)等价于_in % size,因为size为2的整数次幂
                Array.Copy(buf, start, _buffer, _in & (_size - 1), len);
                Array.Copy(buf, start + l, _buffer, 0, len - l);
                _in += len;
                return len;
            }
        }

        public uint Get(byte[] buf)
        {
            return Get(buf, (uint)buf.Length);
        }

        public uint Get(byte[] buf, uint len)
        {
            return Get(buf, 0, len);
        }

        public uint Get(byte[] buf, int start, uint len)
        {
            lock (this)
            {
                len = (uint)Math.Min(len, _in - _out);
                uint l = (uint)Math.Min(len, _size - (_out & (_size - 1)));
                Array.Copy(_buffer, _out & (_size - 1), buf, start, l);
                Array.Copy(_buffer, start, buf, start + l, len - l);
                _out += len;
                return len;
            }
        }

        public void Clear()
        {
            _in = 0;
            _out = 0;
            _lastPutTime = DateTime.Now;
        }

        public uint Size()
        {
            return _in - _out;
        }

    }
}

 

posted on 2021-02-08 14:45  Manuel  阅读(67)  评论(0编辑  收藏  举报