protorpc.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // flags
  13. *p++ = head->flags;
  14. // hton length
  15. unsigned int length = head->length;
  16. *p++ = (length >> 24) & 0xFF;
  17. *p++ = (length >> 16) & 0xFF;
  18. *p++ = (length >> 8) & 0xFF;
  19. *p++ = length & 0xFF;
  20. // memcpy body
  21. if (msg->body && head->length) {
  22. memcpy(p, msg->body, head->length);
  23. }
  24. return packlen;
  25. }
  26. int protorpc_unpack(protorpc_message* msg, const void* buf, int len) {
  27. if (!msg || !buf || !len) return -1;
  28. if (len < PROTORPC_HEAD_LENGTH) return -2;
  29. protorpc_head* head = &(msg->head);
  30. const unsigned char* p = (const unsigned char*)buf;
  31. // flags
  32. head->flags = *p++;
  33. // ntoh length
  34. head->length = ((unsigned int)*p++) << 24;
  35. head->length |= ((unsigned int)*p++) << 16;
  36. head->length |= ((unsigned int)*p++) << 8;
  37. head->length |= *p++;
  38. // Check is buffer enough
  39. unsigned int packlen = protorpc_package_length(head);
  40. if (len < packlen) {
  41. return -3;
  42. }
  43. // NOTE: just shadow copy
  44. if (len > PROTORPC_HEAD_LENGTH) {
  45. msg->body = (const char*)buf + PROTORPC_HEAD_LENGTH;
  46. }
  47. return packlen;
  48. }