13#ifndef WPIUTIL_WPI_MATHEXTRAS_H
14#define WPIUTIL_WPI_MATHEXTRAS_H
32template <
typename T,
typename U>
34 std::enable_if_t<std::is_integral_v<T> && std::is_integral_v<U>>;
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>>;
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");
52 return T(-1) >> (Bits - N);
58 return ~maskTrailingOnes<T>(CHAR_BIT *
sizeof(T) - N);
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)
88#if __has_builtin(__builtin_bitreverse8)
89 if constexpr (std::is_same_v<T, uint8_t>)
90 return __builtin_bitreverse8(Val);
92#if __has_builtin(__builtin_bitreverse16)
93 if constexpr (std::is_same_v<T, uint16_t>)
94 return __builtin_bitreverse16(Val);
96#if __has_builtin(__builtin_bitreverse32)
97 if constexpr (std::is_same_v<T, uint32_t>)
98 return __builtin_bitreverse32(Val);
100#if __has_builtin(__builtin_bitreverse64)
101 if constexpr (std::is_same_v<T, uint64_t>)
102 return __builtin_bitreverse64(Val);
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)
110 std::memcpy(&Val, out,
sizeof(Val));
119constexpr uint32_t
Hi_32(uint64_t Value) {
120 return static_cast<uint32_t
>(Value >> 32);
124constexpr uint32_t
Lo_32(uint64_t Value) {
125 return static_cast<uint32_t
>(Value);
129constexpr uint64_t
Make_64(uint32_t High, uint32_t Low) {
130 return ((uint64_t)High << 32) | (uint64_t)Low;
134template <
unsigned N>
constexpr bool isInt(int64_t x) {
135 if constexpr (N == 0)
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));
150template <
unsigned N,
unsigned S>
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.");
158template <
unsigned N>
constexpr bool isUInt(uint64_t x) {
159 if constexpr (N == 0)
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));
174template <
unsigned N,
unsigned S>
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.");
185 assert(N <= 64 &&
"integer width out of range");
196 return UINT64_MAX >> (64 - N);
201#pragma warning(disable : 4146)
206 assert(N >= 0 && N <= 64 &&
"integer width out of range");
210 return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
219 assert(N >= 0 && N <= 64 &&
"integer width out of range");
225 return (UINT64_C(1) << (N - 1)) - 1;
234inline bool isIntN(
unsigned N, int64_t x) {
242 return Value && ((Value + 1) & Value) == 0;
248 return Value && ((Value + 1) & Value) == 0;
254 return Value &&
isMask_32((Value - 1) | Value);
260 return Value &&
isMask_64((Value - 1) | Value);
266 return std::has_single_bit(Value);
271 return std::has_single_bit(Value);
283 MaskIdx = std::countr_zero(Value);
284 MaskLen = std::popcount(Value);
296 MaskIdx = std::countr_zero(Value);
297 MaskLen = std::popcount(Value);
303template <
size_t kValue>
constexpr size_t CTLog2() {
305 "Value is not a valid power of 2");
306 return 1 +
CTLog2<kValue / 2>();
315 return static_cast<unsigned>(31 - std::countl_zero(Value));
321 return static_cast<unsigned>(63 - std::countl_zero(Value));
328 return static_cast<unsigned>(32 - std::countl_zero(Value - 1));
334 return static_cast<unsigned>(64 - std::countl_zero(Value - 1));
339template <
typename U,
typename V,
typename T = common_u
int<U, V>>
346 return (A | B) & (1 + ~(A | B));
350constexpr uint64_t
MinAlign(uint64_t A, uint64_t B) {
351 return (A | B) & (1 + ~(A | B));
369 if (!A || A > UINT64_MAX / 2)
376template <
typename U,
typename V,
typename T = common_u
int<U, V>>
378 assert(Denominator &&
"Division by zero");
379 T Bias = (Numerator != 0);
380 return (Numerator - Bias) / Denominator + Bias;
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;
392template <
typename U,
typename V>
394 return Numerator == (std::numeric_limits<U>::min)() && Denominator == -1;
399template <
typename U,
typename V,
typename T = common_s
int<U, V>>
401 assert(Denominator &&
"Division by zero");
403 "Divide would overflow");
407 T Bias = Denominator >= 0 ? 1 : -1;
408 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
409 return SameSign ? (Numerator - Bias) / Denominator + 1
410 : Numerator / Denominator;
415template <
typename U,
typename V,
typename T = common_s
int<U, V>>
417 assert(Denominator &&
"Division by zero");
419 "Divide would overflow");
423 T Bias = Denominator >= 0 ? -1 : 1;
424 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
425 return SameSign ? Numerator / Denominator
426 : (Numerator - Bias) / Denominator - 1;
431template <
typename U,
typename V,
typename T = common_s
int<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;
440template <
typename U,
typename V,
typename T = common_u
int<U, V>>
442 assert(Denominator &&
"Division by zero");
443 T Mod = Numerator % Denominator;
444 return (Numerator / Denominator) +
445 (Mod > (
static_cast<T
>(Denominator) - 1) / 2);
460template <
typename U,
typename V,
typename T = common_u
int<U, V>>
462 assert(Align != 0u &&
"Align can't be 0.");
464 return CeilDiv * Align;
468constexpr uint64_t
alignTo(uint64_t Value, uint64_t Align) {
469 assert(Align != 0u &&
"Align can't be 0.");
471 return CeilDiv * Align;
475 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
476 "Align must be a power of 2");
479 uint64_t NegAlign = (~Align) + 1;
480 return (Value + Align - 1) & NegAlign;
497template <
typename U,
typename V,
typename W,
499constexpr T
alignTo(U Value, V Align, W Skew) {
500 assert(Align != 0u &&
"Align can't be 0.");
502 return alignTo(Value - Skew, Align) + Skew;
509template <auto Align,
typename V,
typename T = common_u
int<decltype(Align), V>>
511 static_assert(Align != 0u,
"Align must be non-zero");
513 return CeilDiv * Align;
519template <
typename U,
typename V,
typename W = uint8_t,
522 assert(Align != 0u &&
"Align can't be 0.");
524 return (Value - Skew) / Align * Align + Skew;
530 static_assert(B <= 32,
"Bit width out of range.");
531 if constexpr (B == 0)
533 return int32_t(X << (32 - B)) >> (32 - B);
539 assert(B <= 32 &&
"Bit width out of range.");
542 return int32_t(X << (32 - B)) >> (32 - B);
548 static_assert(B <= 64,
"Bit width out of range.");
549 if constexpr (B == 0)
551 return int64_t(x << (64 - B)) >> (64 - B);
557 assert(B <= 64 &&
"Bit width out of range.");
560 return int64_t(X << (64 - B)) >> (64 - B);
565template <
typename U,
typename V,
typename T = common_u
int<U, V>>
567 return X > Y ? (X - Y) : (Y - X);
574std::enable_if_t<std::is_unsigned_v<T>, T>
577 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
580 Overflowed = (Z < X || Z < Y);
582 return (std::numeric_limits<T>::max)();
589template <
class T,
class... Ts>
592 bool Overflowed =
false;
595 return SaturatingAdd((std::numeric_limits<T>::max)(), T(1), Args...);
603std::enable_if_t<std::is_unsigned_v<T>, T>
606 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
619 const T Max = (std::numeric_limits<T>::max)();
621 if (Log2Z < Log2Max) {
624 if (Log2Z > Log2Max) {
633 if (Z & ~(Max >> 1)) {
649std::enable_if_t<std::is_unsigned_v<T>, T>
652 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
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);
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;
678 Result =
static_cast<T
>(UResult);
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);
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;
704 Result =
static_cast<T
>(UResult);
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);
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;
730 const bool IsNegative = (X < 0) ^ (Y < 0);
731 Result = IsNegative ? (0 - UResult) : UResult;
734 if (UX == 0 || UY == 0)
741 return UX > (
static_cast<U
>((std::numeric_limits<T>::max)()) + U(1)) / UY;
743 return UX > (
static_cast<U
>((std::numeric_limits<T>::max)())) / UY;
749#if defined(__i386__) || defined(_M_IX86)
759 return (T(0) < val) - (val < T(0));
772constexpr T
Lerp(
const T& startValue,
const T& endValue,
double t) {
773 return startValue + (endValue - startValue) * t;
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