-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpacket.h
124 lines (92 loc) · 2.66 KB
/
packet.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
/*
* packet.h
*
* Created on: 2011-11-23
* Author: gxl2007@hotmail.com
*/
#ifndef PACKET_H_
#define PACKET_H_
#include <stdint.h>
#include <endian.h>
#include <byteswap.h>
namespace xlnet
{
# if __BYTE_ORDER == __BIG_ENDIAN
#define hton_int16(x) (x)
#define hton_int32(x) (x)
#define hton_int64(x) (x)
#define ntoh_int16(x) (x)
#define ntoh_int32(x) (x)
#define ntoh_int64(x) (x)
#else
#define hton_int16(x) bswap_16(x)
#define hton_int32(x) bswap_32(x)
#define hton_int64(x) bswap_64(x)
#define ntoh_int16(x) bswap_16(x)
#define ntoh_int32(x) bswap_32(x)
#define ntoh_int64(x) bswap_64(x)
#endif
#define MAX_PACKET_SIZE (4194304)
class packet
{
public:
virtual ~packet() { } ;
/*
* @brief get type , implemented by concrete class
* @return object type
*/
virtual int get_type() = 0 ;
/*
* @brief encode object to buffer , implemented by concrete class
* @param [in] buffer position
* @param [in] max buffer size
* @return actual encoded size , -1 on failure
*/
virtual int encode(char* data, int max_size) = 0 ;
/*
* @brief decode object from buffer , implemented by concrete class
* @param [in] buffer position
* @param [in] buffer size
* @return actual decoded size , -1 on failure
*/
virtual int decode(const char* data, int size) = 0 ;
/*
* @brief get needed buffer size of encoding , implemented by concrete class
* @return needed buffer size , include header size, -1 on failure
*/
virtual int encode_size() = 0 ;
/*
* @brief get needed size of decoding , implemented by concrete class
* @param [in] buffer position
* @param [in] buffer size
* @return actual encoded size , -1 on failure
*/
virtual int decode_size(const char* data, int size) = 0 ;
};
struct packet_info
{
int pay_size ; // payload size, exclude header size
const char* data ;
};
class packet_factory
{
public:
virtual ~packet_factory() { } ;
/*
* @brief get packet info , implemented by concrete class
* @param [in] buffer pointer
* @param [in] buffer size
* @param [out] packet info
* @return 0 on success , -1 on failure
*/
virtual int get_info(const char* data, int size, packet_info* pi) = 0 ;
/*
* @brief create packet , implemented by concrete class
* @param [in] packet data
* @param [in] packet info
* @return 0 on success , -1 on failure
*/
virtual packet* create(const char* data, const packet_info* pi) = 0 ;
};
}
#endif /* PACKET_H_ */