现在的位置: 首页 > 综合 > 正文

using vector to implement buffer

2019年03月11日 ⁄ 综合 ⁄ 共 1966字 ⁄ 字号 评论关闭

I was told that using vector to implement buffer is applicable, but using string to implement buffer is not applicable, because objects in vector are continuous in memory, while in string it is not guaranteed.

It is peculiar that my following codes test OK in red hat linux, but in SUSE, it leads to coredump. I don't have the chance to investigate in SUSE any more for the time being since I've not a SUSE server at hand.

#include <vector>
#include <iostream>
using namespace std; 

class Buf {
    vector<char> buf;
public:    
    Buf();
    Buf(size_t sz);
    void setSize(size_t sz);
    size_t getSize();
    char* head(); 
    char* head2();
};

Buf::Buf(){
}

Buf::Buf(size_t sz):buf(sz) {
    
}

void Buf::setSize(size_t sz){
    buf.resize(sz);
}

size_t Buf::getSize() {
    return buf.size();
}

char* Buf::head(){
    return &buf[0];
}

char* Buf::head2(){
    return &(*buf.begin());
}

class MessageBuffer
{
public:
    enum {HEAD_SIZE = 4, MAX_MESSAGE_SIZE = 65536};
    MessageBuffer(); 
    char* body();
    char* head();
    void setBodySize(int size);
    int getBodySize();
    int getTotalSize();
private:    
    vector<char> m_buff;
};

MessageBuffer::MessageBuffer() 
{
}

char* MessageBuffer:: body() 
{
    vector<char>::iterator it=m_buff.begin();
    char *begin = &(*it) + HEAD_SIZE;
    return begin;
}

char* MessageBuffer:: head()
{
    vector<char>::iterator it=m_buff.begin();
    char *begin = &(*it) + HEAD_SIZE;
    return begin; 
}

void  MessageBuffer:: setBodySize(int size)
{
    m_buff.resize(size+HEAD_SIZE);
    char *begin = &m_buff[0];
    begin[0]=(size >> 24) & 0xff;
    begin[1]=(size >> 16) & 0xff;
    begin[2]=(size >> 8) & 0xff;
    begin[3]=size  & 0xff;
}

int   MessageBuffer:: getBodySize()
{
    int size;
    char *begin = &m_buff[0];
    size = (begin[0] << 24) |(begin[1] << 16) |(begin[2] << 8) |(begin[3] ) ;
    return size; 
}

int   MessageBuffer:: getTotalSize() 
{
    return getBodySize() + HEAD_SIZE;    
}

int main() {
    //test Buf
    Buf buf(100);
    strcpy(buf.head(),"hello");
    strcpy((buf.head()+5)," world");
    cout << buf.head() << endl;
    strcpy(buf.head2(),"hello");
    strcpy((buf.head2()+5)," world");
    cout << buf.head2() << endl;
    //test MessageBuffer
    MessageBuffer buffer;
    buffer.setBodySize(100);
    cout << buffer.getTotalSize() << endl;
    cout << buffer.getBodySize() << endl;
    strcpy(buffer.body(), "hello");
    strcpy(buffer.body()+5," whole world"); 
    cout << buffer.body() << endl; 
    return 0;
}

 

抱歉!评论已关闭.