• 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 #ifndef MSG_HANDLER_H
16 #define MSG_HANDLER_H
17 
18 #include <functional>
19 #include <map>
20 #include <string>
21 
22 #include "proto.h"
23 
24 namespace OHOS {
25 namespace Msdp {
26 namespace DeviceStatus {
27 template<typename K, typename V>
28 class MsgHandler {
29 public:
30     struct MsgCallback {
31         K id;
32         V fun;
33     };
34 
35 public:
Clear()36     void Clear()
37     {
38         callbacks_.clear();
39     }
ChkKey(K id)40     bool ChkKey(K id)
41     {
42         return (GetMsgCallback(id) != nullptr);
43     }
44 
GetDebugInfo()45     const std::string& GetDebugInfo() const
46     {
47         std::string str;
48         for (auto &it : callbacks_) {
49             str += std::to_string(it.first);
50             str += ',';
51         }
52         if (!str.empty()) {
53             str.resize(str.size() - 1);
54         }
55 
56         return std::move(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 it = callbacks_.find(id);
74         if (it == callbacks_.end()) {
75             return nullptr;
76         }
77         return &it->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