• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef SHARE_MEMORY_BLOCK_H
17 #define SHARE_MEMORY_BLOCK_H
18 
19 #ifndef NO_PROTOBUF
20 #include "google/protobuf/message.h"
21 #endif
22 #include <cstdint>
23 #include <functional>
24 #include <map>
25 #include <pthread.h>
26 #include <string>
27 
28 class ShareMemoryBlock {
29 public:
30     ShareMemoryBlock(const std::string& name, uint32_t size);
31     ShareMemoryBlock(const std::string& name, uint32_t size, int fd);
32     ~ShareMemoryBlock();
33 
34     bool PutRaw(const int8_t* data, uint32_t size);
35 #ifndef NO_PROTOBUF
36     bool PutMessage(const google::protobuf::Message& pmsg);
37 #endif
38     using DataHandler = std::function<bool(const int8_t*, uint32_t)>;
39     bool TakeData(const DataHandler& func);
40 
41     std::string GetName();
42     uint32_t GetSize();
43     int GetfileDescriptor();
44 
45     bool Valid() const;
46 
47     enum ReusePolicy {
48         DROP_NONE, // buffer满时,不丢弃老数据,不放入新数据
49         DROP_OLD,  // buffer满时,丢弃最老的数据
50     };
SetReusePolicy(enum ReusePolicy dt)51     void SetReusePolicy(enum ReusePolicy dt)
52     {
53         reusePloicy_ = dt;
54     }
55 
56 private:
57     int8_t* GetFreeMemory(uint32_t size);
58     bool UseFreeMemory(int8_t* pmem, uint32_t size);
59 
60     uint32_t GetDataSize();
61     const int8_t* GetDataPoint();
62     bool Next();
63 
64     struct BlockHeader {
65         struct alignas(sizeof(uintptr_t)) {
66             uint32_t writeOffset_;
67             uint32_t readOffset_;
68             uint32_t memorySize_;
69             pthread_mutex_t mutex_;
70             uint32_t bytesCount_;
71             uint32_t chunkCount_;
72         } info;
73         int8_t data[0];
74     };
75 
76     ShareMemoryBlock();
77     int8_t* GetCurrentFreeMemory(uint32_t size);
78 
79     bool CreateBlock(std::string name, uint32_t size);
80     bool CreateBlockWithFd(std::string name, uint32_t size, int fd);
81     bool ReleaseBlock();
82 
83     int fileDescriptor_;
84     void* memoryPoint_;
85     uint32_t memorySize_;
86     std::string memoryName_;
87 
88     BlockHeader* header_;
89     ReusePolicy reusePloicy_;
90 };
91 
92 #endif
93