• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 API_CORE_PLUGIN_IINTERFACE_HELPER_H
17 #define API_CORE_PLUGIN_IINTERFACE_HELPER_H
18 
19 #include <base/containers/atomics.h>
20 #include <base/util/uid.h>
21 #include <core/plugin/intf_interface.h>
22 
CORE_BEGIN_NAMESPACE()23 CORE_BEGIN_NAMESPACE()
24 namespace Internal {
25 template<typename Me, typename Interface, typename... Interfaces>
26 const CORE_NS::IInterface* GetInterface(const Me* me, const BASE_NS::Uid& uid)
27 {
28     if (uid == Interface::UID) {
29         return static_cast<const Interface*>(me);
30     }
31     if constexpr (sizeof...(Interfaces) > 0) {
32         return GetInterface<Me, Interfaces...>(me, uid);
33     } else {
34         return nullptr;
35     }
36 }
37 } // namespace Internal
38 
39 template<typename... Interfaces>
40 class IInterfaceHelper : public Interfaces... {
41 public:
GetInterface(const BASE_NS::Uid & uid)42     const IInterface* GetInterface(const BASE_NS::Uid& uid) const override
43     {
44         if (uid == CORE_NS::IInterface::UID) {
45             return static_cast<const CORE_NS::IInterface*>(static_cast<const void*>(this));
46         }
47         return Internal::GetInterface<IInterfaceHelper, Interfaces...>(this, uid);
48     }
GetInterface(const BASE_NS::Uid & uid)49     IInterface* GetInterface(const BASE_NS::Uid& uid) override
50     {
51         if (uid == CORE_NS::IInterface::UID) {
52             return static_cast<CORE_NS::IInterface*>(static_cast<void*>(this));
53         }
54         return const_cast<CORE_NS::IInterface*>(Internal::GetInterface<IInterfaceHelper, Interfaces...>(this, uid));
55     }
56 
Ref()57     void Ref() override
58     {
59         BASE_NS::AtomicIncrementRelaxed(&refcnt_);
60     }
61 
Unref()62     void Unref() override
63     {
64         if (BASE_NS::AtomicDecrementRelease(&refcnt_) == 0) {
65             BASE_NS::AtomicFenceAcquire();
66             delete this;
67         }
68     }
69 
70 protected:
71     int32_t refcnt_ { 0 };
72 };
73 CORE_END_NAMESPACE()
74 
75 #endif // API_CORE_PLUGIN_IINTERFACE_HELPER_H