/
serialize.h
140 lines (130 loc) · 2.53 KB
/
serialize.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <sstream>
#include <cpplib/cpplib#gsock>
using namespace std;
/** Templates */
template<typename T>
string serialize(const T& a)
{
return T::serialize(a);
}
template<typename T>
int deserialize(string str,T& a)
{
return T::deserialize(str,a);
}
/** Special Version
* For...
* int, double, float
*/
/// int
template<>
string serialize(const int& a)
{
string ans;
int c=htonl(a);
ans.append((const char*)&c,sizeof(c));
return ans;
}
template<>
int deserialize(string str,int& c)
{
memcpy(&c,str.data(),sizeof(c));
c=ntohl(c);
return sizeof(c);
}
/// string
template<>
string serialize(const string& a)
{
int len=a.size();
string ans;
ans.append(::serialize(len));
ans.append(a);
return ans;
}
template<>
int deserialize(string str,string& a)
{
int len;
::deserialize(str,len);
a=str.substr(sizeof(len),len);
return sizeof(int)+len;
}
/// Marco definition
#define NORMAL_DATA_SERIALIZE(Type) template<> \
string serialize(const Type& a) \
{ \
string ans; \
ans.append((const char*)&a,sizeof(a)); \
return ans; \
}
#define NORMAL_DATA_DESERIALIZE(Type) template<> \
int deserialize(string str,Type& a)\
{ \
memcpy(&a,str.data(),sizeof(a)); \
return sizeof(a); \
}
/// double
NORMAL_DATA_SERIALIZE(double);
NORMAL_DATA_DESERIALIZE(double);
NORMAL_DATA_SERIALIZE(float);
NORMAL_DATA_DESERIALIZE(float);
NORMAL_DATA_SERIALIZE(char);
NORMAL_DATA_DESERIALIZE(char);
template<typename SerializableType>
class Serializable
{
public:
static SerializableType deserialize(string);
static string serialize(const SerializableType& a);
};
class OutEngine
{
public:
template<typename SerializableType>
OutEngine& operator << (SerializableType& a)
{
string x=::serialize(a);
os.write(x.data(),x.size());
return *this;
}
string str()
{
return os.str();
}
void set_empty()
{
os.str("");
}
OutEngine():os(std::ios::binary){}
public:
ostringstream os;
};
class InEngine
{
public:
InEngine(string s) : is(s){n_size=leftsize();}
template<typename SerializableType>
InEngine& operator >> (SerializableType& a)
{
int ret=::deserialize(is,a);
is=is.substr(ret);
return *this;
}
void set_str(string s)
{
is=s;
n_size=leftsize();
}
int leftsize()
{
return is.size();
}
int donesize()
{
return n_size-leftsize();
}
protected:
string is;
int n_size;
};