在缓冲区的一头读出数据 在缓冲区的另一头写进数据 根据两头的指针指明当前保存数据的区域 apped方法写进数据 pop方法弹出数据 SBuffer.h #ifndef S_buffer_class #define S_buffer_class #include "ComDefine.h" #define BYTE8 char #define BYTE32 int #define BUFFER_MAX 2048 //最大缓冲区长度 class SBuffer { public: SBuffer(); ~SBuffer(); static SBuffer* instance(); BYTE32 append(const BYTE8* str, BYTE32 len); BYTE32 pop(BYTE8* dst, BYTE32 len); private: BYTE8 m_buffer[BUFFER_MAX]; //开始位置和写入位置只在没有数据的时候可能出现,其他任何情况不可能出现 BYTE32 m_head; //弹出位置 BYTE32 m_tail; //写入位置 private: static SBuffer* m_instance; }; #endif SBuffer.cpp #include "stdafx.h" #include "SBuffer.h" #include <string> #include <assert.h> using namespace std; SBuffer* SBuffer::m_instance = NULL; SBuffer::SBuffer() : m_head(0) , m_tail(0) { memset(m_buffer, 0, sizeof(m_buffer)); } SBuffer::~SBuffer() { } SBuffer* SBuffer::instance() { if (m_instance == NULL) { m_instance = new SBuffer(); } return m_instance; } BYTE32 SBuffer::append(const BYTE8* str, BYTE32 len) { if ( str == NULL ) { return -1; } BYTE8* tmppos; if (m_tail >= m_head) { if (len > BUFFER_MAX - (m_tail - m_head)) { return -1; } BYTE32 totallen = 0; //总长度 BYTE32 headlen = m_head; //头部长度 BYTE32 taillen = BUFFER_MAX - m_tail; //尾部长度 totallen = headlen + taillen; if ( totallen >= len ) //空间足够填充 { tmppos = m_buffer + m_tail; if (taillen >= len) { memcpy( tmppos, str, len ); m_tail += len; } else { memcpy( tmppos, str, taillen ); tmppos = m_buffer; memcpy( tmppos, str + taillen, len - taillen); m_tail = (len - taillen); } } else //尾部超出要填到头部 { return -1; } } else { if (len >= m_head - m_tail) { return -1; } tmppos = m_buffer + m_tail; memcpy(tmppos, str, len); m_tail += len; } return 0; } BYTE32 SBuffer::pop(BYTE8* dst, BYTE32 len) { if ( dst == NULL ) { return -1; } BYTE8* tmppos; if (m_tail > m_head) { if (len > (m_tail - m_head)) { return -1; } tmppos = m_buffer + m_head; memcpy(dst, tmppos, len); m_head += len; } else if (m_tail < m_head) { BYTE32 totallen = 0; //总长度 BYTE32 headlen = BUFFER_MAX - m_head; //头部长度 BYTE32 taillen = m_tail + 1; //尾部长度 totallen = headlen + taillen; if ( len > totallen ) //空间足够填充 { return -2; } tmppos = m_buffer + m_head; if (len <= headlen) { memcpy( dst, tmppos, len ); m_head += len; if (m_head == BUFFER_MAX) { m_head = 0; } assert(BUFFER_MAX >= m_head); } else { memcpy( dst, tmppos, headlen ); tmppos = m_buffer; memcpy( dst + headlen, tmppos, len - headlen); m_head = len - headlen; } } else { return -2; } return 0; }