ringbuffer添加copy接口

master
zcy 2021-05-18 00:05:39 +08:00
parent fd1e17400d
commit 7fb4970834
2 changed files with 45 additions and 1 deletions

View File

@ -17,7 +17,14 @@ class LockfreeList
int lock; int lock;
int unlock; int unlock;
public: public:
LockfreeList():mutex(0),lock(0),unlock(1){}; LockfreeList():
mutex(0),
lock(0),
unlock(1)
{
};
~LockfreeList(){}; ~LockfreeList(){};
void Lock() void Lock()
{ {

View File

@ -13,6 +13,8 @@ public:
RingBuffer(uint64_t size); RingBuffer(uint64_t size);
int Add(T *data,uint64_t len); int Add(T *data,uint64_t len);
int Take(T *data,uint64_t len); int Take(T *data,uint64_t len);
int Copy(T *data,uint64_t len);
void SetEmpty(); void SetEmpty();
uint32_t CanReadCount(); uint32_t CanReadCount();
uint32_t CanWriteCount(); uint32_t CanWriteCount();
@ -48,12 +50,47 @@ template<typename T>
RingBuffer<T>::~RingBuffer(){ RingBuffer<T>::~RingBuffer(){
delete[] mData; delete[] mData;
} }
template<typename T> template<typename T>
void RingBuffer<T>::SetEmpty(){ void RingBuffer<T>::SetEmpty(){
this->mCurrentHead = this->mCurrentTail; this->mCurrentHead = this->mCurrentTail;
this->mRemain = this->mSize; this->mRemain = this->mSize;
} }
template<typename T>
int RingBuffer<T>::Copy(T *data,uint64_t len){
if(data == nullptr)
return -1;
if(mRemain == mSize)
return 0;
int bytes_read = 0;
if(len > (mSize - mRemain)){
bytes_read = mSize - mRemain;
}else{
bytes_read = len;
}
/// |start|head|.....|tail|end|
if(mCurrentTail >= mCurrentHead){
memcpy(data,&mData[mCurrentHead],sizeof(T)*bytes_read);
return bytes_read;
}
/// |start|...|tail|.....|head|...|end|
if(mCurrentHead > mCurrentTail){
int off = mCurrentHead + bytes_read;
if(off > mSize){
int tmp = mSize - mCurrentHead;
memcpy(data,&mData[mCurrentHead],(mSize - mCurrentHead)*sizeof(T));
memcpy(&data[mSize - mCurrentHead],&mData[0],(bytes_read - tmp)*sizeof(T));
return bytes_read;
}
if(off <= mSize){
memcpy(data,&mData[mCurrentHead],sizeof(T)*bytes_read);
return bytes_read;
}
}
}
template<typename T> template<typename T>
uint32_t RingBuffer<T>::Size(){ uint32_t RingBuffer<T>::Size(){
return mSize; return mSize;