#ifndef CIRCLEARRAY
#define CIRCLEARRAY
/*
* Created by ssd, 2010.7.14
*
*/
#include <assert.h>
#include <string.h>
template <class T>
class CircleArray
{
private:
unsigned int m_size;
T* m_buffer;
T* m_cur_pos;
public:
CircleArray(unsigned int size):m_size(size),m_cur_pos(0)
{
m_buffer = new T[m_size];
assert(m_buffer != 0);
m_cur_pos = m_buffer;
}
~CircleArray()
{
delete[] m_buffer;
}
T& operator[](unsigned long index)const
{//the index can be very large
unsigned int tmpindex= index % m_size;
return m_buffer[tmpindex];
}
void copyFrom(T* data, unsigned long offset, unsigned int data_size)
{
unsigned int tmpindex1 = offset % m_size;
unsigned int tmpindex2 = tmpindex1 + data_size;
if(tmpindex2 > m_size)
{
tmpindex2 -= m_size;
unsigned int tmpsize = data_size - tmpindex2;
memcpy(m_buffer + tmpindex1, data, tmpsize);
memcpy(m_buffer, data + tmpsize, tmpindex2);
}
else
{
memcpy(m_buffer + tmpindex1, data, data_size);
}
}
};
template <class T>
class BreakedArray
{
private:
T *m_array1;
T *m_array2;
unsigned int m_array1_len;
unsigned int m_array2_len;
unsigned int m_current_pos;
public:
BreakedArray(T* array1,unsigned int len1, T*array2, unsigned int len2):m_array1(array1),
m_array2(array2),
m_array1_len(len1),
m_array2_len(len2),
m_current_pos(0)
{
assert(array1 != 0);
assert((m_array2_len == 0 && m_array2 == 0)||(m_array2_len != 0 && m_array2 != 0));
}
~BreakedArray(){}
bool crossBreakPos(unsigned int index1 ,unsigned int data_size)
{//是否需要拼接
if(index1 < m_array1_len && index1 + data_size > m_array1_len)
return true;
else
return false;
}
void copyTo(T* data, unsigned int index1, unsigned int data_size)
{
assert(index1 < m_array1_len && index1 + data_size > m_array1_len);
unsigned int tmpdatasize = m_array1_len - index1;
memcpy(data, m_array1 + index1, tmpdatasize);
memcpy(data + tmpdatasize, m_array2, data_size - tmpdatasize);
}
T& operator[](unsigned int index)const
{
if(index >= m_array1_len)
{
index -= m_array1_len;
return m_array2[index];
}
else
{
return m_array1[index];
}
}
T * operator+(unsigned int step)
{
m_current_pos += step;
return &(this->operator[](m_current_pos));
}
T* operator++(int)
{
return &(this->operator[](m_current_pos++));
}
T* operator++()
{
return &(this->operator[](++m_current_pos));
}
};
#endif
|