#include "StdAfx.h"
#include "CycleBuffer.h"
#include <assert.h>
#include <memory.h>
#include <vector>
CycleBuffer::CycleBuffer(int capacity)
: capacity_(capacity)
, size_(0)
, head_(0)
, tail_(0)
{
buffer_ = new char[capacity_];
}
CycleBuffer::~CycleBuffer(void)
{
delete[] buffer_;
}
int CycleBuffer::Write(char* src, int len)
{
if (capacity_ - size_ < len)
{
return -1;
}
if (head_ >= tail_)
{
/* == 内存模型 ==
(empty) (data) (empty)
|-------------------|----------------------------|---------------------------|
(left_size) tail_ head_ (right_size)
*/
int right_size = capacity_ - head_;
if (right_size > len)
{
memcpy(buffer_ + head_, src, len);
head_ = head_ + len;
}
else
{
memcpy(buffer_ + head_, src, right_size);
memcpy(buffer_ , src + right_size, len - right_size);
head_ = (head_ + len) % capacity_;
}
size_ = size_ + len;
}
else
{
/* == 内存模型 ==
(data) (empty) (data)
|-------------------|----------------------------|---------------------------|
head_ tail_
*/
int left_size = tail_ - head_;
memcpy(buffer_ + head_, src, len);
head_ = head_ + len;
size_ = size_ + len;
}
return len;
}
int CycleBuffer::Read(char* dst, int len)
{
if (size_ < len)
{
return -1;
}
if (head_ > tail_)
{
/* == 内存模型 ==
(empty) (data) (empty)
|-------------------|----------------------------|---------------------------|
tail_ head_
*/
memcpy(dst, buffer_ + tail_, len);
tail_ += len;
size_ -= len;
}
else
{
/* == 内存模型 ==
(data) (empty) (data)
|-------------------|----------------------------|---------------------------|
(left_size) head_ tail_ (right_size)
*/
int right_size = capacity_ - tail_;
if (right_size >= len)
{
memcpy(dst, buffer_ + tail_, len);
tail_ = tail_ + len;
size_ = size_ - len;
}
else
{
memcpy(dst, buffer_ + tail_, right_size);
memcpy(dst + right_size, buffer_, len - right_size);
tail_ = (tail_ + len) % capacity_;
size_ = size_ - len;
}
}
return len;
}
int CycleBuffer::Copy(char* dst, int len)
{
if (size_ < len)
{
return -1;
}
if (head_ > tail_)
{
/* == 内存模型 ==
(empty) (data) (empty)
|-------------------|----------------------------|---------------------------|
tail_ head_
*/
memcpy(dst, buffer_ + tail_, len);
}
else
{
/* == 内存模型 ==
(data) (empty) (data)
|-------------------|----------------------------|---------------------------|
(left_size) head_ tail_ (right_size)
*/
int right_size = capacity_ - tail_;
if (right_size >= len)
{
memcpy(dst, buffer_ + tail_, len);
}
else
{
memcpy(dst, buffer_ + tail_, right_size);
memcpy(dst + right_size, buffer_, len - right_size);
}
}
return len;
}
int CycleBuffer::Advance(int len)
{
if (size_ < len)
{
return -1;
}
tail_ = (tail_ + len) % capacity_;
size_ = size_ - len;
return len;
}
评论0
最新资源