protorpc.h 1.7 KB

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