1 /**
2 * Copyright (c) 2021-2022 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 LIBPANDABASE_UTILS_TYPE_HELPERS_H
17 #define LIBPANDABASE_UTILS_TYPE_HELPERS_H
18
19 #include <cstddef>
20 #include <cstdint>
21 #include <type_traits>
22
23 namespace panda::helpers {
24
25 template <class T>
ToSigned(T v)26 constexpr auto ToSigned(T v)
27 {
28 using signed_type = std::make_signed_t<T>;
29 return static_cast<signed_type>(v);
30 }
31
32 template <class T>
ToUnsigned(T v)33 constexpr auto ToUnsigned(T v)
34 {
35 using unsigned_type = std::make_unsigned_t<T>;
36 return static_cast<unsigned_type>(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 } // namespace panda::helpers
56
57 #ifdef __SIZEOF_INT128__
58 __extension__ using int128 = __int128;
59 #else
60 #include <cstdint>
61 using int128 = struct int128_type {
62 constexpr int128_type() = default;
int128_typeint128_type63 constexpr explicit int128_type(std::int64_t v) : lo(v) {}
64 std::int64_t hi {0};
65 std::int64_t lo {0};
66 bool operator==(std::int64_t v) const
67 {
68 return (hi == 0) && (lo == v);
69 }
70 };
71 static_assert(sizeof(int128) == sizeof(std::int64_t) * 2U);
72 #endif
73
74 #endif // LIBPANDABASE_UTILS_TYPE_HELPERS_H
75