lichao
2021-03-26 d17450bd7bc9fd5e98e8e2f00999caffe2e301a6
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
/*
 * =====================================================================================
 *
 *       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"
 
namespace bhome_shm {
    
 
bool MsgMetaV1::Parse(const void *p)
{
    assert(p);
    *this = *static_cast<const MsgMetaV1*>(p);
    return tag_ == kMsgMetaTag;
}
 
void MsgMetaV1::Pack(void *p)
{
    *static_cast<MsgMetaV1*>(p) = *this;
}
 
bool Msg::Build(SharedMemory &shm, const MQId &src_id, const void *data, const size_t size, const bool refcount)
{
    if (!data || !size) {
        return false;
    }
    void *p = shm.Alloc(sizeof(MsgMetaV1) + size);
    if (!p) {
        return false;
    }
    RefCount *rc = 0;
    if (refcount) {
        rc = shm.New<RefCount>();
        if (!rc) {
            shm.Dealloc(p);
            return false;
        }
    }
    MsgMetaV1 meta;
    meta.data_size_ = size;
    meta.src_id_ = src_id;
    meta.Pack(p);
    memcpy(static_cast<char *>(p) + sizeof(meta), data, size);
    Msg(p, rc).swap(*this);
    return true;
 
}
 
int Msg::Release(SharedMemory &shm) 
{
    if (IsCounted()) {
        const int n = count_->Dec();
        if (n != 0) {
            return n;
        }
    }
    // free data
    shm.Dealloc(ptr_);
    ptr_ = 0;
    shm.Delete(count_);
    count_ = 0;
    return 0;
}
 
} // namespace bhome_shm