1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3#ifndef Q26NUMERIC_H
4#define Q26NUMERIC_H
5
6#include <QtCore/qglobal.h>
7
8//
9// W A R N I N G
10// -------------
11//
12// This file is not part of the Qt API. Types and functions defined in this
13// file can reliably be replaced by their std counterparts, once available.
14// You may use these definitions in your own code, but be aware that we
15// will remove them once Qt depends on the C++ version that supports
16// them in namespace std. There will be NO deprecation warning, the
17// definitions will JUST go away.
18//
19// If you can't agree to these terms, don't use these definitions!
20//
21// We mean it.
22//
23
24#include <numeric>
25#include <limits>
26#include <type_traits>
27
28QT_BEGIN_NAMESPACE
29
30namespace q26 {
31
32// Like std::saturate_cast
33#ifdef __cpp_lib_saturation_arithmetic
34using std::saturate_cast;
35#else
36template <typename To, typename From>
37constexpr auto saturate_cast(From x)
38{
39 static_assert(std::is_integral_v<To>);
40 static_assert(std::is_integral_v<From>);
41
42 [[maybe_unused]]
43 constexpr auto Lo = (std::numeric_limits<To>::min)();
44 constexpr auto Hi = (std::numeric_limits<To>::max)();
45
46 if constexpr (std::is_signed_v<From> == std::is_signed_v<To>) {
47 // same signedness, we can accept regular integer conversion rules
48 return x < Lo ? Lo :
49 x > Hi ? Hi :
50 /*else*/ To(x);
51 } else {
52 if constexpr (std::is_signed_v<From>) { // ie. !is_signed_v<To>
53 if (x < From{0})
54 return To{0};
55 }
56
57 // from here on, x >= 0
58 using FromU = std::make_unsigned_t<From>;
59 using ToU = std::make_unsigned_t<To>;
60 return FromU(x) > ToU(Hi) ? Hi : To(x); // assumes Hi >= 0
61 }
62}
63#endif // __cpp_lib_saturation_arithmetic
64
65} // namespace q26
66
67QT_END_NAMESPACE
68
69#endif /* Q26NUMERIC_H */
70

Provided by KDAB

Privacy Policy
Start learning QML with our Intro Training
Find out more

source code of qtbase/src/corelib/global/q26numeric.h