SquidMath.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9#ifndef _SQUID_SRC_SQUIDMATH_H
10#define _SQUID_SRC_SQUIDMATH_H
11
12#include "base/forward.h"
13#include "base/TypeTraits.h"
14
15#include <limits>
16#include <optional>
17
18// TODO: Move to src/base/Math.h and drop the Math namespace
19
20/* Math functions we define locally for Squid */
21namespace Math
22{
23
24int intPercent(const int a, const int b);
25int64_t int64Percent(const int64_t a, const int64_t b);
26double doublePercent(const double, const double);
27int intAverage(const int, const int, int, const int);
28double doubleAverage(const double, const double, int, const int);
29
30} // namespace Math
31
32// If Sum() performance becomes important, consider using GCC and clang
33// built-ins like __builtin_add_overflow() instead of manual overflow checks.
34
37template <typename T, typename U>
38using AllUnsigned = typename std::conditional<
39 std::is_unsigned<T>::value && std::is_unsigned<U>::value,
40 std::true_type,
41 std::false_type
42 >::type;
43
44// TODO: Replace with std::cmp_less() after migrating to C++20.
46template <typename A, typename B>
47constexpr bool
48Less(const A a, const B b) {
49 // The casts below make standard C++ integer conversions explicit. They
50 // quell compiler warnings about signed/unsigned comparison. The first two
51 // lines exclude different-sign a and b, making the casts/comparison safe.
52 using AB = typename std::common_type<A, B>::type;
53 return
54 (a >= 0 && b < 0) ? false :
55 (a < 0 && b >= 0) ? true :
56 /* (a >= 0) == (b >= 0) */ static_cast<AB>(a) < static_cast<AB>(b);
57}
58
60template<typename T>
61constexpr void
63{
64 static_assert(std::numeric_limits<T>::is_bounded, "std::numeric_limits<T>::max() is meaningful");
65 static_assert(std::numeric_limits<T>::is_exact, "no silent loss of precision");
66 static_assert(!std::is_enum<T>::value, "no silent creation of non-enumerated values");
67}
68
69// TODO: Investigate whether this optimization can be expanded to [signed] types
70// A and B when std::numeric_limits<decltype(A(0)+B(0))>::is_modulo is true.
74template <typename S, typename A, typename B, std::enable_if_t<AllUnsigned<A,B>::value, int> = 0>
75std::optional<S>
76IncreaseSumInternal(const A a, const B b) {
77 // paranoid: AllUnsigned<A,B> precondition established that already
78 static_assert(std::is_unsigned<A>::value, "AllUnsigned dispatch worked for A");
79 static_assert(std::is_unsigned<B>::value, "AllUnsigned dispatch worked for B");
80
81 AssertNaturalType<S>();
82 AssertNaturalType<A>();
83 AssertNaturalType<B>();
84
85 // we should only be called by IncreaseSum(); it forces integer promotion
86 static_assert(std::is_same<A, decltype(+a)>::value, "a will not be promoted");
87 static_assert(std::is_same<B, decltype(+b)>::value, "b will not be promoted");
88 // and without integer promotions, a sum of unsigned integers is unsigned
89 static_assert(std::is_unsigned<decltype(a+b)>::value, "a+b is unsigned");
90
91 // with integer promotions ruled out, a or b can only undergo integer
92 // conversion to the higher rank type (A or B, we do not know which)
93 using AB = typename std::common_type<A, B>::type;
94 static_assert(std::is_same<AB, A>::value || std::is_same<AB, B>::value, "no unexpected conversions");
95 static_assert(std::is_same<AB, decltype(a+b)>::value, "lossless assignment");
96 const AB sum = a + b;
97
98 static_assert(std::numeric_limits<AB>::is_modulo, "we can detect overflows");
99 // 1. modulo math: overflowed sum is smaller than any of its operands
100 // 2. the sum may overflow S (i.e. the return base type)
101 // We do not need Less() here because we compare promoted unsigned types.
102 return (sum >= a && sum <= std::numeric_limits<S>::max()) ?
103 std::optional<S>(sum) : std::optional<S>();
104}
105
110template <typename S, typename A, typename B, std::enable_if_t<!AllUnsigned<A,B>::value, int> = 0>
111std::optional<S> constexpr
112IncreaseSumInternal(const A a, const B b) {
113 AssertNaturalType<S>();
114 AssertNaturalType<A>();
115 AssertNaturalType<B>();
116
117 // we should only be called by IncreaseSum() that does integer promotion
118 static_assert(std::is_same<A, decltype(+a)>::value, "a will not be promoted");
119 static_assert(std::is_same<B, decltype(+b)>::value, "b will not be promoted");
120
121 return
122 // We could support a non-under/overflowing sum of negative numbers, but
123 // our callers use negative values specially (e.g., for do-not-use or
124 // do-not-limit settings) and are not supposed to do math with them.
125 (a < 0 || b < 0) ? std::optional<S>() :
126 // To avoid undefined behavior of signed overflow, we must not compute
127 // the raw a+b sum if it may overflow. When A is not B, a or b undergoes
128 // (safe for non-negatives) integer conversion in these expressions, so
129 // we do not know the resulting a+b type AB and its maximum. We must
130 // also detect subsequent casting-to-S overflows.
131 // Overflow condition: (a + b > maxAB) or (a + b > maxS).
132 // A is an integer promotion of S, so maxS <= maxA <= maxAB.
133 // Since maxS <= maxAB, it is sufficient to just check: a + b > maxS,
134 // which is the same as the overflow-safe condition here: maxS - a < b.
135 // Finally, (maxS - a) cannot overflow because a is not negative and
136 // cannot underflow because a is a promotion of s: 0 <= a <= maxS.
137 Less(std::numeric_limits<S>::max() - a, b) ? std::optional<S>() :
138 std::optional<S>(a + b);
139}
140
142template <typename S, typename T>
143std::optional<S>
144IncreaseSum(const S s, const T t)
145{
146 // Force (always safe) integer promotions now, to give std::enable_if_t<>
147 // promoted types instead of entering IncreaseSumInternal<AllUnsigned>(s,t)
148 // but getting a _signed_ promoted value of s or t in s + t.
149 return IncreaseSumInternal<S>(+s, +t);
150}
151
153template <typename S, typename T, typename... Args>
154std::optional<S>
155IncreaseSum(const S sum, const T t, const Args... args) {
156 if (const auto head = IncreaseSum(sum, t)) {
157 return IncreaseSum(head.value(), args...);
158 } else {
159 // std::optional<S>() triggers bogus -Wmaybe-uninitialized warnings in GCC v10.3
160 return std::nullopt;
161 }
162}
163
165template <typename SummationType, typename... Args>
166std::optional<SummationType>
167NaturalSum(const Args... args) {
168 return IncreaseSum<SummationType>(0, args...);
169}
170
174template <typename S, typename... Args>
175S
176SetToNaturalSumOrMax(S &var, const Args... args)
177{
178 var = NaturalSum<S>(args...).value_or(std::numeric_limits<S>::max());
179 return var;
180}
181
184template <typename Result, typename Source>
185Result
186NaturalCast(const Source s)
187{
188 return NaturalSum<Result>(s).value();
189}
190
191#endif /* _SQUID_SRC_SQUIDMATH_H */
192
Result NaturalCast(const Source s)
Definition: SquidMath.h:186
S SetToNaturalSumOrMax(S &var, const Args... args)
Definition: SquidMath.h:176
std::optional< S > IncreaseSumInternal(const A a, const B b)
Definition: SquidMath.h:76
std::optional< SummationType > NaturalSum(const Args... args)
Definition: SquidMath.h:167
std::optional< S > IncreaseSum(const S s, const T t)
argument pack expansion termination for IncreaseSum<S, T, Args...>()
Definition: SquidMath.h:144
typename std::conditional< std::is_unsigned< T >::value &&std::is_unsigned< U >::value, std::true_type, std::false_type >::type AllUnsigned
Definition: SquidMath.h:42
constexpr void AssertNaturalType()
ensure that T is supported by NaturalSum() and friends
Definition: SquidMath.h:62
constexpr bool Less(const A a, const B b)
whether integer a is less than integer b, with correct overflow handling
Definition: SquidMath.h:48
squidaio_request_t * head
Definition: aiops.cc:127
A const & max(A const &lhs, A const &rhs)
static uint32 A
Definition: md4.c:43
static uint32 B
Definition: md4.c:43
Definition: SquidMath.h:22
int intPercent(const int a, const int b)
Definition: SquidMath.cc:13
double doubleAverage(const double, const double, int, const int)
Definition: SquidMath.cc:31
double doublePercent(const double, const double)
Definition: SquidMath.cc:25
int64_t int64Percent(const int64_t a, const int64_t b)
Definition: SquidMath.cc:19
int intAverage(const int, const int, int, const int)
Definition: SquidMath.cc:40

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors