mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 05:37:34 +00:00
AK: Add saturating addition and subtraction to Checked
This commit is contained in:
parent
746d3c1131
commit
07d712ea00
1 changed files with 22 additions and 0 deletions
22
AK/Checked.h
22
AK/Checked.h
|
@ -199,6 +199,28 @@ public:
|
||||||
m_value /= other;
|
m_value /= other;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
constexpr void saturating_sub(T other)
|
||||||
|
{
|
||||||
|
sub(other);
|
||||||
|
// Depending on whether other was positive or negative, we have to saturate to min or max.
|
||||||
|
if (m_overflow && other <= 0)
|
||||||
|
m_value = NumericLimits<T>::max();
|
||||||
|
else if (m_overflow)
|
||||||
|
m_value = NumericLimits<T>::min();
|
||||||
|
m_overflow = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr void saturating_add(T other)
|
||||||
|
{
|
||||||
|
add(other);
|
||||||
|
// Depending on whether other was positive or negative, we have to saturate to max or min.
|
||||||
|
if (m_overflow && other >= 0)
|
||||||
|
m_value = NumericLimits<T>::max();
|
||||||
|
else if (m_overflow)
|
||||||
|
m_value = NumericLimits<T>::min();
|
||||||
|
m_overflow = false;
|
||||||
|
}
|
||||||
|
|
||||||
constexpr Checked& operator+=(Checked const& other)
|
constexpr Checked& operator+=(Checked const& other)
|
||||||
{
|
{
|
||||||
m_overflow |= other.m_overflow;
|
m_overflow |= other.m_overflow;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue