From 07d712ea00d400a46c7480bcb4825590fb4c29c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?kleines=20Filmr=C3=B6llchen?= Date: Wed, 15 Jun 2022 21:34:25 +0200 Subject: [PATCH] AK: Add saturating addition and subtraction to Checked --- AK/Checked.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/AK/Checked.h b/AK/Checked.h index 5cf1d987f2..77d881273a 100644 --- a/AK/Checked.h +++ b/AK/Checked.h @@ -199,6 +199,28 @@ public: 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::max(); + else if (m_overflow) + m_value = NumericLimits::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::max(); + else if (m_overflow) + m_value = NumericLimits::min(); + m_overflow = false; + } + constexpr Checked& operator+=(Checked const& other) { m_overflow |= other.m_overflow;