• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 template <typename T, std::enable_if_t<std::is_enum_v<T>> * = nullptr>
ToUnderlying(T value)40 constexpr auto ToUnderlying(T value)
41 {
42     return static_cast<std::underlying_type_t<T>>(value);
43 }
44 
UnsignedDifference(size_t x,size_t y)45 constexpr size_t UnsignedDifference(size_t x, size_t y)
46 {
47     return x > y ? x - y : 0;
48 }
49 
UnsignedDifferenceUint64(uint64_t x,uint64_t y)50 constexpr uint64_t UnsignedDifferenceUint64(uint64_t x, uint64_t y)
51 {
52     return x > y ? x - y : 0;
53 }
54 
55 template <typename T>
56 struct TypeIdentity {
57     // NOLINTNEXTLINE(readability-identifier-naming)
58     using type = T;
59 };
60 
61 template <typename T>
62 struct RemoveAllPointers {
63     // NOLINTNEXTLINE(readability-identifier-naming)
64     using type = typename std::conditional_t<std::is_pointer_v<T>, RemoveAllPointers<std::remove_pointer_t<T>>,
65                                              TypeIdentity<T>>::type;
66 };
67 }  // namespace ark::helpers
68 
69 #ifdef __SIZEOF_INT128__
70 __extension__ using Int128 = __int128;
71 #else
72 using Int128 = struct Int128Type {
73     constexpr Int128Type() = default;
Int128TypeInt128Type74     constexpr explicit Int128Type(std::int64_t v) : lo(v) {}
75     // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes)
76     std::int64_t hi {0};
77     // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes)
78     std::int64_t lo {0};
79     bool operator==(std::int64_t v) const
80     {
81         return (hi == 0) && (lo == v);
82     }
83 };
84 static_assert(sizeof(Int128) == sizeof(std::int64_t) * 2U);
85 #endif
86 
87 #endif  // PANDA_LIBPANDABASE_UTILS_STRING_HELPERS_H_
88