forked from compilelife/feiq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparcelable.h
More file actions
145 lines (119 loc) · 2.5 KB
/
parcelable.h
File metadata and controls
145 lines (119 loc) · 2.5 KB
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
141
142
143
144
145
#ifndef PARCELABLE_H
#define PARCELABLE_H
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Parcel
{
private:
class Head
{
public:
Head(int size)
{
this->size = size;
}
Head(istream& ss)
{
read(ss);
}
int size;
void myWriteInt(ostream& os, int val)
{
char buf[9] = {0};
snprintf(buf, sizeof(buf), "%08d", val);
os<<buf;
}
int myReadInt(istream& is)
{
char buf[9] = {0};
is.read(buf, sizeof(buf)-1);
return stoi(buf);
}
void write(ostream& os){
myWriteInt(os, size);
}
void read(istream& is){
size = myReadInt(is);
}
};
public:
template<typename T>
void write(const T& val){
writePtr(&val, 1);
}
template<typename T>
void read(T& val){
readPtr(&val);
}
template<typename T>
void writePtr(const T* ptr, int n){
Head head{(int)(n * sizeof(T))};
head.write(ss);
ss.write((const char*)ptr, head.size);
}
template<typename T>
void readPtr(T* ptr){
Head head(ss);
unique_ptr<char[]> buf(new char[head.size]);
ss.read(buf.get(), head.size);
memcpy(ptr, buf.get(), head.size);
}
void writeString(const string& val)
{
writePtr(val.c_str(), val.length());
}
void readString(string& val)
{
auto size = nextSize();
unique_ptr<char[]> buf(new char[size+1]);
readPtr(buf.get());
buf[size]=0;
val=buf.get();
}
void resetForRead()
{
ss.seekg(0, ss.beg);
}
void fillWith(const void* data, int len)
{
ss.clear();
ss.write(static_cast<const char*>(data), len);
}
public:
streampos mark()
{
return ss.tellg();
}
void unmark(streampos markPos)
{
ss.seekg(markPos);
}
public:
vector<char> raw()
{
auto size = ss.tellp();
resetForRead();
vector<char> buf(size);
ss.read(buf.data(), size);
return buf;
}
private:
int nextSize()
{
auto pos = mark();
Head head(ss);
unmark(pos);
return head.size;
}
private:
stringstream ss;
};
class Parcelable
{
public:
virtual void writeTo(Parcel& out) const =0;
virtual void readFrom(Parcel& in) =0;
};
#endif // PARCELABLE_H