From 5e4796836c6fcdab8e33af08e4ab5fdb390c71be Mon Sep 17 00:00:00 2001 From: zcy <290198252@qq.com> Date: Wed, 22 Dec 2021 13:44:54 +0800 Subject: [PATCH] no message --- general/src/pattern/ringbuffer.hpp | 80 ++++++++++++++++++++++++++---- test/src/cpp11/template.cpp | 35 +++++++++---- 2 files changed, 95 insertions(+), 20 deletions(-) diff --git a/general/src/pattern/ringbuffer.hpp b/general/src/pattern/ringbuffer.hpp index 1ab22cb..28385db 100644 --- a/general/src/pattern/ringbuffer.hpp +++ b/general/src/pattern/ringbuffer.hpp @@ -10,7 +10,8 @@ public: RingBuffer(uint64_t size); int Add(T *data,uint64_t len); int TakeBack(T *data,uint64_t len); - int Copy(T *data,uint64_t len); + int TakeFront(T *data,uint64_t len); + int CopyBack(T *data,uint64_t len); void SetEmpty(); uint32_t CanReadCount(); @@ -52,9 +53,35 @@ void RingBuffer::SetEmpty(){ } template -int RingBuffer::Copy(T *data,uint64_t len){ +int RingBuffer::CopyBack(T *data,uint64_t len){ if(data == nullptr) return -1; + T *tail = nullptr; + if(m_len == 0) + return 0; + if((m_head + m_len) > m_data_end){ + tail = m_head + m_len - m_size; + }else{ + tail = m_head + m_len - 1; + } + + int i = 0; + for(i = 0;i < len;i++){ + T* tmp = tail; + if(tail > m_data) { + tmp--; + } + if(tail == m_data) { + tmp = m_data_end; + } + // next is head stop + if(tmp == m_head) { + data[i] = (*tail); + break; + } + data[i] = (*tail) ; + tail = tmp; + } } template @@ -122,7 +149,7 @@ int RingBuffer::TakeBack(T *data,uint64_t len){ if((m_head + m_len) > m_data_end){ tail = m_head + m_len - m_size; }else{ - tail = m_head + m_len; + tail = m_head + m_len - 1; } int i = 0; @@ -134,23 +161,58 @@ int RingBuffer::TakeBack(T *data,uint64_t len){ if(tail == m_data) { tmp = m_data_end; } - if(tmp == m_head) { - (*tail) = data[i]; + // next is head stop + if((tmp == m_head) || (m_head == tail)) { + data[len - 1 - i] = (*tail); + break; + } + data[len - 1 - i] = (*tail) ; + tail = tmp; + } + m_len-=i; + return i; +} + +template +int TakeFront(T *data,uint64_t len){ + if(data == nullptr) + return -1; + T *tail = nullptr; + if(m_len == 0) + return 0; + if((m_head + m_len) > m_data_end){ + tail = m_head + m_len - m_size; + }else{ + tail = m_head + m_len - 1; + } + int i = 0; + for(i = 0;i < len;i++){ + T* tmp = m_head; + if(m_head < m_data_end) { + tmp++; + } + if(m_head == m_data_end) { + tmp = m_data; + } + // next is head stop + if((tmp == tail) || (m_head == tail)) { + data[i] = (*tail); break; } data[i] = (*tail) ; - tail = tmp; - } + m_head = tmp; + } + m_len-=i; return i; } template uint32_t RingBuffer::CanReadCount(){ - + return m_len; } template uint32_t RingBuffer::CanWriteCount(){ - + return m_size - m_len; } #endif diff --git a/test/src/cpp11/template.cpp b/test/src/cpp11/template.cpp index 5ce2296..da83727 100644 --- a/test/src/cpp11/template.cpp +++ b/test/src/cpp11/template.cpp @@ -25,61 +25,74 @@ void TestRingBuffer(){ int ret = x.Add(in,512); std::cout<<"add "<