From 5c339d459794dc97741a58f7951a060ed0c448e0 Mon Sep 17 00:00:00 2001 From: Oxan van Leeuwen Date: Thu, 6 Jan 2022 12:56:10 +0100 Subject: [PATCH] Convert clamp() helper to backport of std::clamp() (#3010) --- esphome/core/helpers.cpp | 11 ----------- esphome/core/helpers.h | 21 ++++++++++++--------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/esphome/core/helpers.cpp b/esphome/core/helpers.cpp index c70aa2d6dd..457c8ef37f 100644 --- a/esphome/core/helpers.cpp +++ b/esphome/core/helpers.cpp @@ -215,17 +215,6 @@ void HighFrequencyLoopRequester::stop() { } bool HighFrequencyLoopRequester::is_high_frequency() { return high_freq_num_requests > 0; } -template T clamp(const T val, const T min, const T max) { - if (val < min) - return min; - if (val > max) - return max; - return val; -} -template uint8_t clamp(uint8_t, uint8_t, uint8_t); -template float clamp(float, float, float); -template int clamp(int, int, int); - float lerp(float completion, float start, float end) { return start + (end - start) * completion; } bool str_startswith(const std::string &full, const std::string &start) { return full.rfind(start, 0) == 0; } diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 4699e8071c..bbe6b49827 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -58,15 +58,6 @@ class HighFrequencyLoopRequester { bool started_{false}; }; -/** Clamp the value between min and max. - * - * @param val The value. - * @param min The minimum value. - * @param max The maximum value. - * @return val clamped in between min and max. - */ -template T clamp(T val, T min, T max); - /** Linearly interpolate between end start and end by completion. * * @tparam T The input/output typename. @@ -277,6 +268,18 @@ using std::is_trivially_copyable; template struct is_trivially_copyable : public std::integral_constant {}; #endif +// std::clamp from C++17 +#if __cpp_lib_clamp >= 201603 +using std::clamp; +#else +template constexpr const T &clamp(const T &v, const T &lo, const T &hi, Compare comp) { + return comp(v, lo) ? lo : comp(hi, v) ? hi : v; +} +template constexpr const T &clamp(const T &v, const T &lo, const T &hi) { + return clamp(v, lo, hi, std::less{}); +} +#endif + // std::bit_cast from C++20 #if __cpp_lib_bit_cast >= 201806 using std::bit_cast;