protorpc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "protorpc.h"
  2. #include <string.h> // import memcpy
  3. int protorpc_pack(const protorpc_message* msg, void* buf, int len) {
  4. if (!msg || !buf || !len) return -1;
  5. const protorpc_head* head = &(msg->head);
  6. unsigned int packlen = protorpc_package_length(head);
  7. // Check is buffer enough
  8. if (len < packlen) {
  9. return -2;
  10. }
  11. unsigned char* p = (unsigned char*)buf;
  12. *p++ = head->protocol[0];
  13. *p++ = head->protocol[1];
  14. *p++ = head->protocol[2];
  15. *p++ = head->protocol[3];
  16. *p++ = head->version;
  17. *p++ = head->flags;
  18. *p++ = head->reserved[0];
  19. *p++ = head->reserved[1];
  20. // hton length
  21. unsigned int length = head->length;
  22. *p++ = (length >> 24) & 0xFF;
  23. *p++ = (length >> 16) & 0xFF;
  24. *p++ = (length >> 8) & 0xFF;
  25. *p++ = length & 0xFF;
  26. // memcpy body
  27. if (msg->body && head->length) {
  28. memcpy(p, msg->body, head->length);
  29. }
  30. return packlen;
  31. }
  32. int protorpc_unpack(protorpc_message* msg, const void* buf, int len) {
  33. if (!msg || !buf || !len) return -1;
  34. if (len < PROTORPC_HEAD_LENGTH) return -2;
  35. protorpc_head* head = &(msg->head);
  36. const unsigned char* p = (const unsigned char*)buf;
  37. head->protocol[0] = *p++;
  38. head->protocol[1] = *p++;
  39. head->protocol[2] = *p++;
  40. head->protocol[3] = *p++;
  41. head->version = *p++;
  42. head->flags = *p++;
  43. head->reserved[0] = *p++;
  44. head->reserved[1] = *p++;
  45. // ntoh length
  46. head->length = ((unsigned int)*p++) << 24;
  47. head->length |= ((unsigned int)*p++) << 16;
  48. head->length |= ((unsigned int)*p++) << 8;
  49. head->length |= *p++;
  50. // Check is buffer enough
  51. unsigned int packlen = protorpc_package_length(head);
  52. if (len < packlen) {
  53. return -3;
  54. }
  55. // NOTE: just shadow copy
  56. if (len > PROTORPC_HEAD_LENGTH) {
  57. msg->body = (const char*)buf + PROTORPC_HEAD_LENGTH;
  58. }
  59. return packlen;
  60. }