From 9d4f68606c919791d44e86e7a50812c29be32fa3 Mon Sep 17 00:00:00 2001 From: batsumaru <> Date: Sun, 9 Aug 2026 12:00:27 +0900 Subject: Add fp_t subtraction --- include/fixed_point.h | 1 + src/fixed_point.cpp | 4 ++++ tests/test_fixed_point.cpp | 16 ++++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/include/fixed_point.h b/include/fixed_point.h index 254bc91..1bdc5df 100644 --- a/include/fixed_point.h +++ b/include/fixed_point.h @@ -11,6 +11,7 @@ struct fp_t { static constexpr fp_t from_int(std::int32_t i) { return fp_t{i << 16}; } fp_t operator+(const fp_t& other) const; + fp_t operator-(const fp_t& other) const; bool operator==(const fp_t& other) const; }; diff --git a/src/fixed_point.cpp b/src/fixed_point.cpp index 7ff77a0..9b2d8e2 100644 --- a/src/fixed_point.cpp +++ b/src/fixed_point.cpp @@ -4,6 +4,10 @@ fp_t fp_t::operator+(const fp_t& other) const { return {(int32_t)((uint32_t)raw + (uint32_t)other.raw)}; } +fp_t fp_t::operator-(const fp_t& other) const { + return {(int32_t)((uint32_t)raw - (uint32_t)other.raw)}; +} + bool fp_t::operator==(const fp_t& other) const { return raw == other.raw; } diff --git a/tests/test_fixed_point.cpp b/tests/test_fixed_point.cpp index b3d3e78..b116340 100644 --- a/tests/test_fixed_point.cpp +++ b/tests/test_fixed_point.cpp @@ -8,9 +8,25 @@ TEST_CASE("fp_t addition is commutative") { REQUIRE(a.raw != 0); } +TEST_CASE("fp_t subtraction anti-commutative") { + fp_t a = fp_t::from_int(3); + fp_t b = fp_t::from_int(2); + fp_t c = fp_t::from_int(1); + fp_t d = fp_t::from_int(-1); + CHECK((a - b == c && b - a == d)); + REQUIRE(a.raw != 0); +} + TEST_CASE("fp_t addition overflows") { fp_t a = fp_t::from_raw(INT32_MAX); fp_t b = fp_t::from_raw(1); fp_t c = fp_t::from_raw(INT32_MIN); CHECK(a + b == c); } + +TEST_CASE("fp_t subtraction underflows") { + fp_t a = fp_t::from_raw(INT32_MIN); + fp_t b = fp_t::from_raw(1); + fp_t c = fp_t::from_raw(INT32_MAX); + CHECK(a - b == c); +} -- cgit v1.3