summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--include/fixed_point.h1
-rw-r--r--src/fixed_point.cpp4
-rw-r--r--tests/test_fixed_point.cpp16
3 files changed, 21 insertions, 0 deletions
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);
+}