I m writing server with streaming protocol, so I need to do things like find end of header, copy it and then parse other stuff in boost buffer. As I found out the best way for manipulation with strings (find string in it, copy/delete using iterators and so on) is std::string. But I m using char array buffer. So I ll need to have two buffers - char array and std::string - every time I ll need to manipulate with buffer I ll need to convert char array to std::string, do my stuff and then convert it back to char array using std::string.c_str(). Another way I found is use streambuf (as I asked in my previous questition) and then create istream/ostream to it and fill content from it to std::string (as showed in documentation).
With streambuf I ll need :
streambuf
mutable_buffers_type
istream
ostream
and std::string
But with use of char array and std::string I need just :
char array
std::string
所以我认为使用streambuf是浪费内存(我需要为每个连接创建缓冲区)。我可以使用std::string作为boost缓冲区吗?然而,我认为可能有更好的方法来做到这一点。你能给我一个建议吗?
编辑:
我需要对我的缓冲区做这样的事情,但char数组不提供std::string(erase,substr,…)等功能,所以我需要使用std::string作为缓冲区。将其用作boost::buffer的最佳方式是什么,或者像这样解析代码的最佳方式又是什么?
#include <iostream>
int main(int argc, char* argv[])
{
//"header" is header
//"end" is marking that this point is end of header
//"data" is data after header
//this all is sent in one packet which I receive to buffer
//I need to fill "headerend" to std::string header and then remove "headerend" from begining of buffer
//then continue parsing "data" which stay in buffer
std::string buffer = "headerenddata"; //I receive something like this
std::string header; //here I ll fill header (including mark of end of header)
//find end of header and include also mark of end of header which is "end" (+3)
int endOfHeader = int(buffer.find("end"))+3;
//fill header from buffer to string header
header = buffer.substr(0, endOfHeader);
//delete header from input buffer and keep data in it for next parsing
buffer.erase(buffer.begin(), buffer.begin()+endOfHeader);
//will be just "data" becouse header and mark of header are removed
std::cout << buffer << std::endl;
//will be "headerend" which is "header" and mark end of header which is "end"
std::cout << header << std::endl;
return 0;
}