• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 namespace panda::helpers {
20 
21 template <class T>
ToSigned(T v)22 constexpr auto ToSigned(T v)
23 {
24     using signed_type = std::make_signed_t<T>;
25     return static_cast<signed_type>(v);
26 }
27 
28 template <class T>
ToUnsigned(T v)29 constexpr auto ToUnsigned(T v)
30 {
31     using unsigned_type = std::make_unsigned_t<T>;
32     return static_cast<unsigned_type>(v);
33 }
34 
35 template <typename T, std::enable_if_t<std::is_enum_v<T>> * = nullptr>
ToUnderlying(T value)36 constexpr auto ToUnderlying(T value)
37 {
38     return static_cast<std::underlying_type_t<T>>(value);
39 }
40 
UnsignedDifference(size_t x,size_t y)41 constexpr size_t UnsignedDifference(size_t x, size_t y)
42 {
43     return x > y ? x - y : 0;
44 }
45 
UnsignedDifferenceUint64(uint64_t x,uint64_t y)46 constexpr uint64_t UnsignedDifferenceUint64(uint64_t x, uint64_t y)
47 {
48     return x > y ? x - y : 0;
49 }
50 
51 }  // namespace panda::helpers
52 
53 #ifdef __SIZEOF_INT128__
54 __extension__ using int128 = __int128;
55 #else
56 #include <cstdint>
57 using int128 = struct int128_type {
58     constexpr int128_type() = default;
int128_typeint128_type59     constexpr explicit int128_type(std::int64_t v) : lo(v) {};
60     std::int64_t hi {0};
61     std::int64_t lo {0};
62     bool operator==(std::int64_t v) const
63     {
64         return (hi == 0) && (lo == v);
65     }
66 };
67 static_assert(sizeof(int128) == sizeof(std::int64_t) * 2U);
68 #endif
69 
70 #endif  // PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
71