From bbfce66abc39c0c86767dba4f4a94db751fef0ca Mon Sep 17 00:00:00 2001 From: John Wellbelove Date: Tue, 28 May 2024 11:58:07 +0100 Subject: [PATCH] Added template parameter clamp functions --- include/etl/algorithm.h | 22 ++++++++++++++++++---- test/test_algorithm.cpp | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/include/etl/algorithm.h b/include/etl/algorithm.h index fb394f8f..844bc12f 100644 --- a/include/etl/algorithm.h +++ b/include/etl/algorithm.h @@ -2142,19 +2142,33 @@ namespace etl ///\ingroup algorithm //*************************************************************************** template - ETL_CONSTEXPR - const T& clamp(const T& value, const T& low, const T& high, TCompare compare) + ETL_CONSTEXPR + T clamp(const T& value, const T& low, const T& high, TCompare compare) { return compare(value, low) ? low : compare(high, value) ? high : value; } template - ETL_CONSTEXPR - const T& clamp(const T& value, const T& low, const T& high ) + ETL_CONSTEXPR + T clamp(const T& value, const T& low, const T& high) { return clamp(value, low, high, etl::less()); } + template + ETL_CONSTEXPR + T clamp(const T& value, TCompare compare) + { + return compare(value, Low) ? Low : compare(High, value) ? High : value; + } + + template + ETL_CONSTEXPR + T clamp(const T& value) + { + return clamp(value, etl::less()); + } + //*************************************************************************** /// Remove ///\ingroup algorithm diff --git a/test/test_algorithm.cpp b/test/test_algorithm.cpp index 875884c6..43ff2379 100644 --- a/test/test_algorithm.cpp +++ b/test/test_algorithm.cpp @@ -2384,5 +2384,41 @@ namespace data = initial; } } + + //************************************************************************* + TEST(clamp_run_time) + { + CHECK_EQUAL(5, etl::clamp(5, 0, 10)); + CHECK_EQUAL(0, etl::clamp(-5, 0, 10)); + CHECK_EQUAL(10, etl::clamp(15, 0, 10)); + } + + //************************************************************************* + TEST(clamp_compile_time) + { + CHECK_EQUAL(5, (etl::clamp(5))); + CHECK_EQUAL(0, (etl::clamp(-5))); + CHECK_EQUAL(10, (etl::clamp(15))); + } + + //************************************************************************* + TEST(clamp_constexpr) + { + constexpr int result1 = etl::clamp(5, 0, 10); + constexpr int result2 = etl::clamp(-5, 0, 10); + constexpr int result3 = etl::clamp(15, 0, 10); + + constexpr int result4 = etl::clamp(5); + constexpr int result5 = etl::clamp(-5); + constexpr int result6 = etl::clamp(15); + + CHECK_EQUAL(5, result1); + CHECK_EQUAL(0, result2); + CHECK_EQUAL(10, result3); + + CHECK_EQUAL(5, result4); + CHECK_EQUAL(0, result5); + CHECK_EQUAL(10, result6); + } }; }