WPILibC++ 2024.3.2
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
28/// Create a bitmask with the N right-most bits set to 1, and all other
29/// bits set to 0. Only unsigned types are allowed.
30template <typename T> T maskTrailingOnes(unsigned N) {
31 static_assert(std::is_unsigned_v<T>, "Invalid type!");
32 const unsigned Bits = CHAR_BIT * sizeof(T);
33 assert(N <= Bits && "Invalid bit index");
34 return N == 0 ? 0 : (T(-1) >> (Bits - N));
35}
36
37/// Create a bitmask with the N left-most bits set to 1, and all other
38/// bits set to 0. Only unsigned types are allowed.
39template <typename T> T maskLeadingOnes(unsigned N) {
40 return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
41}
42
43/// Create a bitmask with the N right-most bits set to 0, and all other
44/// bits set to 1. Only unsigned types are allowed.
45template <typename T> T maskTrailingZeros(unsigned N) {
46 return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
47}
48
49/// Create a bitmask with the N left-most bits set to 0, and all other
50/// bits set to 1. Only unsigned types are allowed.
51template <typename T> T maskLeadingZeros(unsigned N) {
52 return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
53}
54
55/// Macro compressed bit reversal table for 256 bits.
56///
57/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
58static const unsigned char BitReverseTable256[256] = {
59#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
60#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
61#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
62 R6(0), R6(2), R6(1), R6(3)
63#undef R2
64#undef R4
65#undef R6
66};
67
68/// Reverse the bits in \p Val.
69template <typename T> T reverseBits(T Val) {
70#if __has_builtin(__builtin_bitreverse8)
71 if constexpr (std::is_same_v<T, uint8_t>)
72 return __builtin_bitreverse8(Val);
73#endif
74#if __has_builtin(__builtin_bitreverse16)
75 if constexpr (std::is_same_v<T, uint16_t>)
76 return __builtin_bitreverse16(Val);
77#endif
78#if __has_builtin(__builtin_bitreverse32)
79 if constexpr (std::is_same_v<T, uint32_t>)
80 return __builtin_bitreverse32(Val);
81#endif
82#if __has_builtin(__builtin_bitreverse64)
83 if constexpr (std::is_same_v<T, uint64_t>)
84 return __builtin_bitreverse64(Val);
85#endif
86
87 unsigned char in[sizeof(Val)];
88 unsigned char out[sizeof(Val)];
89 std::memcpy(in, &Val, sizeof(Val));
90 for (unsigned i = 0; i < sizeof(Val); ++i)
91 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
92 std::memcpy(&Val, out, sizeof(Val));
93 return Val;
94}
95
96// NOTE: The following support functions use the _32/_64 extensions instead of
97// type overloading so that signed and unsigned integers can be used without
98// ambiguity.
99
100/// Return the high 32 bits of a 64 bit value.
101constexpr inline uint32_t Hi_32(uint64_t Value) {
102 return static_cast<uint32_t>(Value >> 32);
103}
104
105/// Return the low 32 bits of a 64 bit value.
106constexpr inline uint32_t Lo_32(uint64_t Value) {
107 return static_cast<uint32_t>(Value);
108}
109
110/// Make a 64-bit integer from a high / low pair of 32-bit integers.
111constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
112 return ((uint64_t)High << 32) | (uint64_t)Low;
113}
114
115/// Checks if an integer fits into the given bit width.
116template <unsigned N> constexpr inline bool isInt(int64_t x) {
117 if constexpr (N == 8)
118 return static_cast<int8_t>(x) == x;
119 if constexpr (N == 16)
120 return static_cast<int16_t>(x) == x;
121 if constexpr (N == 32)
122 return static_cast<int32_t>(x) == x;
123 if constexpr (N < 64)
124 return -(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1));
125 (void)x; // MSVC v19.25 warns that x is unused.
126 return true;
127}
128
129/// Checks if a signed integer is an N bit number shifted left by S.
130template <unsigned N, unsigned S>
131constexpr inline bool isShiftedInt(int64_t x) {
132 static_assert(
133 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
134 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
135 return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
136}
137
138/// Checks if an unsigned integer fits into the given bit width.
139template <unsigned N> constexpr inline bool isUInt(uint64_t x) {
140 static_assert(N > 0, "isUInt<0> doesn't make sense");
141 if constexpr (N == 8)
142 return static_cast<uint8_t>(x) == x;
143 if constexpr (N == 16)
144 return static_cast<uint16_t>(x) == x;
145 if constexpr (N == 32)
146 return static_cast<uint32_t>(x) == x;
147 if constexpr (N < 64)
148 return x < (UINT64_C(1) << (N));
149 (void)x; // MSVC v19.25 warns that x is unused.
150 return true;
151}
152
153/// Checks if a unsigned integer is an N bit number shifted left by S.
154template <unsigned N, unsigned S>
155constexpr inline bool isShiftedUInt(uint64_t x) {
156 static_assert(
157 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
158 static_assert(N + S <= 64,
159 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
160 // Per the two static_asserts above, S must be strictly less than 64. So
161 // 1 << S is not undefined behavior.
162 return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
163}
164
165/// Gets the maximum value for a N-bit unsigned integer.
166inline uint64_t maxUIntN(uint64_t N) {
167 assert(N > 0 && N <= 64 && "integer width out of range");
168
169 // uint64_t(1) << 64 is undefined behavior, so we can't do
170 // (uint64_t(1) << N) - 1
171 // without checking first that N != 64. But this works and doesn't have a
172 // branch.
173 return UINT64_MAX >> (64 - N);
174}
175
176#ifdef _WIN32
177#pragma warning(push)
178#pragma warning(disable : 4146)
179#endif
180
181/// Gets the minimum value for a N-bit signed integer.
182inline int64_t minIntN(int64_t N) {
183 assert(N > 0 && N <= 64 && "integer width out of range");
184
185 return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
186}
187
188#ifdef _WIN32
189#pragma warning(pop)
190#endif
191
192/// Gets the maximum value for a N-bit signed integer.
193inline int64_t maxIntN(int64_t N) {
194 assert(N > 0 && N <= 64 && "integer width out of range");
195
196 // This relies on two's complement wraparound when N == 64, so we convert to
197 // int64_t only at the very end to avoid UB.
198 return (UINT64_C(1) << (N - 1)) - 1;
199}
200
201/// Checks if an unsigned integer fits into the given (dynamic) bit width.
202inline bool isUIntN(unsigned N, uint64_t x) {
203 return N >= 64 || x <= maxUIntN(N);
204}
205
206/// Checks if an signed integer fits into the given (dynamic) bit width.
207inline bool isIntN(unsigned N, int64_t x) {
208 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
209}
210
211/// Return true if the argument is a non-empty sequence of ones starting at the
212/// least significant bit with the remainder zero (32 bit version).
213/// Ex. isMask_32(0x0000FFFFU) == true.
214constexpr inline bool isMask_32(uint32_t Value) {
215 return Value && ((Value + 1) & Value) == 0;
216}
217
218/// Return true if the argument is a non-empty sequence of ones starting at the
219/// least significant bit with the remainder zero (64 bit version).
220constexpr inline bool isMask_64(uint64_t Value) {
221 return Value && ((Value + 1) & Value) == 0;
222}
223
224/// Return true if the argument contains a non-empty sequence of ones with the
225/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
226constexpr inline bool isShiftedMask_32(uint32_t Value) {
227 return Value && isMask_32((Value - 1) | Value);
228}
229
230/// Return true if the argument contains a non-empty sequence of ones with the
231/// remainder zero (64 bit version.)
232constexpr inline bool isShiftedMask_64(uint64_t Value) {
233 return Value && isMask_64((Value - 1) | Value);
234}
235
236/// Return true if the argument is a power of two > 0.
237/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
238constexpr inline bool isPowerOf2_32(uint32_t Value) {
239 return std::has_single_bit(Value);
240}
241
242/// Return true if the argument is a power of two > 0 (64 bit edition.)
243constexpr inline bool isPowerOf2_64(uint64_t Value) {
244 return std::has_single_bit(Value);
245}
246
247/// Return true if the argument contains a non-empty sequence of ones with the
248/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
249/// If true, \p MaskIdx will specify the index of the lowest set bit and \p
250/// MaskLen is updated to specify the length of the mask, else neither are
251/// updated.
252inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
253 unsigned &MaskLen) {
254 if (!isShiftedMask_32(Value))
255 return false;
256 MaskIdx = std::countr_zero(Value);
257 MaskLen = std::popcount(Value);
258 return true;
259}
260
261/// Return true if the argument contains a non-empty sequence of ones with the
262/// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
263/// of the lowest set bit and \p MaskLen is updated to specify the length of the
264/// mask, else neither are updated.
265inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
266 unsigned &MaskLen) {
267 if (!isShiftedMask_64(Value))
268 return false;
269 MaskIdx = std::countr_zero(Value);
270 MaskLen = std::popcount(Value);
271 return true;
272}
273
274/// Compile time Log2.
275/// Valid only for positive powers of two.
276template <size_t kValue> constexpr inline size_t CTLog2() {
277 static_assert(kValue > 0 && wpi::isPowerOf2_64(kValue),
278 "Value is not a valid power of 2");
279 return 1 + CTLog2<kValue / 2>();
280}
281
282template <> constexpr inline size_t CTLog2<1>() { return 0; }
283
284/// Return the floor log base 2 of the specified value, -1 if the value is zero.
285/// (32 bit edition.)
286/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
287inline unsigned Log2_32(uint32_t Value) {
288 return static_cast<unsigned>(31 - std::countl_zero(Value));
289}
290
291/// Return the floor log base 2 of the specified value, -1 if the value is zero.
292/// (64 bit edition.)
293inline unsigned Log2_64(uint64_t Value) {
294 return static_cast<unsigned>(63 - std::countl_zero(Value));
295}
296
297/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
298/// (32 bit edition).
299/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
300inline unsigned Log2_32_Ceil(uint32_t Value) {
301 return static_cast<unsigned>(32 - std::countl_zero(Value - 1));
302}
303
304/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
305/// (64 bit edition.)
306inline unsigned Log2_64_Ceil(uint64_t Value) {
307 return static_cast<unsigned>(64 - std::countl_zero(Value - 1));
308}
309
310/// A and B are either alignments or offsets. Return the minimum alignment that
311/// may be assumed after adding the two together.
312constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
313 // The largest power of 2 that divides both A and B.
314 //
315 // Replace "-Value" by "1+~Value" in the following commented code to avoid
316 // MSVC warning C4146
317 // return (A | B) & -(A | B);
318 return (A | B) & (1 + ~(A | B));
319}
320
321/// Returns the next power of two (in 64-bits) that is strictly greater than A.
322/// Returns zero on overflow.
323constexpr inline uint64_t NextPowerOf2(uint64_t A) {
324 A |= (A >> 1);
325 A |= (A >> 2);
326 A |= (A >> 4);
327 A |= (A >> 8);
328 A |= (A >> 16);
329 A |= (A >> 32);
330 return A + 1;
331}
332
333/// Returns the power of two which is greater than or equal to the given value.
334/// Essentially, it is a ceil operation across the domain of powers of two.
335inline uint64_t PowerOf2Ceil(uint64_t A) {
336 if (!A)
337 return 0;
338 return NextPowerOf2(A - 1);
339}
340
341/// Returns the next integer (mod 2**64) that is greater than or equal to
342/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
343///
344/// Examples:
345/// \code
346/// alignTo(5, 8) = 8
347/// alignTo(17, 8) = 24
348/// alignTo(~0LL, 8) = 0
349/// alignTo(321, 255) = 510
350/// \endcode
351inline uint64_t alignTo(uint64_t Value, uint64_t Align) {
352 assert(Align != 0u && "Align can't be 0.");
353 return (Value + Align - 1) / Align * Align;
354}
355
356inline uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) {
357 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
358 "Align must be a power of 2");
359 // Replace unary minus to avoid compilation error on Windows:
360 // "unary minus operator applied to unsigned type, result still unsigned"
361 uint64_t negAlign = (~Align) + 1;
362 return (Value + Align - 1) & negAlign;
363}
364
365/// If non-zero \p Skew is specified, the return value will be a minimal integer
366/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
367/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
368/// Skew mod \p A'. \p Align must be non-zero.
369///
370/// Examples:
371/// \code
372/// alignTo(5, 8, 7) = 7
373/// alignTo(17, 8, 1) = 17
374/// alignTo(~0LL, 8, 3) = 3
375/// alignTo(321, 255, 42) = 552
376/// \endcode
377inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew) {
378 assert(Align != 0u && "Align can't be 0.");
379 Skew %= Align;
380 return alignTo(Value - Skew, Align) + Skew;
381}
382
383/// Returns the next integer (mod 2**64) that is greater than or equal to
384/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
385template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
386 static_assert(Align != 0u, "Align must be non-zero");
387 return (Value + Align - 1) / Align * Align;
388}
389
390/// Returns the integer ceil(Numerator / Denominator).
391inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
392 return alignTo(Numerator, Denominator) / Denominator;
393}
394
395/// Returns the integer nearest(Numerator / Denominator).
396inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
397 return (Numerator + (Denominator / 2)) / Denominator;
398}
399
400/// Returns the largest uint64_t less than or equal to \p Value and is
401/// \p Skew mod \p Align. \p Align must be non-zero
402inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
403 assert(Align != 0u && "Align can't be 0.");
404 Skew %= Align;
405 return (Value - Skew) / Align * Align + Skew;
406}
407
408/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
409/// Requires 0 < B <= 32.
410template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
411 static_assert(B > 0, "Bit width can't be 0.");
412 static_assert(B <= 32, "Bit width out of range.");
413 return int32_t(X << (32 - B)) >> (32 - B);
414}
415
416/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
417/// Requires 0 < B <= 32.
418inline int32_t SignExtend32(uint32_t X, unsigned B) {
419 assert(B > 0 && "Bit width can't be 0.");
420 assert(B <= 32 && "Bit width out of range.");
421 return int32_t(X << (32 - B)) >> (32 - B);
422}
423
424/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
425/// Requires 0 < B <= 64.
426template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
427 static_assert(B > 0, "Bit width can't be 0.");
428 static_assert(B <= 64, "Bit width out of range.");
429 return int64_t(x << (64 - B)) >> (64 - B);
430}
431
432/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
433/// Requires 0 < B <= 64.
434inline int64_t SignExtend64(uint64_t X, unsigned B) {
435 assert(B > 0 && "Bit width can't be 0.");
436 assert(B <= 64 && "Bit width out of range.");
437 return int64_t(X << (64 - B)) >> (64 - B);
438}
439
440/// Subtract two unsigned integers, X and Y, of type T and return the absolute
441/// value of the result.
442template <typename T>
443std::enable_if_t<std::is_unsigned_v<T>, T> AbsoluteDifference(T X, T Y) {
444 return X > Y ? (X - Y) : (Y - X);
445}
446
447/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
448/// maximum representable value of T on overflow. ResultOverflowed indicates if
449/// the result is larger than the maximum representable value of type T.
450template <typename T>
451std::enable_if_t<std::is_unsigned_v<T>, T>
452SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
453 bool Dummy;
454 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
455 // Hacker's Delight, p. 29
456 T Z = X + Y;
457 Overflowed = (Z < X || Z < Y);
458 if (Overflowed)
460 else
461 return Z;
462}
463
464/// Add multiple unsigned integers of type T. Clamp the result to the
465/// maximum representable value of T on overflow.
466template <class T, class... Ts>
467std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
468 Ts... Args) {
469 bool Overflowed = false;
470 T XY = SaturatingAdd(X, Y, &Overflowed);
471 if (Overflowed)
472 return SaturatingAdd((std::numeric_limits<T>::max)(), T(1), Args...);
473 return SaturatingAdd(XY, Z, Args...);
474}
475
476/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
477/// maximum representable value of T on overflow. ResultOverflowed indicates if
478/// the result is larger than the maximum representable value of type T.
479template <typename T>
480std::enable_if_t<std::is_unsigned_v<T>, T>
481SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
482 bool Dummy;
483 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
484
485 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
486 // because it fails for uint16_t (where multiplication can have undefined
487 // behavior due to promotion to int), and requires a division in addition
488 // to the multiplication.
489
490 Overflowed = false;
491
492 // Log2(Z) would be either Log2Z or Log2Z + 1.
493 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
494 // will necessarily be less than Log2Max as desired.
495 int Log2Z = Log2_64(X) + Log2_64(Y);
496 const T Max = (std::numeric_limits<T>::max)();
497 int Log2Max = Log2_64(Max);
498 if (Log2Z < Log2Max) {
499 return X * Y;
500 }
501 if (Log2Z > Log2Max) {
502 Overflowed = true;
503 return Max;
504 }
505
506 // We're going to use the top bit, and maybe overflow one
507 // bit past it. Multiply all but the bottom bit then add
508 // that on at the end.
509 T Z = (X >> 1) * Y;
510 if (Z & ~(Max >> 1)) {
511 Overflowed = true;
512 return Max;
513 }
514 Z <<= 1;
515 if (X & 1)
516 return SaturatingAdd(Z, Y, ResultOverflowed);
517
518 return Z;
519}
520
521/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
522/// the product. Clamp the result to the maximum representable value of T on
523/// overflow. ResultOverflowed indicates if the result is larger than the
524/// maximum representable value of type T.
525template <typename T>
526std::enable_if_t<std::is_unsigned_v<T>, T>
527SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
528 bool Dummy;
529 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
530
531 T Product = SaturatingMultiply(X, Y, &Overflowed);
532 if (Overflowed)
533 return Product;
534
535 return SaturatingAdd(A, Product, &Overflowed);
536}
537
538/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
539extern const float huge_valf;
540
541
542/// Add two signed integers, computing the two's complement truncated result,
543/// returning true if overflow occurred.
544template <typename T>
545std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
546#if __has_builtin(__builtin_add_overflow)
547 return __builtin_add_overflow(X, Y, &Result);
548#else
549 // Perform the unsigned addition.
550 using U = std::make_unsigned_t<T>;
551 const U UX = static_cast<U>(X);
552 const U UY = static_cast<U>(Y);
553 const U UResult = UX + UY;
554
555 // Convert to signed.
556 Result = static_cast<T>(UResult);
557
558 // Adding two positive numbers should result in a positive number.
559 if (X > 0 && Y > 0)
560 return Result <= 0;
561 // Adding two negatives should result in a negative number.
562 if (X < 0 && Y < 0)
563 return Result >= 0;
564 return false;
565#endif
566}
567
568/// Subtract two signed integers, computing the two's complement truncated
569/// result, returning true if an overflow ocurred.
570template <typename T>
571std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
572#if __has_builtin(__builtin_sub_overflow)
573 return __builtin_sub_overflow(X, Y, &Result);
574#else
575 // Perform the unsigned addition.
576 using U = std::make_unsigned_t<T>;
577 const U UX = static_cast<U>(X);
578 const U UY = static_cast<U>(Y);
579 const U UResult = UX - UY;
580
581 // Convert to signed.
582 Result = static_cast<T>(UResult);
583
584 // Subtracting a positive number from a negative results in a negative number.
585 if (X <= 0 && Y > 0)
586 return Result >= 0;
587 // Subtracting a negative number from a positive results in a positive number.
588 if (X >= 0 && Y < 0)
589 return Result <= 0;
590 return false;
591#endif
592}
593
594/// Multiply two signed integers, computing the two's complement truncated
595/// result, returning true if an overflow ocurred.
596template <typename T>
597std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
598 // Perform the unsigned multiplication on absolute values.
599 using U = std::make_unsigned_t<T>;
600 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
601 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
602 const U UResult = UX * UY;
603
604 // Convert to signed.
605 const bool IsNegative = (X < 0) ^ (Y < 0);
606 Result = IsNegative ? (0 - UResult) : UResult;
607
608 // If any of the args was 0, result is 0 and no overflow occurs.
609 if (UX == 0 || UY == 0)
610 return false;
611
612 // UX and UY are in [1, 2^n], where n is the number of digits.
613 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
614 // positive) divided by an argument compares to the other.
615 if (IsNegative)
616 return UX > (static_cast<U>((std::numeric_limits<T>::max)()) + U(1)) / UY;
617 else
618 return UX > (static_cast<U>((std::numeric_limits<T>::max)())) / UY;
619}
620
621// Typesafe implementation of the signum function.
622// Returns -1 if negative, 1 if positive, 0 if 0.
623template <typename T>
624constexpr int sgn(T val) {
625 return (T(0) < val) - (val < T(0));
626}
627
628/**
629 * Linearly interpolates between two values.
630 *
631 * @param startValue The start value.
632 * @param endValue The end value.
633 * @param t The fraction for interpolation.
634 *
635 * @return The interpolated value.
636 */
637template <typename T>
638constexpr T Lerp(const T& startValue, const T& endValue, double t) {
639 return startValue + (endValue - startValue) * t;
640}
641} // End wpi namespace
642
643#endif
#define R6(n)
This file implements the C++20 <bit> header.
constexpr auto in(type t, int set) -> bool
Definition: core.h:611
FMT_CONSTEXPR20 auto countl_zero(uint32_t n) -> int
Definition: format.h:526
UnitTypeLhs() max(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs)
Definition: base.h:3417
Definition: ntcore_cpp.h:26
int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition: MathExtras.h:193
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:571
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:39
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition: MathExtras.h:139
constexpr int sgn(T val)
Definition: MathExtras.h:624
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:287
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:300
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:335
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition: MathExtras.h:106
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:30
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:131
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:226
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:426
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:238
T reverseBits(T Val)
Reverse the bits in Val.
Definition: MathExtras.h:69
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:597
constexpr size_t CTLog2()
Compile time Log2.
Definition: MathExtras.h:276
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:481
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:452
constexpr size_t CTLog2< 1 >()
Definition: MathExtras.h:282
uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator)
Returns the integer nearest(Numerator / Denominator).
Definition: MathExtras.h:396
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition: MathExtras.h:116
uint64_t alignTo(uint64_t Value, uint64_t Align)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:351
uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:391
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:527
constexpr T Lerp(const T &startValue, const T &endValue, double t)
Linearly interpolates between two values.
Definition: MathExtras.h:638
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:312
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:293
uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align)
Definition: MathExtras.h:356
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:243
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:545
std::enable_if_t< std::is_unsigned_v< T >, T > AbsoluteDifference(T X, T Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition: MathExtras.h:443
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:220
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:323
int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition: MathExtras.h:182
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:111
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:45
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition: MathExtras.h:166
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:202
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition: MathExtras.h:155
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:207
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:306
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:232
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:410
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:51
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition: MathExtras.h:101
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:214
uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the largest uint64_t less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:402
static const unsigned char BitReverseTable256[256]
Macro compressed bit reversal table for 256 bits.
Definition: MathExtras.h:58
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.h:539
#define S(label, offset, message)
Definition: Errors.h:119