-
Notifications
You must be signed in to change notification settings - Fork 66
/
StreamBuffer.h
158 lines (137 loc) · 2.36 KB
/
StreamBuffer.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#ifndef _ZJY_STREAMBUFFER_H_
#define _ZJY_STREAMBUFFER_H_
#include <string>
class CReadStream
{
public:
CReadStream(const char *buffer,int len)
:m_bytes(buffer),m_limit(len),m_pos(0)
{
}
size_t LeftBytes()
{
return m_limit- m_pos;
}
void Skip(int step)
{
m_pos+=step;
}
const char *data()
{
return m_bytes;
}
CReadStream &operator >>(int &v)
{
Get(&v,sizeof(v));
v= ntohl(v);
return *this;;
}
CReadStream &operator >>(unsigned int &v)
{
Get(&v,sizeof(v));
v= ntohl(v);
return *this;
}
CReadStream &operator >>(unsigned short &v)
{
Get(&v,sizeof(v));
v= ntohs(v);
return *this;
}
CReadStream &operator >>( std::string &str)
{
int len=0;char c;
(*this)>>len;
while(len--)
{
(*this)>>c;
str+=c;
}
return *this;
}
CReadStream &operator >>( char &c)
{
Get(&c,sizeof(char));
return *this;
}
private:
void Get(void *data,int n)
{
if(m_pos+n>m_limit)
throw "out of range";
memcpy(data,m_bytes+m_pos,n);
m_pos+=n;
}
protected:
const char *m_bytes;
int m_limit;
int m_pos;
};
//ʹÓÃstring,¿ÉÒÔÀûÓÃstlµÄmemory pool
class CWriteStream
{
private:
std::string m_bufer;
public:
CWriteStream()
{
}
int size()const
{
return (int)m_bufer.size();
}
const char *data()const
{
return m_bufer.data();
}
CWriteStream &operator <<(const int &v)
{
int t=htonl(v);
Put(&t,sizeof(t));
return *this;
}
CWriteStream &operator <<(const unsigned int &v)
{
int t=htonl(v);
Put(&t,sizeof(t));
return *this;
}
CWriteStream &operator <<(const unsigned short &v)
{
unsigned short t=htons(v);
Put(&t,sizeof(t));
return *this;
}
//notice!! data not alias of string
CWriteStream &operator <<( const char* data)
{
size_t len = strlen(data);
Put(data,(int)len);
return *this;
}
CWriteStream &operator <<( const std::string &str)
{
(*this)<<(int)str.size();
Put(str.c_str(),int(str.size()));
return *this;
}
CWriteStream &operator <<(const char &c)
{
m_bufer+=c;
return *this;
}
CWriteStream &operator <<(const CWriteStream &c)
{
Put( c.data(), c.size() );
return *this;
}
void Put(const void *data,int n)
{
m_bufer.append((const char*)data,n);
}
void Clear()
{
m_bufer.clear();
}
};
#endif