lichao
2021-04-23 dc86ace85e437ecb8a2e728e4dce36d02bbb8a6e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * =====================================================================================
 *
 *       Filename:  msg.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月24日 16时48分42秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "msg.h"
#include "bh_util.h"
 
namespace bhome_msg
{
/*TODO change msg format, header has proc info;
reply has errer msg
    center accept request and route.;
//*/
const uint32_t kMsgTag = 0xf1e2d3c4;
 
void *MsgI::Alloc(SharedMemory &shm, const size_t size)
{
    void *p = shm.Alloc(sizeof(Meta) + size);
    if (p) {
        auto pmeta = new (p) Meta;
        p = pmeta + 1;
    }
    return p;
}
void MsgI::Free(SharedMemory &shm)
{
    assert(valid());
    shm.Dealloc(meta());
    ptr_ = nullptr;
    assert(!valid());
}
 
void *MsgI::Pack(SharedMemory &shm,
                 const uint32_t head_len, const ToArray &headToArray,
                 const uint32_t body_len, const ToArray &bodyToArray)
{
    void *addr = Alloc(shm, sizeof(head_len) + head_len + sizeof(body_len) + body_len);
    if (addr) {
        auto p = static_cast<char *>(addr);
        auto Pack1 = [&p](auto len, auto &writer) {
            Put32(p, len);
            p += sizeof(len);
            writer(p, len);
            p += len;
        };
        Pack1(head_len, headToArray);
        Pack1(body_len, bodyToArray);
    }
    return addr;
}
 
bool MsgI::ParseHead(BHMsgHead &head) const
{
    auto p = get<char>();
    assert(p);
    uint32_t msg_size = Get32(p);
    p += 4;
    return head.ParseFromArray(p, msg_size);
}
 
bool MsgI::Make(SharedMemory &shm, void *p)
{
    if (!p) {
        return false;
    }
    MsgI(p).swap(*this);
    return true;
}
 
int MsgI::Release(SharedMemory &shm)
{
    if (!valid()) {
        return 0;
    }
    auto n = meta()->count_.Dec();
    if (n == 0) {
        Free(shm);
    }
    return n;
}
 
} // namespace bhome_msg