Browse Source

AK: Add Checked<T>::multiplication_would_overflow()

This allows you to comfortably test if multiply 2 or 3 values would
cause arithmetic overflow.
Andreas Kling 5 years ago
parent
commit
63b8c6913c
1 changed files with 19 additions and 0 deletions
  1. 19 0
      AK/Checked.h

+ 19 - 0
AK/Checked.h

@@ -234,6 +234,25 @@ public:
         return *this;
         return *this;
     }
     }
 
 
+    template<typename U, typename V, typename X>
+    static bool multiplication_would_overflow(U u, V v)
+    {
+        Checked checked;
+        checked = u;
+        checked *= v;
+        return checked.has_overflow();
+    }
+
+    template<typename U, typename V, typename X>
+    static bool multiplication_would_overflow(U u, V v, X x)
+    {
+        Checked checked;
+        checked = u;
+        checked *= v;
+        checked *= x;
+        return checked.has_overflow();
+    }
+
 private:
 private:
     T m_value;
     T m_value;
     bool m_overflow { false };
     bool m_overflow { false };