Defines a simple XML serializer and serializes an object.
If binary XML was used, the serialized results are more compact than text-based XML. Although the results are in binary, it is still XML, so it has the advantage that it can be made readable by converting it to text-based XML.
The serializer in the sample has the following limitations.
The source code of the sample is shown below.
#include <map>
#include <string>
#include <vector>
#include "./def_serializer.h"
using nlib_ns::exi::ExiAllocator;
struct Coordinate {
float latitude;
float longitude;
template <class Archive>
void serialize(Archive& ar);
Coordinate(float arg_latitude, float arg_longitude) {
latitude = arg_latitude;
longitude = arg_longitude;
}
Coordinate() : latitude(0.f), longitude(0.f) {}
};
class CityInfo {
StdString name;
StdString url;
StdString governor;
int population;
Coordinate coordinate;
public:
template <class Archive>
void serialize(Archive& ar);
int arg_population, const Coordinate& arg_coordinate)
: name(arg_name),
url(arg_url),
governor(arg_governor),
population(arg_population),
coordinate(arg_coordinate) {}
CityInfo() : population(0) {}
void Print() {
ConsoleOutputStream out_;
TextWriter out;
out.Init(&out_);
out.WriteFormat("name: %s\n", M(name.c_str()));
out.WriteFormat("\turl: %s\n", M(url.c_str()));
out.WriteFormat("\tgovernor: %s\n", M(governor.c_str()));
out.WriteFormat("\tpopulation: %d\n", population);
out.WriteFormat("\tcoord: (%f, %f)\n\n", coordinate.latitude, coordinate.longitude);
}
};
template <class Archive>
void Coordinate::serialize(Archive& ar) {
ar& latitude;
ar& longitude;
}
template <class Archive>
void CityInfo::serialize(Archive& ar) {
ar& name;
ar& url;
ar& governor;
ar& population;
ar& coordinate;
}
typedef std::map<StdString, CityInfo> CityDB;
const int BUF_SIZE = 1024 * 128;
unsigned char g_Buf[BUF_SIZE];
struct AllocFinalizer {
~AllocFinalizer() {
ExiAllocator::Finalize();
}
};
bool SampleExec() {
ReallocOutputStream os;
{
SimpleSerializer ser(&os);
CityDB sendData;
CityInfo tokyo(N("Tokyo"), N("http://www.metro.tokyo.jp/"), N("Shintaro Ishihara"),
13186835, Coordinate(35.6894875f, 139.6917064f));
CityInfo kyoto(N("Kyoto"), N("http://www.pref.kyoto.jp/"), N("Keiji Yamada"), 2633795,
Coordinate(35.0212466f, 135.7555968f));
sendData[N("Tokyo")] = tokyo;
sendData[N("Kyoto")] = kyoto;
ser << sendData;
if (!ser.IsSuccess()) {
return false;
}
}
ExiAllocator::Reset();
ReallocOutputStream::UniquePtrType data;
size_t data_size = os.Release(&data);
MemoryInputStream is(&data[0], data_size);
{
SimpleDeserializer deser(&is);
CityDB receiveData;
deser >> receiveData;
if (!deser.IsSuccess()) {
return false;
}
CityDB::iterator it;
for (it = receiveData.begin(); it != receiveData.end(); ++it) {
it->second.Print();
}
}
return true;
}
bool SampleMain(int, char**) {
if (!ExiAllocator::Initialize(g_Buf, BUF_SIZE)) {
return false;
}
bool rval = SampleExec();
ExiAllocator::Finalize();
return rval;
}
NLIB_MAINFUNC