测试代码添加ringbuffer

master
a7458969 2020-05-15 00:33:41 +08:00
parent b4665a782e
commit 22ad0c7c81
1 changed files with 10 additions and 10 deletions

View File

@ -5,13 +5,13 @@ using namespace std;
template<typename T>
class RingBuffer{
public:
typedef enum Error{
enum Error{
Error = -10,
ERROR_FULL = -11,
ERROR_NO_ENOUGH_WRITE = -12,
};
RingBuffer(uint16_t len){
mBuffer = new[len];
RingBuffer(uint16_t len) {
mBuffer = new T[len];
mHead = mTail = mBuffer;
if (mBuffer == nullptr){
this->mLen = 0;
@ -35,7 +35,7 @@ public:
{
int copy_sz = min(count, this->ReadableCnt());
memcpy(data, mHead, copy_sz * sizeof(T));
rb->rb_head += copy_sz * sizeof(T);
mHead += copy_sz * sizeof(T);
return copy_sz;
}
else // 头部大于尾部
@ -43,8 +43,8 @@ public:
if (count < mLen -(mHead - mBuffer)) // (rb->rb_head - rb->rb_buff) 是从头部到数组物理结束的长度如果小于说明不需要读取数组头部的只需要copy一次
{
int copy_sz = count*sizeof(T);
memcpy(data, rb->rb_head, copy_sz*sizeof(T));
rb->rb_head += copy_sz;
memcpy(data, mHead, copy_sz*sizeof(T));
mHead += copy_sz;
return copy_sz;
}
else
@ -59,14 +59,14 @@ public:
}
}
int16_t Write(const T *in,uint16_t len){
if (len >= WriteableCnt(rb))
if (len >= WriteableCnt())
return ERROR_NO_ENOUGH_WRITE;
if (mHead <= mTail) // 头部小于尾部
{
int tail_avail_sz = mLen - (mTail - this->mBuffer);
if (len <= tail_avail_sz) // 是否需要循环到0开始写
{
memcpy(rb->rb_tail, in, len*sizeof(T));
memcpy(mTail, in, len*sizeof(T));
mTail += len;
if (mTail == mBuffer + mLen) // 刚好相等的情况
mTail = mBuffer;
@ -75,8 +75,8 @@ public:
else
{
memcpy(mTail, in, tail_avail_sz*sizeof(T));
mTail = rb->rb_buff;
return tail_avail_sz + Write(rb, (char*)in + tail_avail_sz, (len - tail_avail_sz)*sizeof(T));
mTail = mBuffer;
return tail_avail_sz + Write( (T*)in + tail_avail_sz* sizeof(T), (len - tail_avail_sz));
}
}
else