From 5d6e3441feb2ad8c8ef1ab0068cc02b7d7ae1473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?kleines=20Filmr=C3=B6llchen?= Date: Tue, 15 Feb 2022 00:32:55 +0100 Subject: [PATCH] AK: Fix FixedPoint to integral comparisons Add tests to ensure that the fixed point numbers compare correctly to integrals --- AK/FixedPoint.h | 28 ++++------------------------ Tests/AK/TestFixedPoint.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/AK/FixedPoint.h b/AK/FixedPoint.h index 8a23f8d067..7f87935eb8 100644 --- a/AK/FixedPoint.h +++ b/AK/FixedPoint.h @@ -261,42 +261,22 @@ public: template bool operator>(I other) const { - if (m_value > 0) - return (m_value >> precision) > other || (m_value >> precision == other && (m_value & radix_mask)); - if (other > 0) - return false; - - return (m_value >> precision) > other || !(m_value >> precision == other && (m_value & radix_mask)); + return !(*this <= other); } template bool operator>=(I other) const { - if (m_value > 0) - return (m_value >> precision) >= other || (m_value >> precision == other && (m_value & radix_mask)); - if (other > 0) - return false; - - return (m_value >> precision) >= other || !(m_value >> precision == other && (m_value & radix_mask)); + return !(*this < other); } template bool operator<(I other) const { - if (m_value > 0) - return (m_value >> precision) < other || !(m_value >> precision == other && (m_value & radix_mask)); - if (other > 0) - return true; - - return (m_value >> precision) < other || (m_value >> precision == other && (m_value & radix_mask)); + return (m_value >> precision) < other || m_value < (other << precision); } template bool operator<=(I other) const { - if (m_value > 0) - return (m_value >> precision) <= other || !(m_value >> precision == other && (m_value & radix_mask)); - if (other > 0) - return true; - - return (m_value >> precision) <= other || (m_value >> precision == other && (m_value & radix_mask)); + return *this < other || *this == other; } // Casting from a float should be faster than casting to a float diff --git a/Tests/AK/TestFixedPoint.cpp b/Tests/AK/TestFixedPoint.cpp index 8127837ab0..5192f07f94 100644 --- a/Tests/AK/TestFixedPoint.cpp +++ b/Tests/AK/TestFixedPoint.cpp @@ -73,6 +73,31 @@ TEST_CASE(rounding) EXPECT_EQ(Type(-1.5).ltrunk(), -1); } +TEST_CASE(comparison) +{ + EXPECT(Type(0) < 1); + EXPECT(Type(0) <= 1); + EXPECT(Type(0) <= 0); + EXPECT(Type(-10) <= -10); + + EXPECT(Type(4.25) > 4); + EXPECT(Type(4.25) >= 4); + EXPECT(Type(4.25) <= 5); + EXPECT(Type(4.25) < 5); + EXPECT(Type(1.5) > 1); + + EXPECT(!(FixedPoint<4, u8>(2) > 128)); + EXPECT(!(FixedPoint<4, u8>(2) >= 128)); + + EXPECT(Type(-6.25) < -6); + EXPECT(Type(-6.25) <= -6); + EXPECT(Type(-6.75) > -7); + EXPECT(Type(-6.75) >= -7); + + EXPECT(Type(17) == 17); + EXPECT(Type(-8) != -9); +} + TEST_CASE(cast) { FixedPoint<16, u32> downcast_value1(FixedPoint<32, u64>(123.4567));