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