Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-12-15 10:24:05

0001 // Copyright (C) 2024 The Qt Company Ltd.
0002 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
0003 #ifndef Q26NUMERIC_H
0004 #define Q26NUMERIC_H
0005 
0006 #include <QtCore/qglobal.h>
0007 
0008 //
0009 //  W A R N I N G
0010 //  -------------
0011 //
0012 // This file is not part of the Qt API. Types and functions defined in this
0013 // file can reliably be replaced by their std counterparts, once available.
0014 // You may use these definitions in your own code, but be aware that we
0015 // will remove them once Qt depends on the C++ version that supports
0016 // them in namespace std. There will be NO deprecation warning, the
0017 // definitions will JUST go away.
0018 //
0019 // If you can't agree to these terms, don't use these definitions!
0020 //
0021 // We mean it.
0022 //
0023 
0024 #include <numeric>
0025 #include <limits>
0026 #include <type_traits>
0027 
0028 QT_BEGIN_NAMESPACE
0029 
0030 namespace q26 {
0031 
0032 // Like std::saturate_cast
0033 #ifdef __cpp_lib_saturation_arithmetic
0034 using std::saturate_cast;
0035 #else
0036 template <typename To, typename From>
0037 constexpr auto saturate_cast(From x)
0038 {
0039     static_assert(std::is_integral_v<To>);
0040     static_assert(std::is_integral_v<From>);
0041 
0042     [[maybe_unused]]
0043     constexpr auto Lo = (std::numeric_limits<To>::min)();
0044     constexpr auto Hi = (std::numeric_limits<To>::max)();
0045 
0046     if constexpr (std::is_signed_v<From> == std::is_signed_v<To>) {
0047         // same signedness, we can accept regular integer conversion rules
0048         return x < Lo  ? Lo :
0049                x > Hi  ? Hi :
0050                /*else*/  To(x);
0051     } else {
0052         if constexpr (std::is_signed_v<From>) { // ie. !is_signed_v<To>
0053             if (x < From{0})
0054                 return To{0};
0055         }
0056 
0057         // from here on, x >= 0
0058         using FromU = std::make_unsigned_t<From>;
0059         using ToU = std::make_unsigned_t<To>;
0060         return FromU(x) > ToU(Hi) ? Hi : To(x); // assumes Hi >= 0
0061     }
0062 }
0063 #endif // __cpp_lib_saturation_arithmetic
0064 
0065 } // namespace q26
0066 
0067 QT_END_NAMESPACE
0068 
0069 #endif /* Q26NUMERIC_H */