$darkmode
templates.hpp
1 /*
2  * Copyright 2023 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
22 #pragma once
23 
24 #include <cstdint> // for int8_t, ...
25 #include <limits> // for numeric_limits
26 
27 namespace fable {
28 
35 template <typename T, typename S>
36 constexpr bool is_cast_safe(S value) {
37  if (static_cast<S>(static_cast<T>(value)) != value) {
38  // Ensure no narrowing is occurring.
39  return false;
40  }
41 
42  if constexpr (std::numeric_limits<T>::is_signed != std::numeric_limits<S>::is_signed) {
43  // Mismatch in signedness can go wrong in two ways that aren't caught above.
44  if constexpr (std::numeric_limits<S>::is_signed) {
45  // Check value will not underflow.
46  return value >= 0;
47  } else {
48  // Check value will not overflow.
49  return static_cast<unsigned long long>(value) <=
50  static_cast<unsigned long long>(std::numeric_limits<T>::max());
51  }
52  }
53 
54  return true;
55 }
56 
65 template <typename T>
66 struct typeinfo {
67  static const constexpr char* name = "unknown";
68 };
69 
70 // clang-format off
71 template <> struct typeinfo<bool> { static const constexpr char* name = "bool"; };
72 template <> struct typeinfo<int8_t> { static const constexpr char* name = "int8_t"; };
73 template <> struct typeinfo<int16_t> { static const constexpr char* name = "int16_t"; };
74 template <> struct typeinfo<int32_t> { static const constexpr char* name = "int32_t"; };
75 template <> struct typeinfo<int64_t> { static const constexpr char* name = "int64_t"; };
76 template <> struct typeinfo<uint8_t> { static const constexpr char* name = "uint8_t"; };
77 template <> struct typeinfo<uint16_t> { static const constexpr char* name = "uint16_t"; };
78 template <> struct typeinfo<uint32_t> { static const constexpr char* name = "uint32_t"; };
79 template <> struct typeinfo<uint64_t> { static const constexpr char* name = "uint64_t"; };
80 // clang-format on
81 
82 } // namespace fable
Definition: templates.hpp:66