• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 MSG_HANDLER_H
17 #define MSG_HANDLER_H
18 
19 #include <functional>
20 #include <map>
21 #include <string>
22 
23 #include "devicestatus_proto.h"
24 
25 namespace OHOS {
26 namespace Msdp {
27 namespace DeviceStatus {
28 template<typename K, typename V>
29 class MsgHandler {
30 public:
31     struct MsgCallback {
32         K id;
33         V fun;
34     };
35 
36 public:
Clear()37     void Clear()
38     {
39         callbacks_.clear();
40     }
CheckKey(K id)41     bool CheckKey(K id)
42     {
43         return (GetMsgCallback(id) != nullptr);
44     }
45 
GetDebugInfo()46     std::string GetDebugInfo() const
47     {
48         std::string str;
49         for (auto &iter : callbacks_) {
50             str += std::to_string(iter.first);
51             str += ',';
52         }
53         if (str.size() > 0) {
54             str.resize(str.size() - 1);
55         }
56         return str;
57     }
58 
RegisterEvent(MsgCallback & msg)59     bool RegisterEvent(MsgCallback& msg)
60     {
61         auto it = callbacks_.find(msg.id);
62         if (it != callbacks_.end()) {
63             return false;
64         }
65         callbacks_[msg.id] = msg.fun;
66         return true;
67     }
68 
69 protected:
70     virtual ~MsgHandler() = default;
GetMsgCallback(K id)71     V *GetMsgCallback(K id)
72     {
73         auto iter = callbacks_.find(id);
74         if (iter == callbacks_.end()) {
75             return nullptr;
76         }
77         return &iter->second;
78     }
79 
80 protected:
81     std::map<K, V> callbacks_;
82 };
83 } // namespace DeviceStatus
84 } // namespace Msdp
85 } // namespace OHOS
86 #endif // MSG_HANDLER_H
87