我前面有讲到关于C++各种基础数据和自定义复合类型的序列化与反序化,并且开源了一个库DSMarshal,这个库的压包缓冲是仿std::string实现的,其容量可根据压入数据的大小按块实现预分配,默认情况下块大小为4K,即一个内存页的大小。但是考虑到有些程序员兄弟有洁癖行为,比如我就喜欢轻量化的东西,于是我又基于std::string做压包缓冲,实现了一个序列化版本,大家可以到https://github.com/kdjie/dsmarshal下找到其实现。
例子:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
// 引用头文件
#include "simplemarshal.h"
int main(int argc, char* argv[])
{
using namespace dakuang;
std::string strName = "abc123";
int nAge = 20;
std::vector<std::string> vecBooks;
vecBooks.push_back("a");
vecBooks.push_back("b");
vecBooks.push_back("c");
SimplePack pack;
pack << strName << nAge << vecBooks;
SimpleUnpack unpack(pack.data(), pack.size());
std::string strName2;
int nAge2;
std::vector<std::string> vecBooks2;
unpack >> strName2 >> nAge2 >> vecBooks2;
return 0;
}
上面的例子采用了流式操作,如果不习惯的话,可以使用方法名代替,如下:
std::string strName = "abc123";
int nAge = 20;
std::vector<std::string> vecBooks;
vecBooks.push_back("a");
vecBooks.push_back("b");
vecBooks.push_back("c");
SimplePack pack;
pack.push_string(strName.data(), strName.size());
pack.push_uint32((uint32_t)nAge);
marshal_container(pack, vecBooks);
SimpleUnpack unpack(pack.data(), pack.size());
std::string strName2;
int nAge2;
std::vector<std::string> vecBooks2;
strName2 = unpack.pop_string();
nAge2 = (int)unpack.pop_uint32();
unmarshal_container(unpack, std::back_inserter(vecBooks2));