From baf2ad46624303332cf32f5a2b553882812379ce Mon Sep 17 00:00:00 2001 From: robert-git Date: Fri, 11 Jun 2021 01:24:18 -0500 Subject: [PATCH 1/2] Add construction tests --- test/construction.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 test/construction.cpp diff --git a/test/construction.cpp b/test/construction.cpp new file mode 100644 index 0000000..14a4019 --- /dev/null +++ b/test/construction.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include "saturating/types.hpp" + +using std::cerr; + +void test_no_overflow_on_unsigned_construction() { + uint_sat8_t s = 256; + + constexpr auto expected = 255; + + if (expected != s) + { + cerr << "failed. expected = " << expected << ", actual = " << +s << "\n"; + assert(false); + } +} + +void test_no_underflow_on_unsigned_construction() { + uint_sat8_t s = -1; + + constexpr auto expected = 0; + + if (expected != s) + { + cerr << "failed. expected = " << expected << ", actual = " << +s << "\n"; + assert(false); + } +} + +void test_no_overflow_on_signed_construction() { + int_sat8_t s = 129; + + constexpr auto expected = 127; + + if (expected != s) + { + cerr << "failed. expected = " << expected << ", actual = " << +s << "\n"; + assert(false); + } +} + +void test_no_underflow_on_signed_construction() { + int_sat8_t s = -129; + + constexpr auto expected = -128; + + if (expected != s) + { + cerr << "failed. expected = " << expected << ", actual = " << +s << "\n"; + assert(false); + } +} + +int main () { + test_no_overflow_on_unsigned_construction(); + test_no_underflow_on_unsigned_construction(); + test_no_overflow_on_signed_construction(); + test_no_underflow_on_signed_construction(); +} From a9469b4ced4e4c8e22f8c8775f838e2ec223ac03 Mon Sep 17 00:00:00 2001 From: robert-git Date: Fri, 11 Jun 2021 01:27:13 -0500 Subject: [PATCH 2/2] Update types.hpp to pass construction tests --- types.hpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/types.hpp b/types.hpp index 6f941f9..8dd9696 100644 --- a/types.hpp +++ b/types.hpp @@ -54,8 +54,15 @@ namespace saturating { /** Create a new zero-initialized saturated type. */ constexpr type() noexcept : value{0} {} - - constexpr type(const value_type& val) noexcept : value{val} {} + + template + constexpr type(const U& val) noexcept + : value{ + MAX < val ? MAX : + val < MIN ? MIN : + static_cast(val) + } + {} /** * Create a new saturating type based on a given value.