1 /**
2 * Copyright (c) 2021-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 #ifndef PANDA_PLUGINS_ETS_RUNTIME_FFI_CLASSES_ETS_VALUE_H_
16 #define PANDA_PLUGINS_ETS_RUNTIME_FFI_CLASSES_ETS_VALUE_H_
17
18 #include "runtime/include/runtime.h"
19 #include "ets_type.h"
20
21 namespace ark::ets {
22
23 class EtsObject;
24
25 template <typename T>
GetEtsType()26 constexpr EtsType GetEtsType()
27 {
28 if constexpr (std::is_same<T, ets_boolean>::value) { // NOLINT
29 return EtsType::BOOLEAN;
30 }
31 if constexpr (std::is_same<T, ets_byte>::value) { // NOLINT
32 return EtsType::BYTE;
33 }
34 if constexpr (std::is_same<T, ets_char>::value) { // NOLINT
35 return EtsType::CHAR;
36 }
37 if constexpr (std::is_same<T, ets_short>::value) { // NOLINT
38 return EtsType::SHORT;
39 }
40 if constexpr (std::is_same<T, ets_int>::value) { // NOLINT
41 return EtsType::INT;
42 }
43 if constexpr (std::is_same<T, ets_long>::value) { // NOLINT
44 return EtsType::LONG;
45 }
46 if constexpr (std::is_same<T, ets_float>::value) { // NOLINT
47 return EtsType::FLOAT;
48 }
49 if constexpr (std::is_same<T, ets_double>::value) { // NOLINT
50 return EtsType::DOUBLE;
51 }
52 if constexpr (std::is_same<T, EtsObject>::value) { // NOLINT
53 return EtsType::OBJECT;
54 }
55 if constexpr (std::is_same<T, void>::value) { // NOLINT
56 return EtsType::VOID;
57 }
58 return EtsType::UNKNOWN;
59 }
60
61 class EtsValue {
62 public:
63 EtsValue() = default;
64
65 template <typename T>
EtsValue(T value)66 explicit EtsValue(T value)
67 {
68 static_assert(std::is_arithmetic<T>::value || std::is_same<T, ets_object>::value ||
69 std::is_same<T, std::nullptr_t>::value);
70 static_assert(sizeof(T) <= sizeof(holder_));
71
72 memcpy_s(&holder_, sizeof(holder_), &value, sizeof(value));
73 }
74
75 template <typename T>
GetAs()76 T GetAs()
77 {
78 static_assert(std::is_arithmetic<T>::value || std::is_same<T, ets_object>::value);
79 static_assert(sizeof(T) <= sizeof(holder_));
80
81 T tmp;
82 memcpy_s(&tmp, sizeof(T), &holder_, sizeof(T));
83 return tmp;
84 }
85
86 private:
87 int64_t holder_ {0};
88 };
89
90 } // namespace ark::ets
91
92 #endif // PANDA_PLUGINS_ETS_RUNTIME_FFI_CLASSES_ETS_VALUE_H_