1 /*
2  * Copyright (c) 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 #include "callback_manager.h"
17 
18 #include <map>
19 #include <mutex>
20 
21 #include "iam_logger.h"
22 #include "nocopyable.h"
23 
24 #define LOG_TAG "USER_AUTH_SDK"
25 
26 namespace OHOS {
27 namespace UserIam {
28 namespace UserAuth {
29 class CallbackManagerImpl final : public CallbackManager, public NoCopyable {
30 public:
31     void AddCallback(uintptr_t key, CallbackAction &action) override;
32     void RemoveCallback(uintptr_t key) override;
33     void OnServiceDeath() override;
34 
35 private:
36     friend class CallbackManager;
37     CallbackManagerImpl() = default;
38     ~CallbackManagerImpl() override = default;
39     std::mutex mutex_;
40     std::map<uintptr_t, CallbackAction> callbackActionMap_;
41 };
42 
AddCallback(uintptr_t key,CallbackAction & action)43 void CallbackManagerImpl::AddCallback(uintptr_t key, CallbackAction &action)
44 {
45     IAM_LOGI("start");
46     std::lock_guard<std::mutex> lock(mutex_);
47     callbackActionMap_.emplace(key, action);
48 }
49 
RemoveCallback(uintptr_t key)50 void CallbackManagerImpl::RemoveCallback(uintptr_t key)
51 {
52     IAM_LOGI("start");
53     std::lock_guard<std::mutex> lock(mutex_);
54     callbackActionMap_.erase(key);
55 }
56 
OnServiceDeath()57 void CallbackManagerImpl::OnServiceDeath()
58 {
59     IAM_LOGI("start");
60     std::lock_guard<std::mutex> lock(mutex_);
61     for (const auto &item : callbackActionMap_) {
62         if (item.second) {
63             item.second();
64         }
65     }
66     callbackActionMap_.clear();
67 }
68 
GetInstance()69 CallbackManager &CallbackManager::GetInstance()
70 {
71     static CallbackManagerImpl impl;
72     return impl;
73 }
74 } // namespace UserAuth
75 } // namespace UserIam
76 } // namespace OHOS