jsonrpc.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "jsonrpc.h"
  2. #include <string.h> // import memcpy
  3. int jsonrpc_pack(const jsonrpc_message* msg, void* buf, int len) {
  4. if (!msg || !buf || !len) return -1;
  5. const jsonrpc_head* head = &(msg->head);
  6. unsigned int packlen = jsonrpc_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. memcpy(p, msg->body, head->length);
  22. return packlen;
  23. }
  24. int jsonrpc_unpack(jsonrpc_message* msg, const void* buf, int len) {
  25. if (!msg || !buf || !len) return -1;
  26. if (len < JSONRPC_HEAD_LENGTH) return -2;
  27. jsonrpc_head* head = &(msg->head);
  28. const unsigned char* p = (const unsigned char*)buf;
  29. // flags
  30. head->flags = *p++;
  31. // ntoh length
  32. head->length = ((unsigned int)*p++) << 24;
  33. head->length |= ((unsigned int)*p++) << 16;
  34. head->length |= ((unsigned int)*p++) << 8;
  35. head->length |= *p++;
  36. // Check is buffer enough
  37. unsigned int packlen = jsonrpc_package_length(head);
  38. if (len < packlen) {
  39. return -3;
  40. }
  41. // NOTE: just shadow copy
  42. msg->body = (const char*)buf + JSONRPC_HEAD_LENGTH;
  43. return packlen;
  44. }