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
16 #ifndef PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
17 #define PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
18
19 #include <cstddef>
20 #include <cstdint>
21 #include <type_traits>
22
23 namespace ark::helpers {
24
25 template <class T>
ToSigned(T v)26 constexpr auto ToSigned(T v)
27 {
28 using SignedType = std::make_signed_t<T>;
29 return static_cast<SignedType>(v);
30 }
31
32 template <class T>
ToUnsigned(T v)33 constexpr auto ToUnsigned(T v)
34 {
35 using UnsignedType = std::make_unsigned_t<T>;
36 return static_cast<UnsignedType>(v);
37 }
38
39 // CC-OFFNXT(G.FMT.10) project code style
40 template <typename T, std::enable_if_t<std::is_enum_v<T>> * = nullptr>
ToUnderlying(T value)41 constexpr auto ToUnderlying(T value)
42 {
43 return static_cast<std::underlying_type_t<T>>(value);
44 }
45
UnsignedDifference(size_t x,size_t y)46 constexpr size_t UnsignedDifference(size_t x, size_t y)
47 {
48 return x > y ? x - y : 0;
49 }
50
UnsignedDifferenceUint64(uint64_t x,uint64_t y)51 constexpr uint64_t UnsignedDifferenceUint64(uint64_t x, uint64_t y)
52 {
53 return x > y ? x - y : 0;
54 }
55
56 template <typename T>
57 struct TypeIdentity {
58 // NOLINTNEXTLINE(readability-identifier-naming)
59 using type = T;
60 };
61
62 template <typename T>
63 struct RemoveAllPointers {
64 // NOLINTNEXTLINE(readability-identifier-naming)
65 using type = typename std::conditional_t<std::is_pointer_v<T>, RemoveAllPointers<std::remove_pointer_t<T>>,
66 TypeIdentity<T>>::type;
67 };
68 } // namespace ark::helpers
69
70 #ifdef __SIZEOF_INT128__
71 __extension__ using Int128 = __int128;
72 #else
73 using Int128 = struct Int128Type {
74 constexpr Int128Type() = default;
Int128TypeInt128Type75 constexpr explicit Int128Type(std::int64_t v) : lo(v) {}
76 // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes)
77 std::int64_t hi {0};
78 // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes)
79 std::int64_t lo {0};
80 bool operator==(std::int64_t v) const
81 {
82 return (hi == 0) && (lo == v);
83 }
84 };
85 static_assert(sizeof(Int128) == sizeof(std::int64_t) * 2U);
86 #endif
87
88 #endif // PANDA_LIBPANDABASE_UTILS_STRING_HELPERS_H_
89