60 template <u
int64_t num, u
int64_t den,
typename ValType>
struct MuldivLimits {
68 return std::numeric_limits<ValType>::max();
78 using R = std::ratio<num, den>;
79 constexpr
auto frac = R::den / 2;
93 template <
typename ValType> __forceinline ValType
muldivMaxValue(ValType timevar, ValType num, ValType den)
95 constexpr
auto max = std::numeric_limits<ValType>::max();
97 return ValType((max - frac) / num);
109 template <
typename ValType,
typename NumDenType>
110 __forceinline ValType IRAM_ATTR
muldiv(
const ValType& value,
const NumDenType& num,
const NumDenType& den)
112 static_assert(std::is_unsigned<ValType>::value && std::is_unsigned<NumDenType>::value,
113 "muldiv types must be unsigned");
115 if(value == 0 || num == 0) {
119 constexpr
auto max = std::numeric_limits<ValType>::max();
126 auto frac = ValType(den / 2);
133 const ValType lim = (max - frac) / num;
135 if(
sizeof(ValType) <
sizeof(uint64_t)) {
137 return muldiv(uint64_t(value), num, den);
143 auto mul = num * value;
149 return (mul + frac) / den;
160 __forceinline uint32_t IRAM_ATTR
muldiv32(uint32_t value, uint32_t num, uint32_t den)
162 return muldiv(value, num, den);
173 __forceinline uint64_t IRAM_ATTR
muldiv64(
const uint64_t& value,
const uint64_t& num,
const uint64_t& den)
175 return muldiv(value, num, den);
186 template <u
int64_t num, u
int64_t den,
typename ValType> __forceinline ValType IRAM_ATTR
muldiv(
const ValType& value)
188 static_assert(std::is_unsigned<ValType>::value,
"muldiv types must be unsigned");
191 using R = std::ratio<num, den>;
193 constexpr ValType frac = R::den / 2;
194 constexpr ValType max = std::numeric_limits<ValType>::max();
196 if(value == 0 || R::num == 0) {
211 constexpr ValType lim = (max - frac) / R::num;
213 if(
sizeof(ValType) <
sizeof(uint64_t)) {
215 return muldiv<R::num, R::den>(uint64_t(value));
221 return ((value * ValType(R::num)) + frac) / ValType(R::den);
Obtain limits for a muldiv template calculation.
Definition: muldiv.h:60
uint64_t muldiv64(const uint64_t &value, const uint64_t &num, const uint64_t &den)
Perform muldiv using 64-bit values.
Definition: muldiv.h:173
ValType muldivMaxValue(ValType timevar, ValType num, ValType den)
Get the maximum value which can be passed to muldiv() without overflowing.
Definition: muldiv.h:93
static constexpr ValType maxValue()
Get the maximum value which can be used for a muldiv calculation without overflowing.
Definition: muldiv.h:75
ValType muldiv(const ValType &value, const NumDenType &num, const NumDenType &den)
Perform muldiv using unsigned integer types.
Definition: muldiv.h:110
uint32_t muldiv32(uint32_t value, uint32_t num, uint32_t den)
Perform muldiv using 32-bit values.
Definition: muldiv.h:160
static constexpr ValType overflow()
Get the value representing overflow for the given ValType.
Definition: muldiv.h:66