Skip to content

Commit

Permalink
AK: Make Checked<T> check for division overflow as well
Browse files Browse the repository at this point in the history
Signed integer overflow can occur with division when the RHS is -1,
as the negative values' range is one larger than the positives.
  • Loading branch information
alimpfard authored and awesomekling committed May 7, 2021
1 parent df52040 commit da68c45
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions AK/Checked.h
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ class Checked {

constexpr void div(T other)
{
if constexpr (IsSigned<T>) {
// Ensure that the resulting value won't be out of range, this can only happen when dividing by -1.
if (other == -1 && m_value == NumericLimits<T>::min()) {
m_overflow = true;
return;
}
}
m_value /= other;
}

Expand Down

0 comments on commit da68c45

Please sign in to comment.