c#数据缓存

代码
/// <summary>
    
/// <code>
    
/// byte数组
    
/// 本类实例和socket配对
    
/// 仅用于储存网络缓存数据
    
/// </code>
    
/// </summary>
    public class ByteArray
    {
        
private byte[] m_bytes = new byte[1024];

        
private int m_length = 0;

        
public int Length
        {
            
get { return m_length; }
        }

        
public void AddToEnd(byte[] bytes)
        {
            newBuffer(bytes.Length);
            Buffer.BlockCopy(bytes, 
0, m_bytes, m_length, bytes.Length);
            m_length 
+= bytes.Length;
        }
        
public void AddToEnd(byte[] bytes, int index, int count)
        {
            newBuffer(count);
            Buffer.BlockCopy(bytes, index, m_bytes, m_length, count);
            m_length 
+= count;
        }

        
/// <summary>
        
/// 检查内存是否够用,若不够则开辟新内存
        
/// </summary>
        private void newBuffer(int dataLenght)
        {
            
int addLen = m_length + dataLenght;

            
if (addLen >= m_bytes.Length)//内存不够,开辟新内存
            {
                addLen 
+= addLen % 1024;
                
byte[] newBytes = new byte[addLen];
                Buffer.BlockCopy(m_bytes, 
0, newBytes, 0, m_length);
                m_bytes 
= null;
                m_bytes 
= newBytes;
            }
        }

        
/// <summary>
        
/// 从头开始获取指定长度的数据
        
/// </summary>
        
/// <param name="count"></param>
        
/// <returns></returns>
        public byte[] GetBytesFromBegin(int Offset, int count)
        {
            
byte[] newBytes = new byte[count];
            Buffer.BlockCopy(m_bytes, Offset, newBytes, 
0, count);
            
return newBytes;
        }

        
/// <summary>
        
/// 从开头删除
        
/// </summary>
        public void RemoveFromBegin(int count)
        {
            m_length 
-= count;
            Buffer.BlockCopy(m_bytes, count, m_bytes, 
0, m_length);
        }

        
public byte[] GetAndRemoveFromBegin(int count)
        {
            
byte[] newBytes = GetBytesFromBegin(0, count);
            RemoveFromBegin(count);
            
return newBytes;
        }
    }

 

posted @ 2010-07-01 12:23  风叙  阅读(253)  评论(0)    收藏  举报