| 1 |
#ifndef HV_PROTO_RPC_H_ |
| 2 |
#define HV_PROTO_RPC_H_ |
| 3 |
|
| 4 |
#include <string.h> |
| 5 |
|
| 6 |
#ifdef __cplusplus |
| 7 |
extern "C" { |
| 8 |
#endif |
| 9 |
|
| 10 |
#define PROTORPC_NAME "HRPC" |
| 11 |
#define PROTORPC_VERSION 1 |
| 12 |
|
| 13 |
// protocol:4bytes + version:1byte + flags:1byte + reserved:2bytes + length:4bytes = 12bytes |
| 14 |
#define PROTORPC_HEAD_LENGTH 12 |
| 15 |
#define PROTORPC_HEAD_LENGTH_FIELD_OFFSET 8 |
| 16 |
#define PROTORPC_HEAD_LENGTH_FIELD_BYTES 4 |
| 17 |
typedef struct { |
| 18 |
unsigned char protocol[4]; |
| 19 |
unsigned char version; |
| 20 |
unsigned char flags; |
| 21 |
unsigned char reserved[2]; |
| 22 |
unsigned int length; |
| 23 |
} protorpc_head; |
| 24 |
|
| 25 |
typedef const char* protorpc_body; |
| 26 |
|
| 27 |
typedef struct { |
| 28 |
protorpc_head head; |
| 29 |
protorpc_body body; |
| 30 |
} protorpc_message; |
| 31 |
|
| 32 |
static inline unsigned int protorpc_package_length(const protorpc_head* head) { |
| 33 |
return PROTORPC_HEAD_LENGTH + head->length; |
| 34 |
} |
| 35 |
|
| 36 |
static inline void protorpc_head_init(protorpc_head* head) { |
| 37 |
// protocol = HRPC |
| 38 |
memcpy(head->protocol, PROTORPC_NAME, 4); |
| 39 |
head->version = PROTORPC_VERSION; |
| 40 |
head->reserved[0] = head->reserved[1] = 0; |
| 41 |
head->length = 0; |
| 42 |
} |
| 43 |
|
| 44 |
static inline void protorpc_message_init(protorpc_message* msg) { |
| 45 |
protorpc_head_init(&msg->head); |
| 46 |
msg->body = NULL; |
| 47 |
} |
| 48 |
|
| 49 |
static inline int protorpc_head_check(protorpc_head* head) { |
| 50 |
if (memcmp(head->protocol, PROTORPC_NAME, 4) != 0) { |
| 51 |
return -1; |
| 52 |
} |
| 53 |
if (head->version != PROTORPC_VERSION) { |
| 54 |
return -2; |
| 55 |
} |
| 56 |
return 0; |
| 57 |
} |
| 58 |
|
| 59 |
// @retval >0 package_length, <0 error |
| 60 |
int protorpc_pack(const protorpc_message* msg, void* buf, int len); |
| 61 |
// @retval >0 package_length, <0 error |
| 62 |
int protorpc_unpack(protorpc_message* msg, const void* buf, int len); |
| 63 |
|
| 64 |
#ifdef __cplusplus |
| 65 |
} // extern "C" |
| 66 |
#endif |
| 67 |
|
| 68 |
#endif // HV_PROTO_RPC_H_ |