Debian Codegraph @

third-party/libhv-v1.3.3/examples/protorpc/protorpc.c

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