//vbuffer_char.hpp
//vov
#ifndef V_BUFFER_CHAR_HPP
#define V_BUFFER_CHAR_HPP
#include <iostream>
#include <vector>
#include <cstring>
#define BUFFER_CAPACITY (16000)
class vBufferChar
{
std::vector<char> buffer_;
int data_size_;
public:
vBufferChar();
vBufferChar(int size);
~vBufferChar();
int read(char* data,int size);
void write(const char* data,int size);
//get size of storge data
int size();
//get size of buffer
int capacity();
private:
//copy constructor
vBufferChar(const vBufferChar& t) {}
//assignment constructor
vBufferChar& operator=(const vBufferChar& t) {}
int GetFromBeg(char* data,int size);
void DelFromBeg(int size);
void AddFromEnd(const char* data,int size);
};
//public
vBufferChar::vBufferChar() {
buffer_=std::vector<char>(BUFFER_CAPACITY,0);
data_size_=0;
}
vBufferChar::vBufferChar(int size) {
buffer_=std::vector<char>((size>0)?size:BUFFER_CAPACITY,0);
data_size_=0;
}
vBufferChar::~vBufferChar() {
}
int vBufferChar::size() {
return data_size_;
}
int vBufferChar::capacity() {
return buffer_.size();
}
int vBufferChar::read(char* data,int size) {
if(!data || size<=0) {
return 0;
}
int read_size=GetFromBeg(data,size);
if(read_size>0) {
DelFromBeg(read_size);
}
return read_size;
}
void vBufferChar::write(const char* data,int size) {
if(!data || size<=0) {
return;
}
if(size <=(buffer_.size()-data_size_)) {
AddFromEnd(data,size);
return;
}
if(size>=buffer_.size()) {
std::cout<<"[vBufferChar]write:loss data-1:"<<data_size_+(size-buffer_.size())<<std::endl;
DelFromBeg(data_size_);
AddFromEnd(data+(size-buffer_.size()),buffer_.size());
return;
}
if((size>(buffer_.size()-data_size_)) && (size <buffer_.size())) {
std::cout<<"[vBufferChar]write:loss data-2:"<<size-(buffer_.size()-data_size_)<<std::endl;
DelFromBeg(size-(buffer_.size()-data_size_));
AddFromEnd(data,size);
return;
}
}
//private
int vBufferChar::GetFromBeg(char* data,int size) {
if(size<=0) {
return 0;
}
int size_can_read=(size<data_size_)?size:data_size_;
memcpy(data,buffer_.data(),size_can_read);
return size_can_read;
}
void vBufferChar::DelFromBeg(int size) {
if(size<=0) {
return;
}
int size_delete=(size<data_size_)?size:data_size_;
data_size_-=size_delete;
memcpy(buffer_.data(),buffer_.data()+size_delete,data_size_);
return;
}
void vBufferChar::AddFromEnd(const char* data,int size) {
if(size<=0||size>(buffer_.size()-data_size_)) {
return;
}
memcpy(buffer_.data()+data_size_,data,size);
data_size_+=size;
}
#endif