1 /**
2 * Copyright 2021 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_
18 #define MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_
19
20 #include <memory>
21 #include <vector>
22 #include <type_traits>
23 #include "mindapi/base/base.h"
24
25 namespace mindspore::api {
26 template <typename T, typename U>
ToRef(const std::shared_ptr<U> & ptr)27 T &ToRef(const std::shared_ptr<U> &ptr) {
28 return static_cast<T &>(*ptr);
29 }
30
31 template <typename T, typename U, typename = typename std::enable_if_t<std::is_base_of_v<mindspore::Base, T>>,
32 typename = typename std::enable_if_t<std::is_base_of_v<Base, U>>>
ToImpl(const SharedPtr<U> & wrapper)33 std::shared_ptr<T> ToImpl(const SharedPtr<U> &wrapper) {
34 if (wrapper == nullptr || wrapper->impl() == nullptr) {
35 return nullptr;
36 }
37 return std::dynamic_pointer_cast<T>(wrapper->impl());
38 }
39
40 template <typename T, typename = typename std::enable_if_t<std::is_base_of_v<Base, T>>>
ToWrapper(const std::shared_ptr<mindspore::Base> & impl)41 SharedPtr<T> ToWrapper(const std::shared_ptr<mindspore::Base> &impl) {
42 if (impl == nullptr) {
43 return nullptr;
44 }
45 return MakeShared<T>(impl);
46 }
47
48 template <typename T, typename U>
ToImplVector(const U & wrapper_vector)49 std::vector<std::shared_ptr<T>> ToImplVector(const U &wrapper_vector) {
50 std::vector<std::shared_ptr<T>> impl_vector;
51 impl_vector.reserve(wrapper_vector.size());
52 for (auto &wrapper : wrapper_vector) {
53 impl_vector.emplace_back(ToImpl<T>(wrapper));
54 }
55 return impl_vector;
56 }
57
58 template <typename T, typename U>
ToWrapperVector(const U & impl_vector)59 std::vector<SharedPtr<T>> ToWrapperVector(const U &impl_vector) {
60 std::vector<SharedPtr<T>> wrapper_vector;
61 wrapper_vector.reserve(impl_vector.size());
62 for (auto &impl : impl_vector) {
63 wrapper_vector.emplace_back(ToWrapper<T>(impl));
64 }
65 return wrapper_vector;
66 }
67
68 #define MIND_API_BASE_IMPL(current_class, impl_class, base_class) \
69 current_class::current_class(const std::shared_ptr<mindspore::Base> &impl) : base_class(impl) { \
70 if (!impl_->isa<impl_class>()) { \
71 MS_LOG(EXCEPTION) << "Wrong impl " << impl_->type_name() << " for " << #current_class; \
72 } \
73 } \
74 uint32_t current_class::ClassId() { return impl_class::kTypeId; }
75 } // namespace mindspore::api
76 #endif // MINDSPORE_CORE_MINDAPI_IMPL_HELPER_H_
77