WPILibC++ 2025.2.1
Loading...
Searching...
No Matches
MathExtras.h
Go to the documentation of this file.
1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef WPIUTIL_WPI_MATHEXTRAS_H
14#define WPIUTIL_WPI_MATHEXTRAS_H
15
16#include "wpi/bit.h"
17#include "wpi/Compiler.h"
18#include <bit>
19#include <cassert>
20#include <climits>
21#include <cstdint>
22#include <cstring>
23#include <limits>
24#include <type_traits>
25
26namespace wpi {
27/// Some template parameter helpers to optimize for bitwidth, for functions that
28/// take multiple arguments.
29
30// We can't verify signedness, since callers rely on implicit coercions to
31// signed/unsigned.
32template <typename T, typename U>
34 std::enable_if_t<std::is_integral_v<T> && std::is_integral_v<U>>;
35
36// Use std::common_type_t to widen only up to the widest argument.
37template <typename T, typename U, typename = enableif_int<T, U>>
39 std::common_type_t<std::make_unsigned_t<T>, std::make_unsigned_t<U>>;
40template <typename T, typename U, typename = enableif_int<T, U>>
42 std::common_type_t<std::make_signed_t<T>, std::make_signed_t<U>>;
43
44/// Create a bitmask with the N right-most bits set to 1, and all other
45/// bits set to 0. Only unsigned types are allowed.
46template <typename T> T maskTrailingOnes(unsigned N) {
47 static_assert(std::is_unsigned_v<T>, "Invalid type!");
48 const unsigned Bits = CHAR_BIT * sizeof(T);
49 assert(N <= Bits && "Invalid bit index");
50 if (N == 0)
51 return 0;
52 return T(-1) >> (Bits - N);
53}
54
55/// Create a bitmask with the N left-most bits set to 1, and all other
56/// bits set to 0. Only unsigned types are allowed.
57template <typename T> T maskLeadingOnes(unsigned N) {
58 return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
59}
60
61/// Create a bitmask with the N right-most bits set to 0, and all other
62/// bits set to 1. Only unsigned types are allowed.
63template <typename T> T maskTrailingZeros(unsigned N) {
64 return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
65}
66
67/// Create a bitmask with the N left-most bits set to 0, and all other
68/// bits set to 1. Only unsigned types are allowed.
69template <typename T> T maskLeadingZeros(unsigned N) {
70 return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
71}
72
73/// Macro compressed bit reversal table for 256 bits.
74///
75/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
76static const unsigned char BitReverseTable256[256] = {
77#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
78#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
79#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
80 R6(0), R6(2), R6(1), R6(3)
81#undef R2
82#undef R4
83#undef R6
84};
85
86/// Reverse the bits in \p Val.
87template <typename T> T reverseBits(T Val) {
88#if __has_builtin(__builtin_bitreverse8)
89 if constexpr (std::is_same_v<T, uint8_t>)
90 return __builtin_bitreverse8(Val);
91#endif
92#if __has_builtin(__builtin_bitreverse16)
93 if constexpr (std::is_same_v<T, uint16_t>)
94 return __builtin_bitreverse16(Val);
95#endif
96#if __has_builtin(__builtin_bitreverse32)
97 if constexpr (std::is_same_v<T, uint32_t>)
98 return __builtin_bitreverse32(Val);
99#endif
100#if __has_builtin(__builtin_bitreverse64)
101 if constexpr (std::is_same_v<T, uint64_t>)
102 return __builtin_bitreverse64(Val);
103#endif
104
105 unsigned char in[sizeof(Val)];
106 unsigned char out[sizeof(Val)];
107 std::memcpy(in, &Val, sizeof(Val));
108 for (unsigned i = 0; i < sizeof(Val); ++i)
109 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
110 std::memcpy(&Val, out, sizeof(Val));
111 return Val;
112}
113
114// NOTE: The following support functions use the _32/_64 extensions instead of
115// type overloading so that signed and unsigned integers can be used without
116// ambiguity.
117
118/// Return the high 32 bits of a 64 bit value.
119constexpr uint32_t Hi_32(uint64_t Value) {
120 return static_cast<uint32_t>(Value >> 32);
121}
122
123/// Return the low 32 bits of a 64 bit value.
124constexpr uint32_t Lo_32(uint64_t Value) {
125 return static_cast<uint32_t>(Value);
126}
127
128/// Make a 64-bit integer from a high / low pair of 32-bit integers.
129constexpr uint64_t Make_64(uint32_t High, uint32_t Low) {
130 return ((uint64_t)High << 32) | (uint64_t)Low;
131}
132
133/// Checks if an integer fits into the given bit width.
134template <unsigned N> constexpr bool isInt(int64_t x) {
135 if constexpr (N == 0)
136 return 0 == x;
137 if constexpr (N == 8)
138 return static_cast<int8_t>(x) == x;
139 if constexpr (N == 16)
140 return static_cast<int16_t>(x) == x;
141 if constexpr (N == 32)
142 return static_cast<int32_t>(x) == x;
143 if constexpr (N < 64)
144 return -(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1));
145 (void)x; // MSVC v19.25 warns that x is unused.
146 return true;
147}
148
149/// Checks if a signed integer is an N bit number shifted left by S.
150template <unsigned N, unsigned S>
151constexpr bool isShiftedInt(int64_t x) {
152 static_assert(S < 64, "isShiftedInt<N, S> with S >= 64 is too much.");
153 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
154 return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
155}
156
157/// Checks if an unsigned integer fits into the given bit width.
158template <unsigned N> constexpr bool isUInt(uint64_t x) {
159 if constexpr (N == 0)
160 return 0 == x;
161 if constexpr (N == 8)
162 return static_cast<uint8_t>(x) == x;
163 if constexpr (N == 16)
164 return static_cast<uint16_t>(x) == x;
165 if constexpr (N == 32)
166 return static_cast<uint32_t>(x) == x;
167 if constexpr (N < 64)
168 return x < (UINT64_C(1) << (N));
169 (void)x; // MSVC v19.25 warns that x is unused.
170 return true;
171}
172
173/// Checks if a unsigned integer is an N bit number shifted left by S.
174template <unsigned N, unsigned S>
175constexpr bool isShiftedUInt(uint64_t x) {
176 static_assert(S < 64, "isShiftedUInt<N, S> with S >= 64 is too much.");
177 static_assert(N + S <= 64,
178 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
179 // S must be strictly less than 64. So 1 << S is not undefined behavior.
180 return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
181}
182
183/// Gets the maximum value for a N-bit unsigned integer.
184inline uint64_t maxUIntN(uint64_t N) {
185 assert(N <= 64 && "integer width out of range");
186
187 // uint64_t(1) << 64 is undefined behavior, so we can't do
188 // (uint64_t(1) << N) - 1
189 // without checking first that N != 64. But this works and doesn't have a
190 // branch for N != 0.
191 // Unfortunately, shifting a uint64_t right by 64 bit is undefined
192 // behavior, so the condition on N == 0 is necessary. Fortunately, most
193 // optimizers do not emit branches for this check.
194 if (N == 0)
195 return 0;
196 return UINT64_MAX >> (64 - N);
197}
198
199#ifdef _WIN32
200#pragma warning(push)
201#pragma warning(disable : 4146)
202#endif
203
204/// Gets the minimum value for a N-bit signed integer.
205inline int64_t minIntN(int64_t N) {
206 assert(N >= 0 && N <= 64 && "integer width out of range");
207
208 if (N == 0)
209 return 0;
210 return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
211}
212
213#ifdef _WIN32
214#pragma warning(pop)
215#endif
216
217/// Gets the maximum value for a N-bit signed integer.
218inline int64_t maxIntN(int64_t N) {
219 assert(N >= 0 && N <= 64 && "integer width out of range");
220
221 // This relies on two's complement wraparound when N == 64, so we convert to
222 // int64_t only at the very end to avoid UB.
223 if (N == 0)
224 return 0;
225 return (UINT64_C(1) << (N - 1)) - 1;
226}
227
228/// Checks if an unsigned integer fits into the given (dynamic) bit width.
229inline bool isUIntN(unsigned N, uint64_t x) {
230 return N >= 64 || x <= maxUIntN(N);
231}
232
233/// Checks if an signed integer fits into the given (dynamic) bit width.
234inline bool isIntN(unsigned N, int64_t x) {
235 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
236}
237
238/// Return true if the argument is a non-empty sequence of ones starting at the
239/// least significant bit with the remainder zero (32 bit version).
240/// Ex. isMask_32(0x0000FFFFU) == true.
241constexpr bool isMask_32(uint32_t Value) {
242 return Value && ((Value + 1) & Value) == 0;
243}
244
245/// Return true if the argument is a non-empty sequence of ones starting at the
246/// least significant bit with the remainder zero (64 bit version).
247constexpr bool isMask_64(uint64_t Value) {
248 return Value && ((Value + 1) & Value) == 0;
249}
250
251/// Return true if the argument contains a non-empty sequence of ones with the
252/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
253constexpr bool isShiftedMask_32(uint32_t Value) {
254 return Value && isMask_32((Value - 1) | Value);
255}
256
257/// Return true if the argument contains a non-empty sequence of ones with the
258/// remainder zero (64 bit version.)
259constexpr bool isShiftedMask_64(uint64_t Value) {
260 return Value && isMask_64((Value - 1) | Value);
261}
262
263/// Return true if the argument is a power of two > 0.
264/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
265constexpr bool isPowerOf2_32(uint32_t Value) {
266 return std::has_single_bit(Value);
267}
268
269/// Return true if the argument is a power of two > 0 (64 bit edition.)
270constexpr bool isPowerOf2_64(uint64_t Value) {
271 return std::has_single_bit(Value);
272}
273
274/// Return true if the argument contains a non-empty sequence of ones with the
275/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
276/// If true, \p MaskIdx will specify the index of the lowest set bit and \p
277/// MaskLen is updated to specify the length of the mask, else neither are
278/// updated.
279inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
280 unsigned &MaskLen) {
281 if (!isShiftedMask_32(Value))
282 return false;
283 MaskIdx = std::countr_zero(Value);
284 MaskLen = std::popcount(Value);
285 return true;
286}
287
288/// Return true if the argument contains a non-empty sequence of ones with the
289/// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
290/// of the lowest set bit and \p MaskLen is updated to specify the length of the
291/// mask, else neither are updated.
292inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
293 unsigned &MaskLen) {
294 if (!isShiftedMask_64(Value))
295 return false;
296 MaskIdx = std::countr_zero(Value);
297 MaskLen = std::popcount(Value);
298 return true;
299}
300
301/// Compile time Log2.
302/// Valid only for positive powers of two.
303template <size_t kValue> constexpr size_t CTLog2() {
304 static_assert(kValue > 0 && wpi::isPowerOf2_64(kValue),
305 "Value is not a valid power of 2");
306 return 1 + CTLog2<kValue / 2>();
307}
308
309template <> constexpr size_t CTLog2<1>() { return 0; }
310
311/// Return the floor log base 2 of the specified value, -1 if the value is zero.
312/// (32 bit edition.)
313/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
314inline unsigned Log2_32(uint32_t Value) {
315 return static_cast<unsigned>(31 - std::countl_zero(Value));
316}
317
318/// Return the floor log base 2 of the specified value, -1 if the value is zero.
319/// (64 bit edition.)
320inline unsigned Log2_64(uint64_t Value) {
321 return static_cast<unsigned>(63 - std::countl_zero(Value));
322}
323
324/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
325/// (32 bit edition).
326/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
327inline unsigned Log2_32_Ceil(uint32_t Value) {
328 return static_cast<unsigned>(32 - std::countl_zero(Value - 1));
329}
330
331/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
332/// (64 bit edition.)
333inline unsigned Log2_64_Ceil(uint64_t Value) {
334 return static_cast<unsigned>(64 - std::countl_zero(Value - 1));
335}
336
337/// A and B are either alignments or offsets. Return the minimum alignment that
338/// may be assumed after adding the two together.
339template <typename U, typename V, typename T = common_uint<U, V>>
340constexpr T MinAlign(U A, V B) {
341 // The largest power of 2 that divides both A and B.
342 //
343 // Replace "-Value" by "1+~Value" in the following commented code to avoid
344 // MSVC warning C4146
345 // return (A | B) & -(A | B);
346 return (A | B) & (1 + ~(A | B));
347}
348
349/// Fallback when arguments aren't integral.
350constexpr uint64_t MinAlign(uint64_t A, uint64_t B) {
351 return (A | B) & (1 + ~(A | B));
352}
353
354/// Returns the next power of two (in 64-bits) that is strictly greater than A.
355/// Returns zero on overflow.
356constexpr uint64_t NextPowerOf2(uint64_t A) {
357 A |= (A >> 1);
358 A |= (A >> 2);
359 A |= (A >> 4);
360 A |= (A >> 8);
361 A |= (A >> 16);
362 A |= (A >> 32);
363 return A + 1;
364}
365
366/// Returns the power of two which is greater than or equal to the given value.
367/// Essentially, it is a ceil operation across the domain of powers of two.
368inline uint64_t PowerOf2Ceil(uint64_t A) {
369 if (!A || A > UINT64_MAX / 2)
370 return 0;
371 return UINT64_C(1) << Log2_64_Ceil(A);
372}
373
374/// Returns the integer ceil(Numerator / Denominator). Unsigned version.
375/// Guaranteed to never overflow.
376template <typename U, typename V, typename T = common_uint<U, V>>
377constexpr T divideCeil(U Numerator, V Denominator) {
378 assert(Denominator && "Division by zero");
379 T Bias = (Numerator != 0);
380 return (Numerator - Bias) / Denominator + Bias;
381}
382
383/// Fallback when arguments aren't integral.
384constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
385 assert(Denominator && "Division by zero");
386 uint64_t Bias = (Numerator != 0);
387 return (Numerator - Bias) / Denominator + Bias;
388}
389
390// Check whether divideCeilSigned or divideFloorSigned would overflow. This
391// happens only when Numerator = INT_MIN and Denominator = -1.
392template <typename U, typename V>
393constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) {
394 return Numerator == (std::numeric_limits<U>::min)() && Denominator == -1;
395}
396
397/// Returns the integer ceil(Numerator / Denominator). Signed version.
398/// Overflow is explicitly forbidden with an assert.
399template <typename U, typename V, typename T = common_sint<U, V>>
400constexpr T divideCeilSigned(U Numerator, V Denominator) {
401 assert(Denominator && "Division by zero");
402 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
403 "Divide would overflow");
404 if (!Numerator)
405 return 0;
406 // C's integer division rounds towards 0.
407 T Bias = Denominator >= 0 ? 1 : -1;
408 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
409 return SameSign ? (Numerator - Bias) / Denominator + 1
410 : Numerator / Denominator;
411}
412
413/// Returns the integer floor(Numerator / Denominator). Signed version.
414/// Overflow is explicitly forbidden with an assert.
415template <typename U, typename V, typename T = common_sint<U, V>>
416constexpr T divideFloorSigned(U Numerator, V Denominator) {
417 assert(Denominator && "Division by zero");
418 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
419 "Divide would overflow");
420 if (!Numerator)
421 return 0;
422 // C's integer division rounds towards 0.
423 T Bias = Denominator >= 0 ? -1 : 1;
424 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
425 return SameSign ? Numerator / Denominator
426 : (Numerator - Bias) / Denominator - 1;
427}
428
429/// Returns the remainder of the Euclidean division of LHS by RHS. Result is
430/// always non-negative.
431template <typename U, typename V, typename T = common_sint<U, V>>
432constexpr T mod(U Numerator, V Denominator) {
433 assert(Denominator >= 1 && "Mod by non-positive number");
434 T Mod = Numerator % Denominator;
435 return Mod < 0 ? Mod + Denominator : Mod;
436}
437
438/// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
439/// never overflow.
440template <typename U, typename V, typename T = common_uint<U, V>>
441constexpr T divideNearest(U Numerator, V Denominator) {
442 assert(Denominator && "Division by zero");
443 T Mod = Numerator % Denominator;
444 return (Numerator / Denominator) +
445 (Mod > (static_cast<T>(Denominator) - 1) / 2);
446}
447
448/// Returns the next integer (mod 2**nbits) that is greater than or equal to
449/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
450///
451/// Examples:
452/// \code
453/// alignTo(5, 8) = 8
454/// alignTo(17, 8) = 24
455/// alignTo(~0LL, 8) = 0
456/// alignTo(321, 255) = 510
457/// \endcode
458///
459/// Will overflow only if result is not representable in T.
460template <typename U, typename V, typename T = common_uint<U, V>>
461constexpr T alignTo(U Value, V Align) {
462 assert(Align != 0u && "Align can't be 0.");
463 T CeilDiv = divideCeil(Value, Align);
464 return CeilDiv * Align;
465}
466
467/// Fallback when arguments aren't integral.
468constexpr uint64_t alignTo(uint64_t Value, uint64_t Align) {
469 assert(Align != 0u && "Align can't be 0.");
470 uint64_t CeilDiv = divideCeil(Value, Align);
471 return CeilDiv * Align;
472}
473
474constexpr uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) {
475 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
476 "Align must be a power of 2");
477 // Replace unary minus to avoid compilation error on Windows:
478 // "unary minus operator applied to unsigned type, result still unsigned"
479 uint64_t NegAlign = (~Align) + 1;
480 return (Value + Align - 1) & NegAlign;
481}
482
483/// If non-zero \p Skew is specified, the return value will be a minimal integer
484/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
485/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
486/// Skew mod \p A'. \p Align must be non-zero.
487///
488/// Examples:
489/// \code
490/// alignTo(5, 8, 7) = 7
491/// alignTo(17, 8, 1) = 17
492/// alignTo(~0LL, 8, 3) = 3
493/// alignTo(321, 255, 42) = 552
494/// \endcode
495///
496/// May overflow.
497template <typename U, typename V, typename W,
498 typename T = common_uint<common_uint<U, V>, W>>
499constexpr T alignTo(U Value, V Align, W Skew) {
500 assert(Align != 0u && "Align can't be 0.");
501 Skew %= Align;
502 return alignTo(Value - Skew, Align) + Skew;
503}
504
505/// Returns the next integer (mod 2**nbits) that is greater than or equal to
506/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
507///
508/// Will overflow only if result is not representable in T.
509template <auto Align, typename V, typename T = common_uint<decltype(Align), V>>
510constexpr T alignTo(V Value) {
511 static_assert(Align != 0u, "Align must be non-zero");
512 T CeilDiv = divideCeil(Value, Align);
513 return CeilDiv * Align;
514}
515
516/// Returns the largest unsigned integer less than or equal to \p Value and is
517/// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never
518/// overflow.
519template <typename U, typename V, typename W = uint8_t,
520 typename T = common_uint<common_uint<U, V>, W>>
521constexpr T alignDown(U Value, V Align, W Skew = 0) {
522 assert(Align != 0u && "Align can't be 0.");
523 Skew %= Align;
524 return (Value - Skew) / Align * Align + Skew;
525}
526
527/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
528/// Requires B <= 32.
529template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) {
530 static_assert(B <= 32, "Bit width out of range.");
531 if constexpr (B == 0)
532 return 0;
533 return int32_t(X << (32 - B)) >> (32 - B);
534}
535
536/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
537/// Requires B <= 32.
538inline int32_t SignExtend32(uint32_t X, unsigned B) {
539 assert(B <= 32 && "Bit width out of range.");
540 if (B == 0)
541 return 0;
542 return int32_t(X << (32 - B)) >> (32 - B);
543}
544
545/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
546/// Requires B <= 64.
547template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) {
548 static_assert(B <= 64, "Bit width out of range.");
549 if constexpr (B == 0)
550 return 0;
551 return int64_t(x << (64 - B)) >> (64 - B);
552}
553
554/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
555/// Requires B <= 64.
556inline int64_t SignExtend64(uint64_t X, unsigned B) {
557 assert(B <= 64 && "Bit width out of range.");
558 if (B == 0)
559 return 0;
560 return int64_t(X << (64 - B)) >> (64 - B);
561}
562
563/// Subtract two unsigned integers, X and Y, of type T and return the absolute
564/// value of the result.
565template <typename U, typename V, typename T = common_uint<U, V>>
566constexpr T AbsoluteDifference(U X, V Y) {
567 return X > Y ? (X - Y) : (Y - X);
568}
569
570/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
571/// maximum representable value of T on overflow. ResultOverflowed indicates if
572/// the result is larger than the maximum representable value of type T.
573template <typename T>
574std::enable_if_t<std::is_unsigned_v<T>, T>
575SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
576 bool Dummy;
577 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
578 // Hacker's Delight, p. 29
579 T Z = X + Y;
580 Overflowed = (Z < X || Z < Y);
581 if (Overflowed)
582 return (std::numeric_limits<T>::max)();
583 else
584 return Z;
585}
586
587/// Add multiple unsigned integers of type T. Clamp the result to the
588/// maximum representable value of T on overflow.
589template <class T, class... Ts>
590std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
591 Ts... Args) {
592 bool Overflowed = false;
593 T XY = SaturatingAdd(X, Y, &Overflowed);
594 if (Overflowed)
595 return SaturatingAdd((std::numeric_limits<T>::max)(), T(1), Args...);
596 return SaturatingAdd(XY, Z, Args...);
597}
598
599/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
600/// maximum representable value of T on overflow. ResultOverflowed indicates if
601/// the result is larger than the maximum representable value of type T.
602template <typename T>
603std::enable_if_t<std::is_unsigned_v<T>, T>
604SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
605 bool Dummy;
606 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
607
608 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
609 // because it fails for uint16_t (where multiplication can have undefined
610 // behavior due to promotion to int), and requires a division in addition
611 // to the multiplication.
612
613 Overflowed = false;
614
615 // Log2(Z) would be either Log2Z or Log2Z + 1.
616 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
617 // will necessarily be less than Log2Max as desired.
618 int Log2Z = Log2_64(X) + Log2_64(Y);
619 const T Max = (std::numeric_limits<T>::max)();
620 int Log2Max = Log2_64(Max);
621 if (Log2Z < Log2Max) {
622 return X * Y;
623 }
624 if (Log2Z > Log2Max) {
625 Overflowed = true;
626 return Max;
627 }
628
629 // We're going to use the top bit, and maybe overflow one
630 // bit past it. Multiply all but the bottom bit then add
631 // that on at the end.
632 T Z = (X >> 1) * Y;
633 if (Z & ~(Max >> 1)) {
634 Overflowed = true;
635 return Max;
636 }
637 Z <<= 1;
638 if (X & 1)
639 return SaturatingAdd(Z, Y, ResultOverflowed);
640
641 return Z;
642}
643
644/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
645/// the product. Clamp the result to the maximum representable value of T on
646/// overflow. ResultOverflowed indicates if the result is larger than the
647/// maximum representable value of type T.
648template <typename T>
649std::enable_if_t<std::is_unsigned_v<T>, T>
650SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
651 bool Dummy;
652 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
653
654 T Product = SaturatingMultiply(X, Y, &Overflowed);
655 if (Overflowed)
656 return Product;
657
658 return SaturatingAdd(A, Product, &Overflowed);
659}
660
661/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
662extern const float huge_valf;
663
664/// Add two signed integers, computing the two's complement truncated result,
665/// returning true if overflow occurred.
666template <typename T>
667std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
668#if __has_builtin(__builtin_add_overflow)
669 return __builtin_add_overflow(X, Y, &Result);
670#else
671 // Perform the unsigned addition.
672 using U = std::make_unsigned_t<T>;
673 const U UX = static_cast<U>(X);
674 const U UY = static_cast<U>(Y);
675 const U UResult = UX + UY;
676
677 // Convert to signed.
678 Result = static_cast<T>(UResult);
679
680 // Adding two positive numbers should result in a positive number.
681 if (X > 0 && Y > 0)
682 return Result <= 0;
683 // Adding two negatives should result in a negative number.
684 if (X < 0 && Y < 0)
685 return Result >= 0;
686 return false;
687#endif
688}
689
690/// Subtract two signed integers, computing the two's complement truncated
691/// result, returning true if an overflow ocurred.
692template <typename T>
693std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
694#if __has_builtin(__builtin_sub_overflow)
695 return __builtin_sub_overflow(X, Y, &Result);
696#else
697 // Perform the unsigned addition.
698 using U = std::make_unsigned_t<T>;
699 const U UX = static_cast<U>(X);
700 const U UY = static_cast<U>(Y);
701 const U UResult = UX - UY;
702
703 // Convert to signed.
704 Result = static_cast<T>(UResult);
705
706 // Subtracting a positive number from a negative results in a negative number.
707 if (X <= 0 && Y > 0)
708 return Result >= 0;
709 // Subtracting a negative number from a positive results in a positive number.
710 if (X >= 0 && Y < 0)
711 return Result <= 0;
712 return false;
713#endif
714}
715
716/// Multiply two signed integers, computing the two's complement truncated
717/// result, returning true if an overflow ocurred.
718template <typename T>
719std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
720#if __has_builtin(__builtin_mul_overflow)
721 return __builtin_mul_overflow(X, Y, &Result);
722#else
723 // Perform the unsigned multiplication on absolute values.
724 using U = std::make_unsigned_t<T>;
725 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
726 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
727 const U UResult = UX * UY;
728
729 // Convert to signed.
730 const bool IsNegative = (X < 0) ^ (Y < 0);
731 Result = IsNegative ? (0 - UResult) : UResult;
732
733 // If any of the args was 0, result is 0 and no overflow occurs.
734 if (UX == 0 || UY == 0)
735 return false;
736
737 // UX and UY are in [1, 2^n], where n is the number of digits.
738 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
739 // positive) divided by an argument compares to the other.
740 if (IsNegative)
741 return UX > (static_cast<U>((std::numeric_limits<T>::max)()) + U(1)) / UY;
742 else
743 return UX > (static_cast<U>((std::numeric_limits<T>::max)())) / UY;
744#endif
745}
746
747/// Type to force float point values onto the stack, so that x86 doesn't add
748/// hidden precision, avoiding rounding differences on various platforms.
749#if defined(__i386__) || defined(_M_IX86)
750using stack_float_t = volatile float;
751#else
752using stack_float_t = float;
753#endif
754
755// Typesafe implementation of the signum function.
756// Returns -1 if negative, 1 if positive, 0 if 0.
757template <typename T>
758constexpr int sgn(T val) {
759 return (T(0) < val) - (val < T(0));
760}
761
762/**
763 * Linearly interpolates between two values.
764 *
765 * @param startValue The start value.
766 * @param endValue The end value.
767 * @param t The fraction for interpolation.
768 *
769 * @return The interpolated value.
770 */
771template <typename T>
772constexpr T Lerp(const T& startValue, const T& endValue, double t) {
773 return startValue + (endValue - startValue) * t;
774}
775
776} // namespace wpi
777
778#endif
#define R6(n)
This file implements the C++20 <bit> header.
Foonathan namespace.
Definition ntcore_cpp.h:26
int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:218
std::enable_if_t< std::is_signed_v< T >, T > SubOverflow(T X, T Y, T &Result)
Subtract two signed integers, computing the two's complement truncated result, returning true if an o...
Definition MathExtras.h:693
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:377
static const unsigned char BitReverseTable256[256]
Macro compressed bit reversal table for 256 bits.
Definition MathExtras.h:76
T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:57
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:158
constexpr int sgn(T val)
Definition MathExtras.h:758
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:314
std::common_type_t< std::make_unsigned_t< T >, std::make_unsigned_t< U > > common_uint
Definition MathExtras.h:38
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:340
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:327
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:368
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:441
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:124
T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:46
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:151
constexpr bool isShiftedMask_32(uint32_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (32 bit ver...
Definition MathExtras.h:253
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:547
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:265
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
Definition MathExtras.h:416
T reverseBits(T Val)
Reverse the bits in Val.
Definition MathExtras.h:87
std::enable_if_t< std::is_signed_v< T >, T > MulOverflow(T X, T Y, T &Result)
Multiply two signed integers, computing the two's complement truncated result, returning true if an o...
Definition MathExtras.h:719
constexpr size_t CTLog2()
Compile time Log2.
Definition MathExtras.h:303
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition MathExtras.h:604
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:575
constexpr T alignTo(U Value, V Align)
Returns the next integer (mod 2**nbits) that is greater than or equal to Value and is a multiple of A...
Definition MathExtras.h:461
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
constexpr size_t CTLog2< 1 >()
Definition MathExtras.h:309
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:134
std::enable_if_t< std::is_integral_v< T > &&std::is_integral_v< U > > enableif_int
Some template parameter helpers to optimize for bitwidth, for functions that take multiple arguments.
Definition MathExtras.h:33
std::common_type_t< std::make_signed_t< T >, std::make_signed_t< U > > common_sint
Definition MathExtras.h:41
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:650
constexpr T mod(U Numerator, V Denominator)
Returns the remainder of the Euclidean division of LHS by RHS.
Definition MathExtras.h:432
constexpr T Lerp(const T &startValue, const T &endValue, double t)
Linearly interpolates between two values.
Definition MathExtras.h:772
constexpr T divideCeilSigned(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:400
constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator)
Definition MathExtras.h:393
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:320
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:270
std::enable_if_t< std::is_signed_v< T >, T > AddOverflow(T X, T Y, T &Result)
Add two signed integers, computing the two's complement truncated result, returning true if overflow ...
Definition MathExtras.h:667
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:247
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:356
int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition MathExtras.h:205
float stack_float_t
Type to force float point values onto the stack, so that x86 doesn't add hidden precision,...
Definition MathExtras.h:752
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition MathExtras.h:129
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:521
T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition MathExtras.h:63
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:184
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:229
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition MathExtras.h:566
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:175
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:234
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:333
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:259
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition MathExtras.h:529
T maskLeadingZeros(unsigned N)
Create a bitmask with the N left-most bits set to 0, and all other bits set to 1.
Definition MathExtras.h:69
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:119
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:241
constexpr uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align)
Definition MathExtras.h:474
#define S(label, offset, message)
Definition Errors.h:113