Debian Codegraph @

src/mpt/base/saturate_cast.hpp

raw
1 /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
2
3 #ifndef MPT_BASE_SATURATE_CAST_HPP
4 #define MPT_BASE_SATURATE_CAST_HPP
5
6
7
8 #include "mpt/base/detect.hpp"
9 #include "mpt/base/namespace.hpp"
10
11 #include <algorithm>
12 #include <limits>
13 #if MPT_CXX_AT_LEAST(26)
14 #include <numeric>
15 #endif
16
17
18
19 namespace mpt {
20 inline namespace MPT_INLINE_NS {
21
22
23 #if MPT_CXX_AT_LEAST(26)
24
25 using std::saturate_cast;
26
27 #else
28
29 // Saturate the value of src to the domain of Tdst
30 template <typename Tdst, typename Tsrc>
31 constexpr Tdst saturate_cast(Tsrc src) noexcept {
32 // This code tries not only to obviously avoid overflows but also to avoid signed/unsigned comparison warnings and type truncation warnings (which in fact would be safe here) by explicit casting.
33 static_assert(std::numeric_limits<Tdst>::is_integer);
34 static_assert(std::numeric_limits<Tsrc>::is_integer);
35 if constexpr (std::numeric_limits<Tdst>::is_signed && std::numeric_limits<Tsrc>::is_signed) {
36 if constexpr (sizeof(Tdst) >= sizeof(Tsrc)) {
37 return static_cast<Tdst>(src);
38 } else {
39 return static_cast<Tdst>(std::max(static_cast<Tsrc>(std::numeric_limits<Tdst>::min()), std::min(src, static_cast<Tsrc>(std::numeric_limits<Tdst>::max()))));
40 }
41 } else if constexpr (!std::numeric_limits<Tdst>::is_signed && !std::numeric_limits<Tsrc>::is_signed) {
42 if constexpr (sizeof(Tdst) >= sizeof(Tsrc)) {
43 return static_cast<Tdst>(src);
44 } else {
45 return static_cast<Tdst>(std::min(src, static_cast<Tsrc>(std::numeric_limits<Tdst>::max())));
46 }
47 } else if constexpr (std::numeric_limits<Tdst>::is_signed && !std::numeric_limits<Tsrc>::is_signed) {
48 if constexpr (sizeof(Tdst) > sizeof(Tsrc)) {
49 return static_cast<Tdst>(src);
50 } else if constexpr (sizeof(Tdst) == sizeof(Tsrc)) {
51 return static_cast<Tdst>(std::min(src, static_cast<Tsrc>(std::numeric_limits<Tdst>::max())));
52 } else {
53 return static_cast<Tdst>(std::min(src, static_cast<Tsrc>(std::numeric_limits<Tdst>::max())));
54 }
55 } else { // Tdst unsigned, Tsrc signed
56 if constexpr (sizeof(Tdst) >= sizeof(Tsrc)) {
57 return static_cast<Tdst>(std::max(static_cast<Tsrc>(0), src));
58 } else {
59 return static_cast<Tdst>(std::max(static_cast<Tsrc>(0), std::min(src, static_cast<Tsrc>(std::numeric_limits<Tdst>::max()))));
60 }
61 }
62 }
63
64 #endif
65
66
67 } // namespace MPT_INLINE_NS
68 } // namespace mpt
69
70
71
72 #endif // MPT_BASE_SATURATE_CAST_HPP