mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 22:17:44 +00:00
LibAudio: Prevent overflows during prediction
Saturating arithmetic leads to less screwed up audio in these cases.
This commit is contained in:
parent
0347d04289
commit
b432674923
2 changed files with 30 additions and 4 deletions
26
AK/Checked.h
26
AK/Checked.h
|
@ -234,6 +234,24 @@ public:
|
|||
m_overflow = false;
|
||||
}
|
||||
|
||||
constexpr void saturating_mul(T other)
|
||||
{
|
||||
// Figure out if the result is positive, negative or zero beforehand.
|
||||
auto either_is_zero = this->m_value == 0 || other == 0;
|
||||
auto result_is_positive = (this->m_value > 0) == (other > 0);
|
||||
|
||||
mul(other);
|
||||
if (m_overflow) {
|
||||
if (either_is_zero)
|
||||
m_value = 0;
|
||||
else if (result_is_positive)
|
||||
m_value = NumericLimits<T>::max();
|
||||
else
|
||||
m_value = NumericLimits<T>::min();
|
||||
}
|
||||
m_overflow = false;
|
||||
}
|
||||
|
||||
constexpr Checked& operator+=(Checked const& other)
|
||||
{
|
||||
m_overflow |= other.m_overflow;
|
||||
|
@ -354,6 +372,14 @@ public:
|
|||
return checked.value();
|
||||
}
|
||||
|
||||
template<typename U, typename V>
|
||||
static constexpr T saturating_mul(U a, V b)
|
||||
{
|
||||
Checked checked { a };
|
||||
checked.saturating_mul(b);
|
||||
return checked.value();
|
||||
}
|
||||
|
||||
template<typename U, typename V>
|
||||
[[nodiscard]] static constexpr bool multiplication_would_overflow(U u, V v)
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue